@datagrok/bio 2.27.9 → 2.27.10
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/dist/package-test.js +1 -1
- package/dist/package-test.js.map +1 -1
- package/dist/package.js +1 -1
- package/dist/package.js.map +1 -1
- package/files/demo-files/SIRNA.layout +659 -841
- package/package.json +1 -1
- package/src/demo/feature_demos.ts +5 -0
- package/test-console-output-1.log +511 -495
- package/test-record-1.mp4 +0 -0
package/dist/package-test.js
CHANGED
|
@@ -4,5 +4,5 @@ var bio_test;(()=>{var e,t,n={8924(e,t,n){"use strict";n.d(t,{X:()=>o});var i=n(
|
|
|
4
4
|
|| ${a} === "boolean" || ${o} === null`).assign(l,r._`[${o}]`)}}i.else(),p(e),i.endIf(),i.if(r._`${l} !== undefined`,()=>{i.assign(o,l),function({gen:e,parentData:t,parentDataProperty:n},i){e.if(r._`${t} !== undefined`,()=>e.assign(r._`${t}[${n}]`,i))}(e,l)})}(e,t,a):p(e)})}return c};const u=new Set(["string","number","integer","boolean","null"]);function h(e,t,n,i=l.Correct){const o=i===l.Correct?r.operators.EQ:r.operators.NEQ;let s;switch(e){case"null":return r._`${t} ${o} null`;case"array":s=r._`Array.isArray(${t})`;break;case"object":s=r._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=a(r._`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=a();break;default:return r._`typeof ${t} ${o} ${e}`}return i===l.Correct?s:(0,r.not)(s);function a(e=r.nil){return(0,r.and)(r._`typeof ${t} == "number"`,e,n?r._`isFinite(${t})`:r.nil)}}function d(e,t,n,i){if(1===e.length)return h(e[0],t,n,i);let o;const s=(0,a.toHash)(e);if(s.array&&s.object){const e=r._`typeof ${t} != "object"`;o=s.null?e:r._`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=r.nil;s.number&&delete s.integer;for(const e in s)o=(0,r.and)(o,h(e,t,n,i));return o}t.checkDataType=h,t.checkDataTypes=d;const m={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?r._`{type: ${e}}`:r._`{type: ${t}}`};function p(e){const t=function(e){const{gen:t,data:n,schema:i}=e,o=(0,a.schemaRefOrVal)(e,i,"type");return{gen:t,keyword:"type",data:n,schema:i.type,schemaCode:o,schemaValue:o,parentSchema:i,params:{},it:e}}(e);(0,s.reportError)(t,m)}t.reportTypeError=p},7870(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assignDefaults=void 0;const i=n(9029),o=n(4227);function s(e,t,n){const{gen:s,compositeRule:r,data:a,opts:l}=e;if(void 0===n)return;const c=i._`${a}${(0,i.getProperty)(t)}`;if(r)return void(0,o.checkStrictMode)(e,`default is ignored for: ${c}`);let u=i._`${c} === undefined`;"empty"===l.useDefaults&&(u=i._`${u} || ${c} === null || ${c} === ""`),s.if(u,i._`${c} = ${(0,i.stringify)(n)}`)}t.assignDefaults=function(e,t){const{properties:n,items:i}=e.schema;if("object"===t&&n)for(const t in n)s(e,t,n[t].default);else"array"===t&&Array.isArray(i)&&i.forEach((t,n)=>s(e,n,t.default))}},2586(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getData=t.KeywordCxt=t.validateFunctionCode=void 0;const i=n(8727),o=n(208),s=n(7887),r=n(208),a=n(7870),l=n(3673),c=n(4495),u=n(9029),h=n(2023),d=n(6939),m=n(4227),p=n(8708);function g({gen:e,validateName:t,schema:n,schemaEnv:i,opts:o},s){o.code.es5?e.func(t,u._`${h.default.data}, ${h.default.valCxt}`,i.$async,()=>{e.code(u._`"use strict"; ${f(n,o)}`),function(e,t){e.if(h.default.valCxt,()=>{e.var(h.default.instancePath,u._`${h.default.valCxt}.${h.default.instancePath}`),e.var(h.default.parentData,u._`${h.default.valCxt}.${h.default.parentData}`),e.var(h.default.parentDataProperty,u._`${h.default.valCxt}.${h.default.parentDataProperty}`),e.var(h.default.rootData,u._`${h.default.valCxt}.${h.default.rootData}`),t.dynamicRef&&e.var(h.default.dynamicAnchors,u._`${h.default.valCxt}.${h.default.dynamicAnchors}`)},()=>{e.var(h.default.instancePath,u._`""`),e.var(h.default.parentData,u._`undefined`),e.var(h.default.parentDataProperty,u._`undefined`),e.var(h.default.rootData,h.default.data),t.dynamicRef&&e.var(h.default.dynamicAnchors,u._`{}`)})}(e,o),e.code(s)}):e.func(t,u._`${h.default.data}, ${function(e){return u._`{${h.default.instancePath}="", ${h.default.parentData}, ${h.default.parentDataProperty}, ${h.default.rootData}=${h.default.data}${e.dynamicRef?u._`, ${h.default.dynamicAnchors}={}`:u.nil}}={}`}(o)}`,i.$async,()=>e.code(f(n,o)).code(s))}function f(e,t){const n="object"==typeof e&&e[t.schemaId];return n&&(t.code.source||t.code.process)?u._`/*# sourceURL=${n} */`:u.nil}function y({schema:e,self:t}){if("boolean"==typeof e)return!e;for(const n in e)if(t.RULES.all[n])return!0;return!1}function b(e){return"boolean"!=typeof e.schema}function w(e){(0,m.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:n,opts:i,self:o}=e;t.$ref&&i.ignoreKeywordsWithRef&&(0,m.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}(e)}function v(e,t){if(e.opts.jtd)return A(e,[],!1,t);const n=(0,o.getSchemaTypes)(e.schema);A(e,n,!(0,o.coerceAndCheckDataType)(e,n),t)}function C({gen:e,schemaEnv:t,schema:n,errSchemaPath:i,opts:o}){const s=n.$comment;if(!0===o.$comment)e.code(u._`${h.default.self}.logger.log(${s})`);else if("function"==typeof o.$comment){const n=u.str`${i}/$comment`,o=e.scopeValue("root",{ref:t.root});e.code(u._`${h.default.self}.opts.$comment(${s}, ${n}, ${o}.schema)`)}}function A(e,t,n,i){const{gen:o,schema:a,data:l,allErrors:c,opts:d,self:p}=e,{RULES:g}=p;function f(m){(0,s.shouldUseGroup)(a,m)&&(m.type?(o.if((0,r.checkDataType)(m.type,l,d.strictNumbers)),T(e,m),1===t.length&&t[0]===m.type&&n&&(o.else(),(0,r.reportTypeError)(e)),o.endIf()):T(e,m),c||o.if(u._`${h.default.errors} === ${i||0}`))}!a.$ref||!d.ignoreKeywordsWithRef&&(0,m.schemaHasRulesButRef)(a,g)?(d.jtd||function(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(function(e,t){t.length&&(e.dataTypes.length?(t.forEach(t=>{E(e.dataTypes,t)||S(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){const n=[];for(const i of e.dataTypes)E(t,i)?n.push(i):t.includes("integer")&&"number"===i&&n.push("integer");e.dataTypes=n}(e,t)):e.dataTypes=t)}(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&S(e,"use allowUnionTypes to allow union type keyword")}(e,t),function(e,t){const n=e.self.RULES.all;for(const i in n){const o=n[i];if("object"==typeof o&&(0,s.shouldUseRule)(e.schema,o)){const{type:n}=o.definition;n.length&&!n.some(e=>{return i=e,(n=t).includes(i)||"number"===i&&n.includes("integer");var n,i})&&S(e,`missing type "${n.join(",")}" for keyword "${i}"`)}}}(e,e.dataTypes))}(e,t),o.block(()=>{for(const e of g.rules)f(e);f(g.post)})):o.block(()=>x(e,"$ref",g.all.$ref.definition))}function T(e,t){const{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(const n of t.rules)(0,s.shouldUseRule)(i,n)&&x(e,n.keyword,n.definition,t.type)})}function E(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function S(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,m.checkStrictMode)(e,t,e.opts.strictTypes)}t.validateFunctionCode=function(e){b(e)&&(w(e),y(e))?function(e){const{schema:t,opts:n,gen:i}=e;g(e,()=>{n.$comment&&t.$comment&&C(e),function(e){const{schema:t,opts:n}=e;void 0!==t.default&&n.useDefaults&&n.strictSchema&&(0,m.checkStrictMode)(e,"default is ignored in the schema root")}(e),i.let(h.default.vErrors,null),i.let(h.default.errors,0),n.unevaluated&&function(e){const{gen:t,validateName:n}=e;e.evaluated=t.const("evaluated",u._`${n}.evaluated`),t.if(u._`${e.evaluated}.dynamicProps`,()=>t.assign(u._`${e.evaluated}.props`,u._`undefined`)),t.if(u._`${e.evaluated}.dynamicItems`,()=>t.assign(u._`${e.evaluated}.items`,u._`undefined`))}(e),v(e),function(e){const{gen:t,schemaEnv:n,validateName:i,ValidationError:o,opts:s}=e;n.$async?t.if(u._`${h.default.errors} === 0`,()=>t.return(h.default.data),()=>t.throw(u._`new ${o}(${h.default.vErrors})`)):(t.assign(u._`${i}.errors`,h.default.vErrors),s.unevaluated&&function({gen:e,evaluated:t,props:n,items:i}){n instanceof u.Name&&e.assign(u._`${t}.props`,n),i instanceof u.Name&&e.assign(u._`${t}.items`,i)}(e),t.return(u._`${h.default.errors} === 0`))}(e)})}(e):g(e,()=>(0,i.topBoolOrEmptySchema)(e))};class M{constructor(e,t,n){if((0,l.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,m.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",I(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,l.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",h.default.errors))}result(e,t,n){this.failResult((0,u.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,u.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail(u._`${t} !== undefined && (${(0,u.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t)return this.setParams(t),this._error(e,n),void this.setParams({});this._error(e,n)}_error(e,t){(e?p.reportExtraError:p.reportError)(this,this.def.error,t)}$dataError(){(0,p.reportError)(this,this.def.$dataError||p.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,p.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=u.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=u.nil,t=u.nil){if(!this.$data)return;const{gen:n,schemaCode:i,schemaType:o,def:s}=this;n.if((0,u.or)(u._`${i} === undefined`,t)),e!==u.nil&&n.assign(e,!0),(o.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==u.nil&&n.assign(e,!1)),n.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:n,def:i,it:o}=this;return(0,u.or)(function(){if(n.length){if(!(t instanceof u.Name))throw new Error("ajv implementation error");const e=Array.isArray(n)?n:[n];return u._`${(0,r.checkDataTypes)(e,t,o.opts.strictNumbers,r.DataType.Wrong)}`}return u.nil}(),function(){if(i.validateSchema){const n=e.scopeValue("validate$data",{ref:i.validateSchema});return u._`!${n}(${t})`}return u.nil}())}subschema(e,t){const n=(0,c.getSubschema)(this.it,e);(0,c.extendSubschemaData)(n,this.it,e),(0,c.extendSubschemaMode)(n,e);const o={...this.it,...n,items:void 0,props:void 0};return function(e,t){b(e)&&(w(e),y(e))?function(e,t){const{schema:n,gen:i,opts:o}=e;o.$comment&&n.$comment&&C(e),function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,d.resolveUrl)(e.opts.uriResolver,e.baseId,t))}(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const s=i.const("_errs",h.default.errors);v(e,s),i.var(t,u._`${s} === ${h.default.errors}`)}(e,t):(0,i.boolOrEmptySchema)(e,t)}(o,t),o}mergeEvaluated(e,t){const{it:n,gen:i}=this;n.opts.unevaluated&&(!0!==n.props&&void 0!==e.props&&(n.props=m.mergeEvaluated.props(i,e.props,n.props,t)),!0!==n.items&&void 0!==e.items&&(n.items=m.mergeEvaluated.items(i,e.items,n.items,t)))}mergeValidEvaluated(e,t){const{it:n,gen:i}=this;if(n.opts.unevaluated&&(!0!==n.props||!0!==n.items))return i.if(t,()=>this.mergeEvaluated(e,u.Name)),!0}}function x(e,t,n,i){const o=new M(e,n,t);"code"in n?n.code(o,i):o.$data&&n.validate?(0,l.funcKeywordCode)(o,n):"macro"in n?(0,l.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,l.funcKeywordCode)(o,n)}t.KeywordCxt=M;const P=/^\/(?:[^~]|~0|~1)*$/,L=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function I(e,{dataLevel:t,dataNames:n,dataPathArr:i}){let o,s;if(""===e)return h.default.rootData;if("/"===e[0]){if(!P.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=h.default.rootData}else{const r=L.exec(e);if(!r)throw new Error(`Invalid JSON-pointer: ${e}`);const a=+r[1];if(o=r[2],"#"===o){if(a>=t)throw new Error(l("property/index",a));return i[t-a]}if(a>t)throw new Error(l("data",a));if(s=n[t-a],!o)return s}let r=s;const a=o.split("/");for(const e of a)e&&(s=u._`${s}${(0,u.getProperty)((0,m.unescapeJsonPointer)(e))}`,r=u._`${r} && ${s}`);return r;function l(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}t.getData=I},3673(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateKeywordUsage=t.validSchemaType=t.funcKeywordCode=t.macroKeywordCode=void 0;const i=n(9029),o=n(2023),s=n(5765),r=n(8708);function a(e){const{gen:t,data:n,it:o}=e;t.if(o.parentData,()=>t.assign(n,i._`${o.parentData}[${o.parentDataProperty}]`))}function l(e,t,n){if(void 0===n)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword","function"==typeof n?{ref:n}:{ref:n,code:(0,i.stringify)(n)})}t.macroKeywordCode=function(e,t){const{gen:n,keyword:o,schema:s,parentSchema:r,it:a}=e,c=t.macro.call(a.self,s,r,a),u=l(n,o,c);!1!==a.opts.validateSchema&&a.self.validateSchema(c,!0);const h=n.name("valid");e.subschema({schema:c,schemaPath:i.nil,errSchemaPath:`${a.errSchemaPath}/${o}`,topSchemaRef:u,compositeRule:!0},h),e.pass(h,()=>e.error(!0))},t.funcKeywordCode=function(e,t){var n;const{gen:c,keyword:u,schema:h,parentSchema:d,$data:m,it:p}=e;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(p,t);const g=!m&&t.compile?t.compile.call(p.self,h,d,p):t.validate,f=l(c,u,g),y=c.let("valid");function b(n=(t.async?i._`await `:i.nil)){const r=p.opts.passContext?o.default.this:o.default.self,a=!("compile"in t&&!m||!1===t.schema);c.assign(y,i._`${n}${(0,s.callValidateCode)(e,f,r,a)}`,t.modifying)}function w(e){var n;c.if((0,i.not)(null!==(n=t.valid)&&void 0!==n?n:y),e)}e.block$data(y,function(){if(!1===t.errors)b(),t.modifying&&a(e),w(()=>e.error());else{const n=t.async?function(){const e=c.let("ruleErrs",null);return c.try(()=>b(i._`await `),t=>c.assign(y,!1).if(i._`${t} instanceof ${p.ValidationError}`,()=>c.assign(e,i._`${t}.errors`),()=>c.throw(t))),e}():function(){const e=i._`${f}.errors`;return c.assign(e,null),b(i.nil),e}();t.modifying&&a(e),w(()=>function(e,t){const{gen:n}=e;n.if(i._`Array.isArray(${t})`,()=>{n.assign(o.default.vErrors,i._`${o.default.vErrors} === null ? ${t} : ${o.default.vErrors}.concat(${t})`).assign(o.default.errors,i._`${o.default.vErrors}.length`),(0,r.extendErrors)(e)},()=>e.error())}(e,n))}}),e.ok(null!==(n=t.valid)&&void 0!==n?n:y)},t.validSchemaType=function(e,t,n=!1){return!t.length||t.some(t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||n&&void 0===e)},t.validateKeywordUsage=function({schema:e,opts:t,self:n,errSchemaPath:i},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");const r=o.dependencies;if(null==r?void 0:r.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw new Error(`parent schema must have dependencies of ${s}: ${r.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[s])){const e=`keyword "${s}" value is invalid at path "${i}": `+n.errorsText(o.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);n.logger.error(e)}}},4495(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.extendSubschemaMode=t.extendSubschemaData=t.getSubschema=void 0;const i=n(9029),o=n(4227);t.getSubschema=function(e,{keyword:t,schemaProp:n,schema:s,schemaPath:r,errSchemaPath:a,topSchemaRef:l}){if(void 0!==t&&void 0!==s)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==t){const s=e.schema[t];return void 0===n?{schema:s,schemaPath:i._`${e.schemaPath}${(0,i.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:s[n],schemaPath:i._`${e.schemaPath}${(0,i.getProperty)(t)}${(0,i.getProperty)(n)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,o.escapeFragment)(n)}`}}if(void 0!==s){if(void 0===r||void 0===a||void 0===l)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:s,schemaPath:r,topSchemaRef:l,errSchemaPath:a}}throw new Error('either "keyword" or "schema" must be passed')},t.extendSubschemaData=function(e,t,{dataProp:n,dataPropType:s,data:r,dataTypes:a,propertyName:l}){if(void 0!==r&&void 0!==n)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:c}=t;if(void 0!==n){const{errorPath:r,dataPathArr:a,opts:l}=t;u(c.let("data",i._`${t.data}${(0,i.getProperty)(n)}`,!0)),e.errorPath=i.str`${r}${(0,o.getErrorPath)(n,s,l.jsPropertySyntax)}`,e.parentDataProperty=i._`${n}`,e.dataPathArr=[...a,e.parentDataProperty]}function u(n){e.data=n,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,n]}void 0!==r&&(u(r instanceof i.Name?r:c.let("data",r,!0)),void 0!==l&&(e.propertyName=l)),a&&(e.dataTypes=a)},t.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:i,createErrors:o,allErrors:s}){void 0!==i&&(e.compositeRule=i),void 0!==o&&(e.createErrors=o),void 0!==s&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=n}},4042(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var i=n(2586);Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return i.KeywordCxt}});var o=n(9029);Object.defineProperty(t,"_",{enumerable:!0,get:function(){return o._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return o.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return o.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return o.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return o.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return o.CodeGen}});const s=n(3558),r=n(4551),a=n(396),l=n(3835),c=n(9029),u=n(6939),h=n(208),d=n(4227),m=n(3837),p=n(5944),g=(e,t)=>new RegExp(e,t);g.code="new RegExp";const f=["removeAdditional","useDefaults","coerceTypes"],y=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),b={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},w={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function v(e){var t,n,i,o,s,r,a,l,c,u,h,d,m,f,y,b,w,v,C,A,T,E,S,M,x;const P=e.strict,L=null===(t=e.code)||void 0===t?void 0:t.optimize,I=!0===L||void 0===L?1:L||0,_=null!==(i=null===(n=e.code)||void 0===n?void 0:n.regExp)&&void 0!==i?i:g,N=null!==(o=e.uriResolver)&&void 0!==o?o:p.default;return{strictSchema:null===(r=null!==(s=e.strictSchema)&&void 0!==s?s:P)||void 0===r||r,strictNumbers:null===(l=null!==(a=e.strictNumbers)&&void 0!==a?a:P)||void 0===l||l,strictTypes:null!==(u=null!==(c=e.strictTypes)&&void 0!==c?c:P)&&void 0!==u?u:"log",strictTuples:null!==(d=null!==(h=e.strictTuples)&&void 0!==h?h:P)&&void 0!==d?d:"log",strictRequired:null!==(f=null!==(m=e.strictRequired)&&void 0!==m?m:P)&&void 0!==f&&f,code:e.code?{...e.code,optimize:I,regExp:_}:{optimize:I,regExp:_},loopRequired:null!==(y=e.loopRequired)&&void 0!==y?y:200,loopEnum:null!==(b=e.loopEnum)&&void 0!==b?b:200,meta:null===(w=e.meta)||void 0===w||w,messages:null===(v=e.messages)||void 0===v||v,inlineRefs:null===(C=e.inlineRefs)||void 0===C||C,schemaId:null!==(A=e.schemaId)&&void 0!==A?A:"$id",addUsedSchema:null===(T=e.addUsedSchema)||void 0===T||T,validateSchema:null===(E=e.validateSchema)||void 0===E||E,validateFormats:null===(S=e.validateFormats)||void 0===S||S,unicodeRegExp:null===(M=e.unicodeRegExp)||void 0===M||M,int32range:null===(x=e.int32range)||void 0===x||x,uriResolver:N}}class C{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};const{es5:t,lines:n}=this.opts.code;this.scope=new c.ValueScope({scope:{},prefixes:y,es5:t,lines:n}),this.logger=function(e){if(!1===e)return P;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}(e.logger);const i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),A.call(this,b,e,"NOT SUPPORTED"),A.call(this,w,e,"DEPRECATED","warn"),this._metaOpts=x.call(this),e.formats&&S.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&M.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),E.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:n}=this.opts;let i=m;"id"===n&&(i={...m},i.id=i.$id,delete i.$id),t&&e&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){const{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let n;if("string"==typeof e){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);const i=n(t);return"$async"in n||(this.errors=n.errors),i}compile(e,t){const n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw new Error("options.loadSchema should be a function");const{loadSchema:n}=this.opts;return i.call(this,e,t);async function i(e,t){await o.call(this,e.$schema);const n=this._addSchema(e,t);return n.validate||s.call(this,n)}async function o(e){e&&!this.getSchema(e)&&await i.call(this,{$ref:e},!0)}async function s(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof r.default))throw t;return a.call(this,t),await l.call(this,t.missingSchema),s.call(this,e)}}function a({missingSchema:e,missingRef:t}){if(this.refs[e])throw new Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function l(e){const n=await c.call(this,e);this.refs[e]||await o.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function c(e){const t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,i=this.opts.validateSchema){if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,n,i);return this}let o;if("object"==typeof e){const{schemaId:t}=this.opts;if(o=e[t],void 0!==o&&"string"!=typeof o)throw new Error(`schema ${t} must be string`)}return t=(0,u.normalizeId)(t||o),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,i,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let n;if(n=e.$schema,void 0!==n&&"string"!=typeof n)throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const i=this.validate(n,e);if(!i&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return i}getSchema(e){let t;for(;"string"==typeof(t=T.call(this,e));)e=t;if(void 0===t){const{schemaId:n}=this.opts,i=new l.SchemaEnv({schema:{},schemaId:n});if(t=l.resolveSchema.call(this,i,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const t=T.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{const t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,u.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(const t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if("string"==typeof e)n=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=n);else{if("object"!=typeof e||void 0!==t)throw new Error("invalid addKeywords parameters");if(n=(t=e).keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}if(I.call(this,n,t),!t)return(0,d.eachItem)(n,e=>_.call(this,e)),this;R.call(this,t);const i={...t,type:(0,h.getJSONTypes)(t.type),schemaType:(0,h.getJSONTypes)(t.schemaType)};return(0,d.eachItem)(n,0===i.type.length?e=>_.call(this,e,i):e=>i.type.forEach(t=>_.call(this,e,i,t))),this}getKeyword(e){const t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){const{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(const n of t.rules){const t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:n="data"}={}){return e&&0!==e.length?e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n):"No errors"}$dataMetaSchema(e,t){const n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(const i of t){const t=i.split("/").slice(1);let o=e;for(const e of t)o=o[e];for(const e in n){const t=n[e];if("object"!=typeof t)continue;const{$data:i}=t.definition,s=o[e];i&&s&&(o[e]=O(s))}}return e}_removeAllSchemas(e,t){for(const n in e){const i=e[n];t&&!t.test(n)||("string"==typeof i?delete e[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[n]))}}_addSchema(e,t,n,i=this.opts.validateSchema,o=this.opts.addUsedSchema){let s;const{schemaId:r}=this.opts;if("object"==typeof e)s=e[r];else{if(this.opts.jtd)throw new Error("schema must be object");if("boolean"!=typeof e)throw new Error("schema must be object or boolean")}let a=this._cache.get(e);if(void 0!==a)return a;n=(0,u.normalizeId)(s||n);const c=u.getSchemaRefs.call(this,e,n);return a=new l.SchemaEnv({schema:e,schemaId:r,meta:t,baseId:n,localRefs:c}),this._cache.set(a.schema,a),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=a),i&&this.validateSchema(e,!0),a}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):l.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){const t=this.opts;this.opts=this._metaOpts;try{l.compileSchema.call(this,e)}finally{this.opts=t}}}function A(e,t,n,i="error"){for(const o in e){const s=o;s in t&&this.logger[i](`${n}: option ${o}. ${e[s]}`)}}function T(e){return e=(0,u.normalizeId)(e),this.schemas[e]||this.refs[e]}function E(){const e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(const t in e)this.addSchema(e[t],t)}function S(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function M(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(const t in e){const n=e[t];n.keyword||(n.keyword=t),this.addKeyword(n)}}}function x(){const e={...this.opts};for(const t of f)delete e[t];return e}C.ValidationError=s.default,C.MissingRefError=r.default,t.default=C;const P={log(){},warn(){},error(){}},L=/^[a-z_$][a-z0-9_$:-]*$/i;function I(e,t){const{RULES:n}=this;if((0,d.eachItem)(e,e=>{if(n.keywords[e])throw new Error(`Keyword ${e} is already defined`);if(!L.test(e))throw new Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!("code"in t)&&!("validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function _(e,t,n){var i;const o=null==t?void 0:t.post;if(n&&o)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:s}=this;let r=o?s.post:s.rules.find(({type:e})=>e===n);if(r||(r={type:n,rules:[]},s.rules.push(r)),s.keywords[e]=!0,!t)return;const a={keyword:e,definition:{...t,type:(0,h.getJSONTypes)(t.type),schemaType:(0,h.getJSONTypes)(t.schemaType)}};t.before?N.call(this,r,a,t.before):r.rules.push(a),s.all[e]=a,null===(i=t.implements)||void 0===i||i.forEach(e=>this.addKeyword(e))}function N(e,t,n){const i=e.rules.findIndex(e=>e.keyword===n);i>=0?e.rules.splice(i,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function R(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=O(t)),e.validateSchema=this.compile(t,!0))}const $={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function O(e){return{anyOf:[e,$]}}},9572(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(1678),o=n(7216),s=n(9547),r=n(8226),a=n(518),l=n(4588),c=n(5707),u=n(7082),h=["/properties"];t.default=function(e){return[i,o,s,r,a,t(this,l),c,t(this,u)].forEach(e=>this.addMetaSchema(e,void 0,!1)),this;function t(t,n){return e?t.$dataMetaSchema(n,h):n}}},6250(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(2017);i.code='require("ajv/dist/runtime/equal").default',t.default=i},3853(e,t){"use strict";function n(e){const t=e.length;let n,i=0,o=0;for(;o<t;)i++,n=e.charCodeAt(o++),n>=55296&&n<=56319&&o<t&&(n=e.charCodeAt(o),56320==(64512&n)&&o++);return i}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n,n.code='require("ajv/dist/runtime/ucs2length").default'},5944(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(8343);i.code='require("ajv/dist/runtime/uri").default',t.default=i},3558(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});class n extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}t.default=n},5457(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateAdditionalItems=void 0;const i=n(9029),o=n(4227),s={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:e}})=>i.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>i._`{limit: ${e}}`},code(e){const{parentSchema:t,it:n}=e,{items:i}=t;Array.isArray(i)?r(e,i):(0,o.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas')}};function r(e,t){const{gen:n,schema:s,data:r,keyword:a,it:l}=e;l.items=!0;const c=n.const("len",i._`${r}.length`);if(!1===s)e.setParams({len:t.length}),e.pass(i._`${c} <= ${t.length}`);else if("object"==typeof s&&!(0,o.alwaysValidSchema)(l,s)){const s=n.var("valid",i._`${c} <= ${t.length}`);n.if((0,i.not)(s),()=>function(s){n.forRange("i",t.length,c,t=>{e.subschema({keyword:a,dataProp:t,dataPropType:o.Type.Num},s),l.allErrors||n.if((0,i.not)(s),()=>n.break())})}(s)),e.ok(s)}}t.validateAdditionalItems=r,t.default=s},8660(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(5765),o=n(9029),s=n(2023),r=n(4227),a={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:e})=>o._`{additionalProperty: ${e.additionalProperty}}`},code(e){const{gen:t,schema:n,parentSchema:a,data:l,errsCount:c,it:u}=e;if(!c)throw new Error("ajv implementation error");const{allErrors:h,opts:d}=u;if(u.props=!0,"all"!==d.removeAdditional&&(0,r.alwaysValidSchema)(u,n))return;const m=(0,i.allSchemaProperties)(a.properties),p=(0,i.allSchemaProperties)(a.patternProperties);function g(e){t.code(o._`delete ${l}[${e}]`)}function f(i){if("all"===d.removeAdditional||d.removeAdditional&&!1===n)g(i);else{if(!1===n)return e.setParams({additionalProperty:i}),e.error(),void(h||t.break());if("object"==typeof n&&!(0,r.alwaysValidSchema)(u,n)){const n=t.name("valid");"failing"===d.removeAdditional?(y(i,n,!1),t.if((0,o.not)(n),()=>{e.reset(),g(i)})):(y(i,n),h||t.if((0,o.not)(n),()=>t.break()))}}}function y(t,n,i){const o={keyword:"additionalProperties",dataProp:t,dataPropType:r.Type.Str};!1===i&&Object.assign(o,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(o,n)}t.forIn("key",l,n=>{m.length||p.length?t.if(function(n){let s;if(m.length>8){const e=(0,r.schemaRefOrVal)(u,a.properties,"properties");s=(0,i.isOwnProperty)(t,e,n)}else s=m.length?(0,o.or)(...m.map(e=>o._`${n} === ${e}`)):o.nil;return p.length&&(s=(0,o.or)(s,...p.map(t=>o._`${(0,i.usePattern)(e,t)}.test(${n})`))),(0,o.not)(s)}(n),()=>f(n)):f(n)}),e.ok(o._`${c} === ${s.default.errors}`)}};t.default=a},5844(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(4227),o={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:n,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");const s=t.name("valid");n.forEach((t,n)=>{if((0,i.alwaysValidSchema)(o,t))return;const r=e.subschema({keyword:"allOf",schemaProp:n},s);e.ok(s),e.mergeEvaluated(r)})}};t.default=o},6505(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:n(5765).validateUnion,error:{message:"must match a schema in anyOf"}};t.default=i},2661(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(4227),s={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:t}})=>void 0===t?i.str`must contain at least ${e} valid item(s)`:i.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>void 0===t?i._`{minContains: ${e}}`:i._`{minContains: ${e}, maxContains: ${t}}`},code(e){const{gen:t,schema:n,parentSchema:s,data:r,it:a}=e;let l,c;const{minContains:u,maxContains:h}=s;a.opts.next?(l=void 0===u?1:u,c=h):l=1;const d=t.const("len",i._`${r}.length`);if(e.setParams({min:l,max:c}),void 0===c&&0===l)return void(0,o.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==c&&l>c)return(0,o.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),void e.fail();if((0,o.alwaysValidSchema)(a,n)){let t=i._`${d} >= ${l}`;return void 0!==c&&(t=i._`${t} && ${d} <= ${c}`),void e.pass(t)}a.items=!0;const m=t.name("valid");function p(){const e=t.name("_valid"),n=t.let("count",0);g(e,()=>t.if(e,()=>function(e){t.code(i._`${e}++`),void 0===c?t.if(i._`${e} >= ${l}`,()=>t.assign(m,!0).break()):(t.if(i._`${e} > ${c}`,()=>t.assign(m,!1).break()),1===l?t.assign(m,!0):t.if(i._`${e} >= ${l}`,()=>t.assign(m,!0)))}(n)))}function g(n,i){t.forRange("i",0,d,t=>{e.subschema({keyword:"contains",dataProp:t,dataPropType:o.Type.Num,compositeRule:!0},n),i()})}void 0===c&&1===l?g(m,()=>t.if(m,()=>t.break())):0===l?(t.let(m,!0),void 0!==c&&t.if(i._`${r}.length > 0`,p)):(t.let(m,!1),p()),e.result(m,()=>e.reset())}};t.default=s},3025(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const i=n(9029),o=n(4227),s=n(5765);t.error={message:({params:{property:e,depsCount:t,deps:n}})=>{const o=1===t?"property":"properties";return i.str`must have ${o} ${n} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:n,missingProperty:o}})=>i._`{property: ${e},
|
|
5
5
|
missingProperty: ${o},
|
|
6
6
|
depsCount: ${t},
|
|
7
|
-
deps: ${n}}`};const r={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(e){const[t,n]=function({schema:e}){const t={},n={};for(const i in e)"__proto__"!==i&&((Array.isArray(e[i])?t:n)[i]=e[i]);return[t,n]}(e);a(e,t),l(e,n)}};function a(e,t=e.schema){const{gen:n,data:o,it:r}=e;if(0===Object.keys(t).length)return;const a=n.let("missing");for(const l in t){const c=t[l];if(0===c.length)continue;const u=(0,s.propertyInData)(n,o,l,r.opts.ownProperties);e.setParams({property:l,depsCount:c.length,deps:c.join(", ")}),r.allErrors?n.if(u,()=>{for(const t of c)(0,s.checkReportMissingProp)(e,t)}):(n.if(i._`${u} && (${(0,s.checkMissingProp)(e,c,a)})`),(0,s.reportMissingProp)(e,a),n.else())}}function l(e,t=e.schema){const{gen:n,data:i,keyword:r,it:a}=e,l=n.name("valid");for(const c in t)(0,o.alwaysValidSchema)(a,t[c])||(n.if((0,s.propertyInData)(n,i,c,a.opts.ownProperties),()=>{const t=e.subschema({keyword:r,schemaProp:c},l);e.mergeValidEvaluated(t,l)},()=>n.var(l,!0)),e.ok(l))}t.validatePropertyDeps=a,t.validateSchemaDeps=l,t.default=r},4845(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(3025),o={keyword:"dependentSchemas",type:"object",schemaType:"object",code:e=>(0,i.validateSchemaDeps)(e)};t.default=o},1239(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(4227),s={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:e})=>i.str`must match "${e.ifClause}" schema`,params:({params:e})=>i._`{failingKeyword: ${e.ifClause}}`},code(e){const{gen:t,parentSchema:n,it:s}=e;void 0===n.then&&void 0===n.else&&(0,o.checkStrictMode)(s,'"if" without "then" and "else" is ignored');const a=r(s,"then"),l=r(s,"else");if(!a&&!l)return;const c=t.let("valid",!0),u=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}(),e.reset(),a&&l){const n=t.let("ifClause");e.setParams({ifClause:n}),t.if(u,h("then",n),h("else",n))}else a?t.if(u,h("then")):t.if((0,i.not)(u),h("else"));function h(n,o){return()=>{const s=e.subschema({keyword:n},u);t.assign(c,u),e.mergeValidEvaluated(s,c),o?t.assign(o,i._`${n}`):e.setParams({ifClause:n})}}e.pass(c,()=>e.error(!0))}};function r(e,t){const n=e.schema[t];return void 0!==n&&!(0,o.alwaysValidSchema)(e,n)}t.default=s},6378(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(5457),o=n(5354),s=n(494),r=n(3966),a=n(2661),l=n(3025),c=n(2094),u=n(8660),h=n(117),d=n(5333),m=n(7923),p=n(6505),g=n(6163),f=n(5844),y=n(1239),b=n(4426);t.default=function(e=!1){const t=[m.default,p.default,g.default,f.default,y.default,b.default,c.default,u.default,l.default,h.default,d.default];return e?t.push(o.default,r.default):t.push(i.default,s.default),t.push(a.default),t}},494(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateTuple=void 0;const i=n(9029),o=n(4227),s=n(5765),r={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:n}=e;if(Array.isArray(t))return a(e,"additionalItems",t);n.items=!0,(0,o.alwaysValidSchema)(n,t)||e.ok((0,s.validateArray)(e))}};function a(e,t,n=e.schema){const{gen:s,parentSchema:r,data:a,keyword:l,it:c}=e;!function(e){const{opts:i,errSchemaPath:s}=c,r=n.length,a=r===e.minItems&&(r===e.maxItems||!1===e[t]);if(i.strictTuples&&!a){const e=`"${l}" is ${r}-tuple, but minItems or maxItems/${t} are not specified or different at path "${s}"`;(0,o.checkStrictMode)(c,e,i.strictTuples)}}(r),c.opts.unevaluated&&n.length&&!0!==c.items&&(c.items=o.mergeEvaluated.items(s,n.length,c.items));const u=s.name("valid"),h=s.const("len",i._`${a}.length`);n.forEach((t,n)=>{(0,o.alwaysValidSchema)(c,t)||(s.if(i._`${h} > ${n}`,()=>e.subschema({keyword:l,schemaProp:n,dataProp:n},u)),e.ok(u))})}t.validateTuple=a,t.default=r},3966(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(4227),s=n(5765),r=n(5457),a={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>i.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>i._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:n,it:i}=e,{prefixItems:a}=n;i.items=!0,(0,o.alwaysValidSchema)(i,t)||(a?(0,r.validateAdditionalItems)(e,a):e.ok((0,s.validateArray)(e)))}};t.default=a},7923(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(4227),o={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:n,it:o}=e;if((0,i.alwaysValidSchema)(o,n))return void e.fail();const s=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),e.failResult(s,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};t.default=o},6163(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(4227),s={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:e})=>i._`{passingSchemas: ${e.passing}}`},code(e){const{gen:t,schema:n,parentSchema:s,it:r}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(r.opts.discriminator&&s.discriminator)return;const a=n,l=t.let("valid",!1),c=t.let("passing",null),u=t.name("_valid");e.setParams({passing:c}),t.block(function(){a.forEach((n,s)=>{let a;(0,o.alwaysValidSchema)(r,n)?t.var(u,!0):a=e.subschema({keyword:"oneOf",schemaProp:s,compositeRule:!0},u),s>0&&t.if(i._`${u} && ${l}`).assign(l,!1).assign(c,i._`[${c}, ${s}]`).else(),t.if(u,()=>{t.assign(l,!0),t.assign(c,s),a&&e.mergeEvaluated(a,i.Name)})})}),e.result(l,()=>e.reset(),()=>e.error(!0))}};t.default=s},5333(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(5765),o=n(9029),s=n(4227),r=n(4227),a={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,data:a,parentSchema:l,it:c}=e,{opts:u}=c,h=(0,i.allSchemaProperties)(n),d=h.filter(e=>(0,s.alwaysValidSchema)(c,n[e]));if(0===h.length||d.length===h.length&&(!c.opts.unevaluated||!0===c.props))return;const m=u.strictSchema&&!u.allowMatchingProperties&&l.properties,p=t.name("valid");!0===c.props||c.props instanceof o.Name||(c.props=(0,r.evaluatedPropsToName)(t,c.props));const{props:g}=c;function f(e){for(const t in m)new RegExp(e).test(t)&&(0,s.checkStrictMode)(c,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function y(n){t.forIn("key",a,s=>{t.if(o._`${(0,i.usePattern)(e,n)}.test(${s})`,()=>{const i=d.includes(n);i||e.subschema({keyword:"patternProperties",schemaProp:n,dataProp:s,dataPropType:r.Type.Str},p),c.opts.unevaluated&&!0!==g?t.assign(o._`${g}[${s}]`,!0):i||c.allErrors||t.if((0,o.not)(p),()=>t.break())})})}!function(){for(const e of h)m&&f(e),c.allErrors?y(e):(t.var(p,!0),y(e),t.if(p))}()}};t.default=a},5354(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(494),o={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,i.validateTuple)(e,"items")};t.default=o},117(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(2586),o=n(5765),s=n(4227),r=n(8660),a={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,parentSchema:a,data:l,it:c}=e;"all"===c.opts.removeAdditional&&void 0===a.additionalProperties&&r.default.code(new i.KeywordCxt(c,r.default,"additionalProperties"));const u=(0,o.allSchemaProperties)(n);for(const e of u)c.definedProperties.add(e);c.opts.unevaluated&&u.length&&!0!==c.props&&(c.props=s.mergeEvaluated.props(t,(0,s.toHash)(u),c.props));const h=u.filter(e=>!(0,s.alwaysValidSchema)(c,n[e]));if(0===h.length)return;const d=t.name("valid");for(const n of h)m(n)?p(n):(t.if((0,o.propertyInData)(t,l,n,c.opts.ownProperties)),p(n),c.allErrors||t.else().var(d,!0),t.endIf()),e.it.definedProperties.add(n),e.ok(d);function m(e){return c.opts.useDefaults&&!c.compositeRule&&void 0!==n[e].default}function p(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},d)}}};t.default=a},2094(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(4227),s={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:e})=>i._`{propertyName: ${e.propertyName}}`},code(e){const{gen:t,schema:n,data:s,it:r}=e;if((0,o.alwaysValidSchema)(r,n))return;const a=t.name("valid");t.forIn("key",s,n=>{e.setParams({propertyName:n}),e.subschema({keyword:"propertyNames",data:n,dataTypes:["string"],propertyName:n,compositeRule:!0},a),t.if((0,i.not)(a),()=>{e.error(!0),r.allErrors||t.break()})}),e.ok(a)}};t.default=s},4426(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(4227),o={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){void 0===t.if&&(0,i.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};t.default=o},5765(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateUnion=t.validateArray=t.usePattern=t.callValidateCode=t.schemaProperties=t.allSchemaProperties=t.noPropertyInData=t.propertyInData=t.isOwnProperty=t.hasPropFunc=t.reportMissingProp=t.checkMissingProp=t.checkReportMissingProp=void 0;const i=n(9029),o=n(4227),s=n(2023),r=n(4227);function a(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:i._`Object.prototype.hasOwnProperty`})}function l(e,t,n){return i._`${a(e)}.call(${t}, ${n})`}function c(e,t,n,o){const s=i._`${t}${(0,i.getProperty)(n)} === undefined`;return o?(0,i.or)(s,(0,i.not)(l(e,t,n))):s}function u(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}t.checkReportMissingProp=function(e,t){const{gen:n,data:o,it:s}=e;n.if(c(n,o,t,s.opts.ownProperties),()=>{e.setParams({missingProperty:i._`${t}`},!0),e.error()})},t.checkMissingProp=function({gen:e,data:t,it:{opts:n}},o,s){return(0,i.or)(...o.map(o=>(0,i.and)(c(e,t,o,n.ownProperties),i._`${s} = ${o}`)))},t.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},t.hasPropFunc=a,t.isOwnProperty=l,t.propertyInData=function(e,t,n,o){const s=i._`${t}${(0,i.getProperty)(n)} !== undefined`;return o?i._`${s} && ${l(e,t,n)}`:s},t.noPropertyInData=c,t.allSchemaProperties=u,t.schemaProperties=function(e,t){return u(t).filter(n=>!(0,o.alwaysValidSchema)(e,t[n]))},t.callValidateCode=function({schemaCode:e,data:t,it:{gen:n,topSchemaRef:o,schemaPath:r,errorPath:a},it:l},c,u,h){const d=h?i._`${e}, ${t}, ${o}${r}`:t,m=[[s.default.instancePath,(0,i.strConcat)(s.default.instancePath,a)],[s.default.parentData,l.parentData],[s.default.parentDataProperty,l.parentDataProperty],[s.default.rootData,s.default.rootData]];l.opts.dynamicRef&&m.push([s.default.dynamicAnchors,s.default.dynamicAnchors]);const p=i._`${d}, ${n.object(...m)}`;return u!==i.nil?i._`${c}.call(${u}, ${p})`:i._`${c}(${p})`};const h=i._`new RegExp`;t.usePattern=function({gen:e,it:{opts:t}},n){const o=t.unicodeRegExp?"u":"",{regExp:s}=t.code,a=s(n,o);return e.scopeValue("pattern",{key:a.toString(),ref:a,code:i._`${"new RegExp"===s.code?h:(0,r.useFunc)(e,s)}(${n}, ${o})`})},t.validateArray=function(e){const{gen:t,data:n,keyword:s,it:r}=e,a=t.name("valid");if(r.allErrors){const e=t.let("valid",!0);return l(()=>t.assign(e,!1)),e}return t.var(a,!0),l(()=>t.break()),a;function l(r){const l=t.const("len",i._`${n}.length`);t.forRange("i",0,l,n=>{e.subschema({keyword:s,dataProp:n,dataPropType:o.Type.Num},a),t.if((0,i.not)(a),r)})}},t.validateUnion=function(e){const{gen:t,schema:n,keyword:s,it:r}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(e=>(0,o.alwaysValidSchema)(r,e))&&!r.opts.unevaluated)return;const a=t.let("valid",!1),l=t.name("_valid");t.block(()=>n.forEach((n,o)=>{const r=e.subschema({keyword:s,schemaProp:o,compositeRule:!0},l);t.assign(a,i._`${a} || ${l}`),e.mergeValidEvaluated(r,l)||t.if((0,i.not)(a))})),e.result(a,()=>e.reset(),()=>e.error(!0))}},3463(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};t.default=n},2128(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(3463),o=n(3693),s=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",i.default,o.default];t.default=s},3693(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.callRef=t.getValidate=void 0;const i=n(4551),o=n(5765),s=n(9029),r=n(2023),a=n(3835),l=n(4227),c={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:n,it:o}=e,{baseId:r,schemaEnv:l,validateName:c,opts:d,self:m}=o,{root:p}=l;if(("#"===n||"#/"===n)&&r===p.baseId)return function(){if(l===p)return h(e,c,l,l.$async);const n=t.scopeValue("root",{ref:p});return h(e,s._`${n}.validate`,p,p.$async)}();const g=a.resolveRef.call(m,p,r,n);if(void 0===g)throw new i.default(o.opts.uriResolver,r,n);return g instanceof a.SchemaEnv?function(t){const n=u(e,t);h(e,n,t,t.$async)}(g):function(i){const o=t.scopeValue("schema",!0===d.code.source?{ref:i,code:(0,s.stringify)(i)}:{ref:i}),r=t.name("valid"),a=e.subschema({schema:i,dataTypes:[],schemaPath:s.nil,topSchemaRef:o,errSchemaPath:n},r);e.mergeEvaluated(a),e.ok(r)}(g)}};function u(e,t){const{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):s._`${n.scopeValue("wrapper",{ref:t})}.validate`}function h(e,t,n,i){const{gen:a,it:c}=e,{allErrors:u,schemaEnv:h,opts:d}=c,m=d.passContext?r.default.this:s.nil;function p(e){const t=s._`${e}.errors`;a.assign(r.default.vErrors,s._`${r.default.vErrors} === null ? ${t} : ${r.default.vErrors}.concat(${t})`),a.assign(r.default.errors,s._`${r.default.vErrors}.length`)}function g(e){var t;if(!c.opts.unevaluated)return;const i=null===(t=null==n?void 0:n.validate)||void 0===t?void 0:t.evaluated;if(!0!==c.props)if(i&&!i.dynamicProps)void 0!==i.props&&(c.props=l.mergeEvaluated.props(a,i.props,c.props));else{const t=a.var("props",s._`${e}.evaluated.props`);c.props=l.mergeEvaluated.props(a,t,c.props,s.Name)}if(!0!==c.items)if(i&&!i.dynamicItems)void 0!==i.items&&(c.items=l.mergeEvaluated.items(a,i.items,c.items));else{const t=a.var("items",s._`${e}.evaluated.items`);c.items=l.mergeEvaluated.items(a,t,c.items,s.Name)}}i?function(){if(!h.$async)throw new Error("async schema referenced by sync schema");const n=a.let("valid");a.try(()=>{a.code(s._`await ${(0,o.callValidateCode)(e,t,m)}`),g(t),u||a.assign(n,!0)},e=>{a.if(s._`!(${e} instanceof ${c.ValidationError})`,()=>a.throw(e)),p(e),u||a.assign(n,!1)}),e.ok(n)}():e.result((0,o.callValidateCode)(e,t,m),()=>g(t),()=>p(t))}t.getValidate=u,t.callRef=h,t.default=c},6653(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(7652),s=n(3835),r=n(4551),a=n(4227),l={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===o.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>i._`{error: ${e}, tag: ${n}, tagValue: ${t}}`},code(e){const{gen:t,data:n,schema:l,parentSchema:c,it:u}=e,{oneOf:h}=c;if(!u.opts.discriminator)throw new Error("discriminator: requires discriminator option");const d=l.propertyName;if("string"!=typeof d)throw new Error("discriminator: requires propertyName");if(l.mapping)throw new Error("discriminator: mapping is not supported");if(!h)throw new Error("discriminator: requires oneOf keyword");const m=t.let("valid",!1),p=t.const("tag",i._`${n}${(0,i.getProperty)(d)}`);function g(n){const o=t.name("valid"),s=e.subschema({keyword:"oneOf",schemaProp:n},o);return e.mergeEvaluated(s,i.Name),o}t.if(i._`typeof ${p} == "string"`,()=>function(){const n=function(){var e;const t={},n=o(c);let i=!0;for(let t=0;t<h.length;t++){let c=h[t];if((null==c?void 0:c.$ref)&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){const e=c.$ref;if(c=s.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof s.SchemaEnv&&(c=c.schema),void 0===c)throw new r.default(u.opts.uriResolver,u.baseId,e)}const m=null===(e=null==c?void 0:c.properties)||void 0===e?void 0:e[d];if("object"!=typeof m)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${d}"`);i=i&&(n||o(c)),l(m,t)}if(!i)throw new Error(`discriminator: "${d}" must be required`);return t;function o({required:e}){return Array.isArray(e)&&e.includes(d)}function l(e,t){if(e.const)m(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${d}" must have "const" or "enum"`);for(const n of e.enum)m(n,t)}}function m(e,n){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${d}" values must be unique strings`);t[e]=n}}();t.if(!1);for(const e in n)t.elseIf(i._`${p} === ${e}`),t.assign(m,g(n[e]));t.else(),e.error(!1,{discrError:o.DiscrError.Mapping,tag:p,tagName:d}),t.endIf()}(),()=>e.error(!1,{discrError:o.DiscrError.Tag,tag:p,tagName:d})),e.ok(m)}};t.default=l},7652(e,t){"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(n||(t.DiscrError=n={}))},6105(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(2128),o=n(7060),s=n(6378),r=n(5520),a=n(5413),l=n(3265),c=n(7532),u=n(9857),h=[r.default,i.default,o.default,(0,s.default)(!0),c.default,u.metadataVocabulary,u.contentVocabulary,a.default,l.default];t.default=h},6144(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(2128),o=n(7060),s=n(6378),r=n(7532),a=n(9857),l=[i.default,o.default,(0,s.default)(),r.default,a.metadataVocabulary,a.contentVocabulary];t.default=l},2476(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dynamicAnchor=void 0;const i=n(9029),o=n(2023),s=n(3835),r=n(3693),a={keyword:"$dynamicAnchor",schemaType:"string",code:e=>l(e,e.schema)};function l(e,t){const{gen:n,it:a}=e;a.schemaEnv.root.dynamicAnchors[t]=!0;const l=i._`${o.default.dynamicAnchors}${(0,i.getProperty)(t)}`,c="#"===a.errSchemaPath?a.validateName:function(e){const{schemaEnv:t,schema:n,self:i}=e.it,{root:o,baseId:a,localRefs:l,meta:c}=t.root,{schemaId:u}=i.opts,h=new s.SchemaEnv({schema:n,schemaId:u,root:o,baseId:a,localRefs:l,meta:c});return s.compileSchema.call(i,h),(0,r.getValidate)(e,h)}(e);n.if(i._`!${l}`,()=>n.assign(l,c))}t.dynamicAnchor=l,t.default=a},3252(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dynamicRef=void 0;const i=n(9029),o=n(2023),s=n(3693),r={keyword:"$dynamicRef",schemaType:"string",code:e=>a(e,e.schema)};function a(e,t){const{gen:n,keyword:r,it:a}=e;if("#"!==t[0])throw new Error(`"${r}" only supports hash fragment reference`);const l=t.slice(1);if(a.allErrors)c();else{const t=n.let("valid",!1);c(t),e.ok(t)}function c(e){if(a.schemaEnv.root.dynamicAnchors[l]){const t=n.let("_v",i._`${o.default.dynamicAnchors}${(0,i.getProperty)(l)}`);n.if(t,u(t,e),u(a.validateName,e))}else u(a.validateName,e)()}function u(t,i){return i?()=>n.block(()=>{(0,s.callRef)(e,t),n.let(i,!0)}):()=>(0,s.callRef)(e,t)}}t.dynamicRef=a,t.default=r},5520(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(2476),o=n(3252),s=n(2721),r=n(3799),a=[i.default,o.default,s.default,r.default];t.default=a},2721(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(2476),o=n(4227),s={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){e.schema?(0,i.dynamicAnchor)(e,""):(0,o.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};t.default=s},3799(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(3252),o={keyword:"$recursiveRef",schemaType:"string",code:e=>(0,i.dynamicRef)(e,e.schema)};t.default=o},4737(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>i.str`must match format "${e}"`,params:({schemaCode:e})=>i._`{format: ${e}}`},code(e,t){const{gen:n,data:o,$data:s,schema:r,schemaCode:a,it:l}=e,{opts:c,errSchemaPath:u,schemaEnv:h,self:d}=l;c.validateFormats&&(s?function(){const s=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),r=n.const("fDef",i._`${s}[${a}]`),l=n.let("fType"),u=n.let("format");n.if(i._`typeof ${r} == "object" && !(${r} instanceof RegExp)`,()=>n.assign(l,i._`${r}.type || "string"`).assign(u,i._`${r}.validate`),()=>n.assign(l,i._`"string"`).assign(u,r)),e.fail$data((0,i.or)(!1===c.strictSchema?i.nil:i._`${a} && !${u}`,function(){const e=h.$async?i._`(${r}.async ? await ${u}(${o}) : ${u}(${o}))`:i._`${u}(${o})`,n=i._`(typeof ${u} == "function" ? ${e} : ${u}.test(${o}))`;return i._`${u} && ${u} !== true && ${l} === ${t} && !${n}`}()))}():function(){const s=d.formats[r];if(!s)return void function(){if(!1!==c.strictSchema)throw new Error(e());function e(){return`unknown format "${r}" ignored in schema at path "${u}"`}d.logger.warn(e())}();if(!0===s)return;const[a,l,m]=function(e){const t=e instanceof RegExp?(0,i.regexpCode)(e):c.code.formats?i._`${c.code.formats}${(0,i.getProperty)(r)}`:void 0,o=n.scopeValue("formats",{key:r,ref:e,code:t});return"object"!=typeof e||e instanceof RegExp?["string",e,o]:[e.type||"string",e.validate,i._`${o}.validate`]}(s);a===t&&e.pass(function(){if("object"==typeof s&&!(s instanceof RegExp)&&s.async){if(!h.$async)throw new Error("async format in sync schema");return i._`await ${m}(${o})`}return"function"==typeof l?i._`${m}(${o})`:i._`${m}.test(${o})`}())}())}};t.default=o},7532(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=[n(4737).default];t.default=i},9857(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.contentVocabulary=t.metadataVocabulary=void 0,t.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],t.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]},5413(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(1846),o=n(4845),s=n(2626),r=[i.default,o.default,s.default];t.default=r},3265(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(392),o=n(3445),s=[i.default,o.default];t.default=s},3445(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(4227),s={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:{message:({params:{len:e}})=>i.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>i._`{limit: ${e}}`},code(e){const{gen:t,schema:n,data:s,it:r}=e,a=r.items||0;if(!0===a)return;const l=t.const("len",i._`${s}.length`);if(!1===n)e.setParams({len:a}),e.fail(i._`${l} > ${a}`);else if("object"==typeof n&&!(0,o.alwaysValidSchema)(r,n)){const n=t.var("valid",i._`${l} <= ${a}`);t.if((0,i.not)(n),()=>function(n,s){t.forRange("i",s,l,s=>{e.subschema({keyword:"unevaluatedItems",dataProp:s,dataPropType:o.Type.Num},n),r.allErrors||t.if((0,i.not)(n),()=>t.break())})}(n,a)),e.ok(n)}r.items=!0}};t.default=s},392(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(4227),s=n(2023),r={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:{message:"must NOT have unevaluated properties",params:({params:e})=>i._`{unevaluatedProperty: ${e.unevaluatedProperty}}`},code(e){const{gen:t,schema:n,data:r,errsCount:a,it:l}=e;if(!a)throw new Error("ajv implementation error");const{allErrors:c,props:u}=l;function h(s){if(!1===n)return e.setParams({unevaluatedProperty:s}),e.error(),void(c||t.break());if(!(0,o.alwaysValidSchema)(l,n)){const n=t.name("valid");e.subschema({keyword:"unevaluatedProperties",dataProp:s,dataPropType:o.Type.Str},n),c||t.if((0,i.not)(n),()=>t.break())}}u instanceof i.Name?t.if(i._`${u} !== true`,()=>t.forIn("key",r,e=>t.if(function(e,t){return i._`!${e} || !${e}[${t}]`}(u,e),()=>h(e)))):!0!==u&&t.forIn("key",r,e=>void 0===u?h(e):t.if(function(e,t){const n=[];for(const o in e)!0===e[o]&&n.push(i._`${t} !== ${o}`);return(0,i.and)(...n)}(u,e),()=>h(e))),l.props=!0,e.ok(i._`${a} === ${s.default.errors}`)}};t.default=r},7935(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(4227),s=n(6250),r={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>i._`{allowedValue: ${e}}`},code(e){const{gen:t,data:n,$data:r,schemaCode:a,schema:l}=e;r||l&&"object"==typeof l?e.fail$data(i._`!${(0,o.useFunc)(t,s.default)}(${n}, ${a})`):e.fail(i._`${l} !== ${n}`)}};t.default=r},1846(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(3025),o={keyword:"dependentRequired",type:"object",schemaType:"object",error:i.error,code:e=>(0,i.validatePropertyDeps)(e)};t.default=o},8643(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(4227),s=n(6250),r={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>i._`{allowedValues: ${e}}`},code(e){const{gen:t,data:n,$data:r,schema:a,schemaCode:l,it:c}=e;if(!r&&0===a.length)throw new Error("enum must have non-empty array");const u=a.length>=c.opts.loopEnum;let h;const d=()=>null!=h?h:h=(0,o.useFunc)(t,s.default);let m;if(u||r)m=t.let("valid"),e.block$data(m,function(){t.assign(m,!1),t.forOf("v",l,e=>t.if(i._`${d()}(${n}, ${e})`,()=>t.assign(m,!0).break()))});else{if(!Array.isArray(a))throw new Error("ajv implementation error");const e=t.const("vSchema",l);m=(0,i.or)(...a.map((t,o)=>function(e,t){const o=a[t];return"object"==typeof o&&null!==o?i._`${d()}(${n}, ${e}[${t}])`:i._`${n} === ${o}`}(e,o)))}e.pass(m)}};t.default=r},7060(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(5882),o=n(3439),s=n(7307),r=n(422),a=n(4486),l=n(4003),c=n(1163),u=n(617),h=n(7935),d=n(8643),m=[i.default,o.default,s.default,r.default,a.default,l.default,c.default,u.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},h.default,d.default];t.default=m},2626(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(4227),o={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:n}){void 0===t.contains&&(0,i.checkStrictMode)(n,`"${e}" without "contains" is ignored`)}};t.default=o},1163(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n="maxItems"===e?"more":"fewer";return i.str`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>i._`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:o}=e,s="maxItems"===t?i.operators.GT:i.operators.LT;e.fail$data(i._`${n}.length ${s} ${o}`)}};t.default=o},7307(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(4227),s=n(3853),r={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n="maxLength"===e?"more":"fewer";return i.str`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>i._`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:r,it:a}=e,l="maxLength"===t?i.operators.GT:i.operators.LT,c=!1===a.opts.unicode?i._`${n}.length`:i._`${(0,o.useFunc)(e.gen,s.default)}(${n})`;e.fail$data(i._`${c} ${l} ${r}`)}};t.default=r},5882(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=i.operators,s={maximum:{okStr:"<=",ok:o.LTE,fail:o.GT},minimum:{okStr:">=",ok:o.GTE,fail:o.LT},exclusiveMaximum:{okStr:"<",ok:o.LT,fail:o.GTE},exclusiveMinimum:{okStr:">",ok:o.GT,fail:o.LTE}},r={message:({keyword:e,schemaCode:t})=>i.str`must be ${s[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>i._`{comparison: ${s[e].okStr}, limit: ${t}}`},a={keyword:Object.keys(s),type:"number",schemaType:"number",$data:!0,error:r,code(e){const{keyword:t,data:n,schemaCode:o}=e;e.fail$data(i._`${n} ${s[t].fail} ${o} || isNaN(${n})`)}};t.default=a},4486(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n="maxProperties"===e?"more":"fewer";return i.str`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>i._`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:o}=e,s="maxProperties"===t?i.operators.GT:i.operators.LT;e.fail$data(i._`Object.keys(${n}).length ${s} ${o}`)}};t.default=o},3439(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>i.str`must be multiple of ${e}`,params:({schemaCode:e})=>i._`{multipleOf: ${e}}`},code(e){const{gen:t,data:n,schemaCode:o,it:s}=e,r=s.opts.multipleOfPrecision,a=t.let("res"),l=r?i._`Math.abs(Math.round(${a}) - ${a}) > 1e-${r}`:i._`${a} !== parseInt(${a})`;e.fail$data(i._`(${o} === 0 || (${a} = ${n}/${o}, ${l}))`)}};t.default=o},422(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(5765),o=n(9029),s={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>o.str`must match pattern "${e}"`,params:({schemaCode:e})=>o._`{pattern: ${e}}`},code(e){const{data:t,$data:n,schema:s,schemaCode:r,it:a}=e,l=a.opts.unicodeRegExp?"u":"",c=n?o._`(new RegExp(${r}, ${l}))`:(0,i.usePattern)(e,s);e.fail$data(o._`!${c}.test(${t})`)}};t.default=s},4003(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(5765),o=n(9029),s=n(4227),r={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>o.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>o._`{missingProperty: ${e}}`},code(e){const{gen:t,schema:n,schemaCode:r,data:a,$data:l,it:c}=e,{opts:u}=c;if(!l&&0===n.length)return;const h=n.length>=u.loopRequired;if(c.allErrors?function(){if(h||l)e.block$data(o.nil,d);else for(const t of n)(0,i.checkReportMissingProp)(e,t)}():function(){const s=t.let("missing");if(h||l){const n=t.let("valid",!0);e.block$data(n,()=>function(n,s){e.setParams({missingProperty:n}),t.forOf(n,r,()=>{t.assign(s,(0,i.propertyInData)(t,a,n,u.ownProperties)),t.if((0,o.not)(s),()=>{e.error(),t.break()})},o.nil)}(s,n)),e.ok(n)}else t.if((0,i.checkMissingProp)(e,n,s)),(0,i.reportMissingProp)(e,s),t.else()}(),u.strictRequired){const t=e.parentSchema.properties,{definedProperties:i}=e.it;for(const e of n)if(void 0===(null==t?void 0:t[e])&&!i.has(e)){const t=`required property "${e}" is not defined at "${c.schemaEnv.baseId+c.errSchemaPath}" (strictRequired)`;(0,s.checkStrictMode)(c,t,c.opts.strictRequired)}}function d(){t.forOf("prop",r,n=>{e.setParams({missingProperty:n}),t.if((0,i.noPropertyInData)(t,a,n,u.ownProperties),()=>e.error())})}}};t.default=r},617(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(208),o=n(9029),s=n(4227),r=n(6250),a={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>o.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>o._`{i: ${e}, j: ${t}}`},code(e){const{gen:t,data:n,$data:a,schema:l,parentSchema:c,schemaCode:u,it:h}=e;if(!a&&!l)return;const d=t.let("valid"),m=c.items?(0,i.getSchemaTypes)(c.items):[];function p(s,r){const a=t.name("item"),l=(0,i.checkDataTypes)(m,a,h.opts.strictNumbers,i.DataType.Wrong),c=t.const("indices",o._`{}`);t.for(o._`;${s}--;`,()=>{t.let(a,o._`${n}[${s}]`),t.if(l,o._`continue`),m.length>1&&t.if(o._`typeof ${a} == "string"`,o._`${a} += "_"`),t.if(o._`typeof ${c}[${a}] == "number"`,()=>{t.assign(r,o._`${c}[${a}]`),e.error(),t.assign(d,!1).break()}).code(o._`${c}[${a}] = ${s}`)})}function g(i,a){const l=(0,s.useFunc)(t,r.default),c=t.name("outer");t.label(c).for(o._`;${i}--;`,()=>t.for(o._`${a} = ${i}; ${a}--;`,()=>t.if(o._`${l}(${n}[${i}], ${n}[${a}])`,()=>{e.error(),t.assign(d,!1).break(c)})))}e.block$data(d,function(){const i=t.let("i",o._`${n}.length`),s=t.let("j");e.setParams({i,j:s}),t.assign(d,!0),t.if(o._`${i} > 1`,()=>(m.length>0&&!m.some(e=>"object"===e||"array"===e)?p:g)(i,s))},o._`${u} === false`),e.ok(d)}};t.default=a},5488(e,t,n){"use strict";n.d(t,{A:()=>a});var i=n(1354),o=n.n(i),s=n(6314),r=n.n(s)()(o());r.push([e.id,"\n.ui-form.ui-tooltip .ui-input-root > label.ui-input-label:not(:empty) {\n /* min-width: 30px; /* Breaks right margin /**/\n}\n\n.ui-form.ui-tooltip .ui-input-root > div.ui-input-text:not(:empty) {\n margin-top: 6px;\n}","",{version:3,sources:["webpack://./css/cell-renderer.css"],names:[],mappings:";AACA;IACI,8CAA8C;AAClD;;AAEA;IACI,eAAe;AACnB",sourcesContent:["\n.ui-form.ui-tooltip .ui-input-root > label.ui-input-label:not(:empty) {\n /* min-width: 30px; /* Breaks right margin /**/\n}\n\n.ui-form.ui-tooltip .ui-input-root > div.ui-input-text:not(:empty) {\n margin-top: 6px;\n}"],sourceRoot:""}]);const a=r},5999(e,t,n){"use strict";n.d(t,{A:()=>a});var i=n(1354),o=n.n(i),s=n(6314),r=n.n(s)()(o());r.push([e.id,".macromolecule-cell-comp-analysis-host{\n max-height: 250px;\n overflow-y: scroll;\n}\n\n.macromolecule-cell-comp-analysis-bar{\n height: inherit;\n display: block;\n margin-top: 1.5px;\n margin-bottom: 1.5px;\n margin-right: 3px;\n}\n\n.macromolecule-cell-comp-analysis-value{\n display: flex;\n}","",{version:3,sources:["webpack://./css/composition-analysis.css"],names:[],mappings:"AAAA;IACI,iBAAiB;IACjB,kBAAkB;AACtB;;AAEA;IACI,eAAe;IACf,cAAc;IACd,iBAAiB;IACjB,oBAAoB;IACpB,iBAAiB;AACrB;;AAEA;IACI,aAAa;AACjB",sourcesContent:[".macromolecule-cell-comp-analysis-host{\n max-height: 250px;\n overflow-y: scroll;\n}\n\n.macromolecule-cell-comp-analysis-bar{\n height: inherit;\n display: block;\n margin-top: 1.5px;\n margin-bottom: 1.5px;\n margin-right: 3px;\n}\n\n.macromolecule-cell-comp-analysis-value{\n display: flex;\n}"],sourceRoot:""}]);const a=r},6520(e,t,n){"use strict";n.d(t,{A:()=>a});var i=n(1354),o=n.n(i),s=n(6314),r=n.n(s)()(o());r.push([e.id,".monomer-collections-view {\n padding: 16px;\n overflow-y: auto;\n height: 100%;\n}\n\n.monomer-collections-grid {\n display: flex;\n flex-wrap: wrap;\n gap: 16px;\n align-content: flex-start;\n}\n\n.monomer-collection-card {\n width: 20%;\n min-width: 240px;\n height: 300px;\n border: 1px solid var(--grey-2);\n border-radius: 8px;\n background: var(--white);\n display: flex;\n flex-direction: column;\n overflow: hidden;\n transition: box-shadow 0.2s ease;\n}\n\n.monomer-collection-card:hover {\n box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12);\n}\n\n.monomer-collection-card-selected {\n border-color: #ff8c00;\n box-shadow: 0 0 0 1px #ff8c00;\n}\n\n.monomer-collection-card-selected:hover {\n box-shadow: 0 0 0 1px #ff8c00, 0 2px 12px rgba(0, 0, 0, 0.12);\n}\n\n.monomer-collection-card-header {\n padding: 12px 14px 8px 14px;\n border-bottom: 1px solid var(--grey-2);\n flex-shrink: 0;\n}\n\n.monomer-collection-card-title {\n font-size: 14px;\n font-weight: 600;\n color: var(--grey-6);\n margin: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n.monomer-collection-card-description {\n font-size: 11px;\n color: var(--grey-4);\n margin: 4px 0 0 0;\n overflow: hidden;\n text-overflow: ellipsis;\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n}\n\n.monomer-collection-card-tags {\n display: flex;\n flex-wrap: wrap;\n gap: 3px;\n margin: 4px 0 0 0;\n}\n\n.monomer-collection-card-tag {\n display: inline-block;\n padding: 1px 6px;\n border-radius: 3px;\n background: #e8f0fe;\n border: 1px solid var(--blue-2, #aecbfa);\n font-size: 10px;\n color: var(--blue-3, #4285f4);\n}\n\n.monomer-collection-card-meta {\n font-size: 10px;\n color: var(--grey-3);\n margin: 4px 0 0 0;\n}\n\n.monomer-collections-search {\n margin-bottom: 12px;\n}\n\n.monomer-collections-search input {\n width: 100%;\n max-width: 400px;\n}\n\n.monomer-collection-card-body {\n flex: 1;\n overflow-y: auto;\n padding: 10px 14px;\n min-height: 0;\n}\n\n.monomer-collection-card-actions {\n padding: 0px 14px;\n border-top: 1px solid var(--grey-2);\n display: flex;\n gap: 8px;\n justify-content: flex-end;\n flex-shrink: 0;\n}\n\n.monomer-collection-card-actions .ui-btn {\n font-size: 11px;\n padding: 2px 10px;\n margin: 0;\n}\n\n.monomer-collection-tags {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n}\n\n.monomer-collection-tag {\n display: inline-block;\n padding: 2px 8px;\n border-radius: 4px;\n background: var(--grey-1);\n border: 1px solid var(--grey-2);\n font-size: 11px;\n color: var(--grey-5);\n cursor: pointer;\n transition: background 0.15s ease;\n}\n\n.monomer-collection-tag:hover {\n background: var(--blue-1, #e8f0fe);\n border-color: var(--blue-2, #aecbfa);\n}\n\n.monomer-collection-add-card {\n width: 20%;\n min-width: 240px;\n height: 300px;\n border: 2px dashed var(--grey-3);\n border-radius: 8px;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n transition: border-color 0.2s ease, background 0.2s ease;\n}\n\n.monomer-collection-add-card:hover {\n border-color: var(--blue-2, #aecbfa);\n background: var(--blue-1, #e8f0fe);\n}\n\n.monomer-collection-add-card-content {\n text-align: center;\n color: var(--grey-4);\n}\n\n.monomer-collection-add-card-content .grok-icon {\n font-size: 32px;\n margin-bottom: 8px;\n}\n\n.monomer-collection-add-card-content span {\n display: block;\n font-size: 13px;\n}\n\n.monomer-collections-load-more {\n width: 100%;\n display: flex;\n justify-content: center;\n padding: 16px 0;\n}\n\n.monomer-collections-load-more .ui-btn {\n min-width: 200px;\n}\n\n.monomer-collection-empty-state {\n width: 100%;\n text-align: center;\n padding: 60px 20px;\n color: var(--grey-4);\n font-size: 14px;\n}\n","",{version:3,sources:["webpack://./css/monomer-collections.css"],names:[],mappings:"AAAA;EACE,aAAa;EACb,gBAAgB;EAChB,YAAY;AACd;;AAEA;EACE,aAAa;EACb,eAAe;EACf,SAAS;EACT,yBAAyB;AAC3B;;AAEA;EACE,UAAU;EACV,gBAAgB;EAChB,aAAa;EACb,+BAA+B;EAC/B,kBAAkB;EAClB,wBAAwB;EACxB,aAAa;EACb,sBAAsB;EACtB,gBAAgB;EAChB,gCAAgC;AAClC;;AAEA;EACE,0CAA0C;AAC5C;;AAEA;EACE,qBAAqB;EACrB,6BAA6B;AAC/B;;AAEA;EACE,6DAA6D;AAC/D;;AAEA;EACE,2BAA2B;EAC3B,sCAAsC;EACtC,cAAc;AAChB;;AAEA;EACE,eAAe;EACf,gBAAgB;EAChB,oBAAoB;EACpB,SAAS;EACT,gBAAgB;EAChB,uBAAuB;EACvB,mBAAmB;AACrB;;AAEA;EACE,eAAe;EACf,oBAAoB;EACpB,iBAAiB;EACjB,gBAAgB;EAChB,uBAAuB;EACvB,oBAAoB;EACpB,qBAAqB;EACrB,4BAA4B;AAC9B;;AAEA;EACE,aAAa;EACb,eAAe;EACf,QAAQ;EACR,iBAAiB;AACnB;;AAEA;EACE,qBAAqB;EACrB,gBAAgB;EAChB,kBAAkB;EAClB,mBAAmB;EACnB,wCAAwC;EACxC,eAAe;EACf,6BAA6B;AAC/B;;AAEA;EACE,eAAe;EACf,oBAAoB;EACpB,iBAAiB;AACnB;;AAEA;EACE,mBAAmB;AACrB;;AAEA;EACE,WAAW;EACX,gBAAgB;AAClB;;AAEA;EACE,OAAO;EACP,gBAAgB;EAChB,kBAAkB;EAClB,aAAa;AACf;;AAEA;EACE,iBAAiB;EACjB,mCAAmC;EACnC,aAAa;EACb,QAAQ;EACR,yBAAyB;EACzB,cAAc;AAChB;;AAEA;EACE,eAAe;EACf,iBAAiB;EACjB,SAAS;AACX;;AAEA;EACE,aAAa;EACb,eAAe;EACf,QAAQ;AACV;;AAEA;EACE,qBAAqB;EACrB,gBAAgB;EAChB,kBAAkB;EAClB,yBAAyB;EACzB,+BAA+B;EAC/B,eAAe;EACf,oBAAoB;EACpB,eAAe;EACf,iCAAiC;AACnC;;AAEA;EACE,kCAAkC;EAClC,oCAAoC;AACtC;;AAEA;EACE,UAAU;EACV,gBAAgB;EAChB,aAAa;EACb,gCAAgC;EAChC,kBAAkB;EAClB,aAAa;EACb,mBAAmB;EACnB,uBAAuB;EACvB,eAAe;EACf,wDAAwD;AAC1D;;AAEA;EACE,oCAAoC;EACpC,kCAAkC;AACpC;;AAEA;EACE,kBAAkB;EAClB,oBAAoB;AACtB;;AAEA;EACE,eAAe;EACf,kBAAkB;AACpB;;AAEA;EACE,cAAc;EACd,eAAe;AACjB;;AAEA;EACE,WAAW;EACX,aAAa;EACb,uBAAuB;EACvB,eAAe;AACjB;;AAEA;EACE,gBAAgB;AAClB;;AAEA;EACE,WAAW;EACX,kBAAkB;EAClB,kBAAkB;EAClB,oBAAoB;EACpB,eAAe;AACjB",sourcesContent:[".monomer-collections-view {\n padding: 16px;\n overflow-y: auto;\n height: 100%;\n}\n\n.monomer-collections-grid {\n display: flex;\n flex-wrap: wrap;\n gap: 16px;\n align-content: flex-start;\n}\n\n.monomer-collection-card {\n width: 20%;\n min-width: 240px;\n height: 300px;\n border: 1px solid var(--grey-2);\n border-radius: 8px;\n background: var(--white);\n display: flex;\n flex-direction: column;\n overflow: hidden;\n transition: box-shadow 0.2s ease;\n}\n\n.monomer-collection-card:hover {\n box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12);\n}\n\n.monomer-collection-card-selected {\n border-color: #ff8c00;\n box-shadow: 0 0 0 1px #ff8c00;\n}\n\n.monomer-collection-card-selected:hover {\n box-shadow: 0 0 0 1px #ff8c00, 0 2px 12px rgba(0, 0, 0, 0.12);\n}\n\n.monomer-collection-card-header {\n padding: 12px 14px 8px 14px;\n border-bottom: 1px solid var(--grey-2);\n flex-shrink: 0;\n}\n\n.monomer-collection-card-title {\n font-size: 14px;\n font-weight: 600;\n color: var(--grey-6);\n margin: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n.monomer-collection-card-description {\n font-size: 11px;\n color: var(--grey-4);\n margin: 4px 0 0 0;\n overflow: hidden;\n text-overflow: ellipsis;\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n}\n\n.monomer-collection-card-tags {\n display: flex;\n flex-wrap: wrap;\n gap: 3px;\n margin: 4px 0 0 0;\n}\n\n.monomer-collection-card-tag {\n display: inline-block;\n padding: 1px 6px;\n border-radius: 3px;\n background: #e8f0fe;\n border: 1px solid var(--blue-2, #aecbfa);\n font-size: 10px;\n color: var(--blue-3, #4285f4);\n}\n\n.monomer-collection-card-meta {\n font-size: 10px;\n color: var(--grey-3);\n margin: 4px 0 0 0;\n}\n\n.monomer-collections-search {\n margin-bottom: 12px;\n}\n\n.monomer-collections-search input {\n width: 100%;\n max-width: 400px;\n}\n\n.monomer-collection-card-body {\n flex: 1;\n overflow-y: auto;\n padding: 10px 14px;\n min-height: 0;\n}\n\n.monomer-collection-card-actions {\n padding: 0px 14px;\n border-top: 1px solid var(--grey-2);\n display: flex;\n gap: 8px;\n justify-content: flex-end;\n flex-shrink: 0;\n}\n\n.monomer-collection-card-actions .ui-btn {\n font-size: 11px;\n padding: 2px 10px;\n margin: 0;\n}\n\n.monomer-collection-tags {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n}\n\n.monomer-collection-tag {\n display: inline-block;\n padding: 2px 8px;\n border-radius: 4px;\n background: var(--grey-1);\n border: 1px solid var(--grey-2);\n font-size: 11px;\n color: var(--grey-5);\n cursor: pointer;\n transition: background 0.15s ease;\n}\n\n.monomer-collection-tag:hover {\n background: var(--blue-1, #e8f0fe);\n border-color: var(--blue-2, #aecbfa);\n}\n\n.monomer-collection-add-card {\n width: 20%;\n min-width: 240px;\n height: 300px;\n border: 2px dashed var(--grey-3);\n border-radius: 8px;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n transition: border-color 0.2s ease, background 0.2s ease;\n}\n\n.monomer-collection-add-card:hover {\n border-color: var(--blue-2, #aecbfa);\n background: var(--blue-1, #e8f0fe);\n}\n\n.monomer-collection-add-card-content {\n text-align: center;\n color: var(--grey-4);\n}\n\n.monomer-collection-add-card-content .grok-icon {\n font-size: 32px;\n margin-bottom: 8px;\n}\n\n.monomer-collection-add-card-content span {\n display: block;\n font-size: 13px;\n}\n\n.monomer-collections-load-more {\n width: 100%;\n display: flex;\n justify-content: center;\n padding: 16px 0;\n}\n\n.monomer-collections-load-more .ui-btn {\n min-width: 200px;\n}\n\n.monomer-collection-empty-state {\n width: 100%;\n text-align: center;\n padding: 60px 20px;\n color: var(--grey-4);\n font-size: 14px;\n}\n"],sourceRoot:""}]);const a=r},857(e,t,n){"use strict";n.d(t,{A:()=>a});var i=n(1354),o=n.n(i),s=n(6314),r=n.n(s)()(o());r.push([e.id,".monomer-manager-root .grok-sketcher {\n min-width: unset !important;\n}\n\n.monomer-manager-root {\n width: 100% !important;\n height: 100% !important;\n}\n\n.monomer-manager-sketcher .ketcher-host {\n height: 100% !important;\n width: unset !important;\n} \n\n.monomer-manager-root > div:first-child {\n flex-basis: 40% !important;\n}\n.monomer-manager-root > div:nth-child(2) {\n flex-basis: 60% !important;\n}\n\n.monomer-manager-root > div:first-child > .ui-form {\n max-width: unset !important;\n}\n\n.monomer-card-info-row {\n width: 100%;\n overflow: hidden;\n text-overflow: ellipsis;\n margin-bottom: 10px;\n}\n\n.monomer-card-info-row > div:nth-child(2) {\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.monomer-card-info-row > div:nth-child(1) {\n font-weight: bold;\n margin-right: 5px;\n text-wrap: nowrap;\n}\n\n.duplicate-monomer-symbol-row {\n visibility: visible !important;\n}\n\n.monomer-card-root {\n border: 2px solid var(--grey-2);\n border-radius: 5px;\n padding: 5px;\n margin: 5px;\n overflow: hidden;\n align-items: center;\n cursor: pointer;\n width: 200px;\n height: 300px;\n min-width: 200px;\n min-height: 300px;\n}\n\n.duplicate-monomers-virtual-view {\n width: 100% !important;\n overflow-x: clip;\n overflow-y: auto;\n}\n\n.monomer-manager-form-tab-control input.d4-invalid {\n background: #ff000030;\n}\n\n.monomer-lib-controls-form .ui-input-root {\n flex-wrap: nowrap !important;\n}","",{version:3,sources:["webpack://./css/monomer-manager.css"],names:[],mappings:"AAAA;IACI,2BAA2B;AAC/B;;AAEA;IACI,sBAAsB;IACtB,uBAAuB;AAC3B;;AAEA;IACI,uBAAuB;IACvB,uBAAuB;AAC3B;;AAEA;IACI,0BAA0B;AAC9B;AACA;IACI,0BAA0B;AAC9B;;AAEA;IACI,2BAA2B;AAC/B;;AAEA;IACI,WAAW;IACX,gBAAgB;IAChB,uBAAuB;IACvB,mBAAmB;AACvB;;AAEA;IACI,mBAAmB;IACnB,gBAAgB;IAChB,uBAAuB;AAC3B;;AAEA;IACI,iBAAiB;IACjB,iBAAiB;IACjB,iBAAiB;AACrB;;AAEA;IACI,8BAA8B;AAClC;;AAEA;IACI,+BAA+B;IAC/B,kBAAkB;IAClB,YAAY;IACZ,WAAW;IACX,gBAAgB;IAChB,mBAAmB;IACnB,eAAe;IACf,YAAY;IACZ,aAAa;IACb,gBAAgB;IAChB,iBAAiB;AACrB;;AAEA;IACI,sBAAsB;IACtB,gBAAgB;IAChB,gBAAgB;AACpB;;AAEA;IACI,qBAAqB;AACzB;;AAEA;IACI,4BAA4B;AAChC",sourcesContent:[".monomer-manager-root .grok-sketcher {\n min-width: unset !important;\n}\n\n.monomer-manager-root {\n width: 100% !important;\n height: 100% !important;\n}\n\n.monomer-manager-sketcher .ketcher-host {\n height: 100% !important;\n width: unset !important;\n} \n\n.monomer-manager-root > div:first-child {\n flex-basis: 40% !important;\n}\n.monomer-manager-root > div:nth-child(2) {\n flex-basis: 60% !important;\n}\n\n.monomer-manager-root > div:first-child > .ui-form {\n max-width: unset !important;\n}\n\n.monomer-card-info-row {\n width: 100%;\n overflow: hidden;\n text-overflow: ellipsis;\n margin-bottom: 10px;\n}\n\n.monomer-card-info-row > div:nth-child(2) {\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.monomer-card-info-row > div:nth-child(1) {\n font-weight: bold;\n margin-right: 5px;\n text-wrap: nowrap;\n}\n\n.duplicate-monomer-symbol-row {\n visibility: visible !important;\n}\n\n.monomer-card-root {\n border: 2px solid var(--grey-2);\n border-radius: 5px;\n padding: 5px;\n margin: 5px;\n overflow: hidden;\n align-items: center;\n cursor: pointer;\n width: 200px;\n height: 300px;\n min-width: 200px;\n min-height: 300px;\n}\n\n.duplicate-monomers-virtual-view {\n width: 100% !important;\n overflow-x: clip;\n overflow-y: auto;\n}\n\n.monomer-manager-form-tab-control input.d4-invalid {\n background: #ff000030;\n}\n\n.monomer-lib-controls-form .ui-input-root {\n flex-wrap: nowrap !important;\n}"],sourceRoot:""}]);const a=r},6369(e,t,n){"use strict";n.d(t,{A:()=>a});var i=n(1354),o=n.n(i),s=n(6314),r=n.n(s)()(o());r.push([e.id,".kalign-version {\n margin-bottom: 0;\n text-align: end;\n font-size: 12px;\n opacity: 0.8;\n}\nbutton.msa-params-button.ui-btn {\n justify-content: end;\n}","",{version:3,sources:["webpack://./css/msa.css"],names:[],mappings:"AAAA;IACI,gBAAgB;IAChB,eAAe;IACf,eAAe;IACf,YAAY;AAChB;AACA;IACI,oBAAoB;AACxB",sourcesContent:[".kalign-version {\n margin-bottom: 0;\n text-align: end;\n font-size: 12px;\n opacity: 0.8;\n}\nbutton.msa-params-button.ui-btn {\n justify-content: end;\n}"],sourceRoot:""}]);const a=r},7939(e,t,n){"use strict";n.d(t,{A:()=>a});var i=n(1354),o=n.n(i),s=n(6314),r=n.n(s)()(o());r.push([e.id,".scatter_plot_link {\n right: 10px;\n}\n\n.cliffs_div {\n flex-grow: initial!important;\n justify-content: flex-end;\n flex-wrap: wrap;\n}\n\n.cliffs_grid {\n margin: 0!important;\n}\n\n.ml-dim-reduction-settings-input i.grok-icon.grok-font-icon-settings {\n font-size: 18px;\n position: absolute;\n height: 28px;\n}\n\n.ml-dim-reduction-settings-input i.grok-icon.grok-font-icon-settings:not(.ml-dim-reduction-column-editor-input-root i) {\n left: -20px;\n}\n.dlg-dimensionality-reduction.ui-form, .dlg-markov-clustering.ui-form, .dlg-markov-clustering.ui-form .ui-form, .dlg-dimensionality-reduction.ui-form .ui-form {\n max-width: unset;\n}\n\n.ml-dim-reduction-column-editor-input-root label {\n display: none !important;\n}\n\n.dim-reduction-dialog-form > .ui-input-root, .dim-reduction-dialog-form > div > .ui-input-root {\n margin-left: 10px;\n}\n\n.ml-dim-reduction-column-editor-input-root input, .ml-dim-reduction-column-editor-input-root select {\n margin-left: 20px !important;\n}\n\nh3.ml-dim-reduction-column-editor-input-root {\n margin: 0 !important;\n}\n\n.ml-dim-reduction-column-editor-root, .ml-dim-reduction-column-editor-header-root {\n display: flex;\n flex-direction: row;\n align-items: center;\n margin-bottom: 10px !important;\n width: 700px !important;\n}\n\n.ml-dim-reduction-column-editor-column-title {\n text-overflow: ellipsis;\n overflow: hidden;\n}\n\n.ml-dim-reduction-column-editor-header-root > h1:not(:first-child) {\n margin-left: 20px !important;\n}\n\n.ml-dim-reduction-column-editor-table-root .header > td:not(:first-child) {\n padding-left: 32px;\n}","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/ml/css/styles.css"],names:[],mappings:"AAAA;IACI,WAAW;AACf;;AAEA;IACI,4BAA4B;IAC5B,yBAAyB;IACzB,eAAe;AACnB;;AAEA;GACG,mBAAmB;AACtB;;AAEA;IACI,eAAe;IACf,kBAAkB;IAClB,YAAY;AAChB;;AAEA;IACI,WAAW;AACf;AACA;IACI,gBAAgB;AACpB;;AAEA;IACI,wBAAwB;AAC5B;;AAEA;IACI,iBAAiB;AACrB;;AAEA;IACI,4BAA4B;AAChC;;AAEA;IACI,oBAAoB;AACxB;;AAEA;IACI,aAAa;IACb,mBAAmB;IACnB,mBAAmB;IACnB,8BAA8B;IAC9B,uBAAuB;AAC3B;;AAEA;IACI,uBAAuB;IACvB,gBAAgB;AACpB;;AAEA;IACI,4BAA4B;AAChC;;AAEA;IACI,kBAAkB;AACtB",sourcesContent:[".scatter_plot_link {\n right: 10px;\n}\n\n.cliffs_div {\n flex-grow: initial!important;\n justify-content: flex-end;\n flex-wrap: wrap;\n}\n\n.cliffs_grid {\n margin: 0!important;\n}\n\n.ml-dim-reduction-settings-input i.grok-icon.grok-font-icon-settings {\n font-size: 18px;\n position: absolute;\n height: 28px;\n}\n\n.ml-dim-reduction-settings-input i.grok-icon.grok-font-icon-settings:not(.ml-dim-reduction-column-editor-input-root i) {\n left: -20px;\n}\n.dlg-dimensionality-reduction.ui-form, .dlg-markov-clustering.ui-form, .dlg-markov-clustering.ui-form .ui-form, .dlg-dimensionality-reduction.ui-form .ui-form {\n max-width: unset;\n}\n\n.ml-dim-reduction-column-editor-input-root label {\n display: none !important;\n}\n\n.dim-reduction-dialog-form > .ui-input-root, .dim-reduction-dialog-form > div > .ui-input-root {\n margin-left: 10px;\n}\n\n.ml-dim-reduction-column-editor-input-root input, .ml-dim-reduction-column-editor-input-root select {\n margin-left: 20px !important;\n}\n\nh3.ml-dim-reduction-column-editor-input-root {\n margin: 0 !important;\n}\n\n.ml-dim-reduction-column-editor-root, .ml-dim-reduction-column-editor-header-root {\n display: flex;\n flex-direction: row;\n align-items: center;\n margin-bottom: 10px !important;\n width: 700px !important;\n}\n\n.ml-dim-reduction-column-editor-column-title {\n text-overflow: ellipsis;\n overflow: hidden;\n}\n\n.ml-dim-reduction-column-editor-header-root > h1:not(:first-child) {\n margin-left: 20px !important;\n}\n\n.ml-dim-reduction-column-editor-table-root .header > td:not(:first-child) {\n padding-left: 32px;\n}"],sourceRoot:""}]);const a=r},3017(e,t,n){"use strict";n.d(t,{A:()=>a});var i=n(1354),o=n.n(i),s=n(6314),r=n.n(s)()(o());r.push([e.id,".monomer-lib-controls-form {\n margin-left: auto;\n margin-right: auto;\n display: flex;\n flex-direction: column;\n align-items: center;\n min-width: 220px;\n width: 100%;\n\n}\n","",{version:3,sources:["webpack://./src/utils/monomer-lib/library-file-manager/style.css"],names:[],mappings:"AAAA;EACE,iBAAiB;EACjB,kBAAkB;EAClB,aAAa;EACb,sBAAsB;EACtB,mBAAmB;EACnB,gBAAgB;EAChB,WAAW;;AAEb",sourcesContent:[".monomer-lib-controls-form {\n margin-left: auto;\n margin-right: auto;\n display: flex;\n flex-direction: column;\n align-items: center;\n min-width: 220px;\n width: 100%;\n\n}\n"],sourceRoot:""}]);const a=r},6314(e){"use strict";e.exports=function(e){var t=[];return t.toString=function(){return this.map(function(t){var n="",i=void 0!==t[5];return t[4]&&(n+="@supports (".concat(t[4],") {")),t[2]&&(n+="@media ".concat(t[2]," {")),i&&(n+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),n+=e(t),i&&(n+="}"),t[2]&&(n+="}"),t[4]&&(n+="}"),n}).join("")},t.i=function(e,n,i,o,s){"string"==typeof e&&(e=[[null,e,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 c=0;c<e.length;c++){var u=[].concat(e[c]);i&&r[u[0]]||(void 0!==s&&(void 0===u[5]||(u[1]="@layer".concat(u[5].length>0?" ".concat(u[5]):""," {").concat(u[1],"}")),u[5]=s),n&&(u[2]?(u[1]="@media ".concat(u[2]," {").concat(u[1],"}"),u[2]=n):u[2]=n),o&&(u[4]?(u[1]="@supports (".concat(u[4],") {").concat(u[1],"}"),u[4]=o):u[4]="".concat(o)),t.push(u))}},t}},1354(e){"use strict";e.exports=function(e){var t=e[1],n=e[3];if(!n)return t;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[t].concat([s]).join("\n")}return[t].join("\n")}},2017(e){"use strict";e.exports=function e(t,n){if(t===n)return!0;if(t&&n&&"object"==typeof t&&"object"==typeof n){if(t.constructor!==n.constructor)return!1;var i,o,s;if(Array.isArray(t)){if((i=t.length)!=n.length)return!1;for(o=i;0!==o--;)if(!e(t[o],n[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if((i=(s=Object.keys(t)).length)!==Object.keys(n).length)return!1;for(o=i;0!==o--;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=i;0!==o--;){var r=s[o];if(!e(t[r],n[r]))return!1}return!0}return t!=t&&n!=n}},9982(e,t,n){var i;!function(){var t={};!function(e){"use strict";e.__esModule=!0,e.digestLength=32,e.blockSize=64;var t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function n(e,n,i,o,s){for(var r,a,l,c,u,h,d,m,p,g,f,y,b;s>=64;){for(r=n[0],a=n[1],l=n[2],c=n[3],u=n[4],h=n[5],d=n[6],m=n[7],g=0;g<16;g++)f=o+4*g,e[g]=(255&i[f])<<24|(255&i[f+1])<<16|(255&i[f+2])<<8|255&i[f+3];for(g=16;g<64;g++)y=((p=e[g-2])>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,b=((p=e[g-15])>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,e[g]=(y+e[g-7]|0)+(b+e[g-16]|0);for(g=0;g<64;g++)y=(((u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7))+(u&h^~u&d)|0)+(m+(t[g]+e[g]|0)|0)|0,b=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&a^r&l^a&l)|0,m=d,d=h,h=u,u=c+y|0,c=l,l=a,a=r,r=y+b|0;n[0]+=r,n[1]+=a,n[2]+=l,n[3]+=c,n[4]+=u,n[5]+=h,n[6]+=d,n[7]+=m,o+=64,s-=64}return o}var i=function(){function t(){this.digestLength=e.digestLength,this.blockSize=e.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return t.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},t.prototype.clean=function(){for(var e=0;e<this.buffer.length;e++)this.buffer[e]=0;for(e=0;e<this.temp.length;e++)this.temp[e]=0;this.reset()},t.prototype.update=function(e,t){if(void 0===t&&(t=e.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var i=0;if(this.bytesHashed+=t,this.bufferLength>0){for(;this.bufferLength<64&&t>0;)this.buffer[this.bufferLength++]=e[i++],t--;64===this.bufferLength&&(n(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(t>=64&&(i=n(this.temp,this.state,e,i,t),t%=64);t>0;)this.buffer[this.bufferLength++]=e[i++],t--;return this},t.prototype.finish=function(e){if(!this.finished){var t=this.bytesHashed,i=this.bufferLength,o=t/536870912|0,s=t<<3,r=t%64<56?64:128;this.buffer[i]=128;for(var a=i+1;a<r-8;a++)this.buffer[a]=0;this.buffer[r-8]=o>>>24&255,this.buffer[r-7]=o>>>16&255,this.buffer[r-6]=o>>>8&255,this.buffer[r-5]=o>>>0&255,this.buffer[r-4]=s>>>24&255,this.buffer[r-3]=s>>>16&255,this.buffer[r-2]=s>>>8&255,this.buffer[r-1]=s>>>0&255,n(this.temp,this.state,this.buffer,0,r),this.finished=!0}for(a=0;a<8;a++)e[4*a+0]=this.state[a]>>>24&255,e[4*a+1]=this.state[a]>>>16&255,e[4*a+2]=this.state[a]>>>8&255,e[4*a+3]=this.state[a]>>>0&255;return this},t.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},t.prototype._saveState=function(e){for(var t=0;t<this.state.length;t++)e[t]=this.state[t]},t.prototype._restoreState=function(e,t){for(var n=0;n<this.state.length;n++)this.state[n]=e[n];this.bytesHashed=t,this.finished=!1,this.bufferLength=0},t}();e.Hash=i;var o=function(){function e(e){this.inner=new i,this.outer=new i,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var t=new Uint8Array(this.blockSize);if(e.length>this.blockSize)(new i).update(e).finish(t).clean();else for(var n=0;n<e.length;n++)t[n]=e[n];for(n=0;n<t.length;n++)t[n]^=54;for(this.inner.update(t),n=0;n<t.length;n++)t[n]^=106;for(this.outer.update(t),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate),n=0;n<t.length;n++)t[n]=0}return e.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},e.prototype.clean=function(){for(var e=0;e<this.istate.length;e++)this.ostate[e]=this.istate[e]=0;this.inner.clean(),this.outer.clean()},e.prototype.update=function(e){return this.inner.update(e),this},e.prototype.finish=function(e){return this.outer.finished?this.outer.finish(e):(this.inner.finish(e),this.outer.update(e,this.digestLength).finish(e)),this},e.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},e}();function s(e){var t=(new i).update(e),n=t.digest();return t.clean(),n}function r(e,t){var n=new o(e).update(t),i=n.digest();return n.clean(),i}function a(e,t,n,i){var o=i[0];if(0===o)throw new Error("hkdf: cannot expand more");t.reset(),o>1&&t.update(e),n&&t.update(n),t.update(i),t.finish(e),i[0]++}e.HMAC=o,e.hash=s,e.default=s,e.hmac=r;var l=new Uint8Array(e.digestLength);e.hkdf=function(e,t,n,i){void 0===t&&(t=l),void 0===i&&(i=32);for(var s=new Uint8Array([1]),c=r(t,e),u=new o(c),h=new Uint8Array(u.digestLength),d=h.length,m=new Uint8Array(i),p=0;p<i;p++)d===h.length&&(a(h,u,n,s),d=0),m[p]=h[d++];return u.clean(),h.fill(0),s.fill(0),m},e.pbkdf2=function(e,t,n,i){for(var s=new o(e),r=s.digestLength,a=new Uint8Array(4),l=new Uint8Array(r),c=new Uint8Array(r),u=new Uint8Array(i),h=0;h*r<i;h++){var d=h+1;a[0]=d>>>24&255,a[1]=d>>>16&255,a[2]=d>>>8&255,a[3]=d>>>0&255,s.reset(),s.update(t),s.update(a),s.finish(c);for(var m=0;m<r;m++)l[m]=c[m];for(m=2;m<=n;m++){s.reset(),s.update(c).finish(c);for(var p=0;p<r;p++)l[p]^=c[p]}for(m=0;m<r&&h*r+m<i;m++)u[h*r+m]=l[m]}for(h=0;h<r;h++)l[h]=c[h]=0;for(h=0;h<4;h++)a[h]=0;return s.clean(),u}}(t);var o=t.default;for(var s in t)o[s]=t[s];"object"==typeof e.exports?e.exports=o:void 0===(i=function(){return o}.call(t,n,t,e))||(e.exports=i)}()},2787(e,t,n){"use strict";n.d(t,{I:()=>o});const i=new Uint32Array(65536),o=(e,t)=>{if(e.length<t.length){const n=t;t=e,e=n}return 0===t.length?e.length:e.length<=32?((e,t)=>{const n=e.length,o=t.length,s=1<<n-1;let r=-1,a=0,l=n,c=n;for(;c--;)i[e.charCodeAt(c)]|=1<<c;for(c=0;c<o;c++){let e=i[t.charCodeAt(c)];const n=e|a;e|=(e&r)+r^r,a|=~(e|r),r&=e,a&s&&l++,r&s&&l--,a=a<<1|1,r=r<<1|~(n|a),a&=n}for(c=n;c--;)i[e.charCodeAt(c)]=0;return l})(e,t):((e,t)=>{const n=t.length,o=e.length,s=[],r=[],a=Math.ceil(n/32),l=Math.ceil(o/32);for(let e=0;e<a;e++)r[e]=-1,s[e]=0;let c=0;for(;c<l-1;c++){let a=0,l=-1;const u=32*c,h=Math.min(32,o)+u;for(let t=u;t<h;t++)i[e.charCodeAt(t)]|=1<<t;for(let e=0;e<n;e++){const n=i[t.charCodeAt(e)],o=r[e/32|0]>>>e&1,c=s[e/32|0]>>>e&1,u=n|a,h=((n|c)&l)+l^l|n|c;let d=a|~(h|l),m=l&h;d>>>31^o&&(r[e/32|0]^=1<<e),m>>>31^c&&(s[e/32|0]^=1<<e),d=d<<1|o,m=m<<1|c,l=m|~(u|d),a=d&u}for(let t=u;t<h;t++)i[e.charCodeAt(t)]=0}let u=0,h=-1;const d=32*c,m=Math.min(32,o-d)+d;for(let t=d;t<m;t++)i[e.charCodeAt(t)]|=1<<t;let p=o;for(let e=0;e<n;e++){const n=i[t.charCodeAt(e)],a=r[e/32|0]>>>e&1,l=s[e/32|0]>>>e&1,c=n|u,d=((n|l)&h)+h^h|n|l;let m=u|~(d|h),g=h&d;p+=m>>>o-1&1,p-=g>>>o-1&1,m>>>31^a&&(r[e/32|0]^=1<<e),g>>>31^l&&(s[e/32|0]^=1<<e),m=m<<1|a,g=g<<1|l,h=g|~(c|m),u=m&c}for(let t=d;t<m;t++)i[e.charCodeAt(t)]=0;return p})(e,t)}},9937(e){e.exports={linLogMode:!1,outboundAttractionDistribution:!1,adjustSizes:!1,edgeWeightInfluence:1,scalingRatio:1,strongGravityMode:!1,gravity:1,slowDown:1,barnesHutOptimize:!1,barnesHutTheta:.5}},1782(e,t){t.assign=function(e){e=e||{};var t,n,i,o=Array.prototype.slice.call(arguments).slice(1);for(t=0,i=o.length;t<i;t++)if(o[t])for(n in o[t])e[n]=o[t][n];return e},t.validateSettings=function(e){return"linLogMode"in e&&"boolean"!=typeof e.linLogMode?{message:"the `linLogMode` setting should be a boolean."}:"outboundAttractionDistribution"in e&&"boolean"!=typeof e.outboundAttractionDistribution?{message:"the `outboundAttractionDistribution` setting should be a boolean."}:"adjustSizes"in e&&"boolean"!=typeof e.adjustSizes?{message:"the `adjustSizes` setting should be a boolean."}:"edgeWeightInfluence"in e&&"number"!=typeof e.edgeWeightInfluence?{message:"the `edgeWeightInfluence` setting should be a number."}:!("scalingRatio"in e)||"number"==typeof e.scalingRatio&&e.scalingRatio>=0?"strongGravityMode"in e&&"boolean"!=typeof e.strongGravityMode?{message:"the `strongGravityMode` setting should be a boolean."}:!("gravity"in e)||"number"==typeof e.gravity&&e.gravity>=0?"slowDown"in e&&!("number"==typeof e.slowDown||e.slowDown>=0)?{message:"the `slowDown` setting should be a number >= 0."}:"barnesHutOptimize"in e&&"boolean"!=typeof e.barnesHutOptimize?{message:"the `barnesHutOptimize` setting should be a boolean."}:!("barnesHutTheta"in e)||"number"==typeof e.barnesHutTheta&&e.barnesHutTheta>=0?null:{message:"the `barnesHutTheta` setting should be a number >= 0."}:{message:"the `gravity` setting should be a number >= 0."}:{message:"the `scalingRatio` setting should be a number >= 0."}},t.graphToByteArrays=function(e,t){var n,i=e.order,o=e.size,s={},r=new Float32Array(10*i),a=new Float32Array(3*o);return n=0,e.forEachNode(function(e,t){s[e]=n,r[n]=t.x,r[n+1]=t.y,r[n+2]=0,r[n+3]=0,r[n+4]=0,r[n+5]=0,r[n+6]=1,r[n+7]=1,r[n+8]=t.size||1,r[n+9]=t.fixed?1:0,n+=10}),n=0,e.forEachEdge(function(e,i,o,l,c,u,h){var d=s[o],m=s[l],p=t(e,i,o,l,c,u,h);r[d+6]+=p,r[m+6]+=p,a[n]=d,a[n+1]=m,a[n+2]=p,n+=3}),{nodes:r,edges:a}},t.assignLayoutChanges=function(e,t,n){var i=0;e.updateEachNodeAttributes(function(e,o){return o.x=t[i],o.y=t[i+1],i+=10,n?n(e,o):o})},t.readGraphPositions=function(e,t){var n=0;e.forEachNode(function(e,i){t[n]=i.x,t[n+1]=i.y,n+=10})},t.collectLayoutChanges=function(e,t,n){for(var i=e.nodes(),o={},s=0,r=0,a=t.length;s<a;s+=10){if(n){var l=Object.assign({},e.getNodeAttributes(i[r]));l.x=t[s],l.y=t[s+1],l=n(i[r],l),o[i[r]]={x:l.x,y:l.y}}else o[i[r]]={x:t[s],y:t[s+1]};r++}return o},t.createWorker=function(e){var t=window.URL||window.webkitURL,n=e.toString(),i=t.createObjectURL(new Blob(["("+n+").call(this);"],{type:"text/javascript"})),o=new Worker(i);return t.revokeObjectURL(i),o}},8903(e,t,n){var i=n(1736),o=n(8153).Fd,s=n(2561),r=n(1782),a=n(9937);function l(e,t,n){if(!i(t))throw new Error("graphology-layout-forceatlas2: the given graph is not a valid graphology instance.");"number"==typeof n&&(n={iterations:n});var l=n.iterations;if("number"!=typeof l)throw new Error("graphology-layout-forceatlas2: invalid number of iterations.");if(l<=0)throw new Error("graphology-layout-forceatlas2: you should provide a positive number of iterations.");var c=o("getEdgeWeight"in n?n.getEdgeWeight:"weight").fromEntry,u="function"==typeof n.outputReducer?n.outputReducer:null,h=r.assign({},a,n.settings),d=r.validateSettings(h);if(d)throw new Error("graphology-layout-forceatlas2: "+d.message);var m,p=r.graphToByteArrays(t,c);for(m=0;m<l;m++)s(h,p.nodes,p.edges);if(!e)return r.collectLayoutChanges(t,p.nodes);r.assignLayoutChanges(t,p.nodes,u)}var c=l.bind(null,!1);c.assign=l.bind(null,!0),c.inferSettings=function(e){var t="number"==typeof e?e:e.order;return{barnesHutOptimize:t>2e3,strongGravityMode:!0,gravity:.05,scalingRatio:10,slowDown:1+Math.log(t)}},e.exports=c},2561(e){var t=10;e.exports=function(e,n,i){var o,s,r,a,l,c,u,h,d,m,p,g,f,y,b,w,v,C,A,T,E,S,M,x=n.length,P=i.length,L=e.adjustSizes,I=e.barnesHutTheta*e.barnesHutTheta,_=[];for(r=0;r<x;r+=t)n[r+4]=n[r+2],n[r+5]=n[r+3],n[r+2]=0,n[r+3]=0;if(e.outboundAttractionDistribution){for(p=0,r=0;r<x;r+=t)p+=n[r+6];p/=x/t}if(e.barnesHutOptimize){var N,R,$,O=1/0,H=-1/0,D=1/0,F=-1/0;for(r=0;r<x;r+=t)O=Math.min(O,n[r+0]),H=Math.max(H,n[r+0]),D=Math.min(D,n[r+1]),F=Math.max(F,n[r+1]);var k=H-O,G=F-D;for(k>G?F=(D-=(k-G)/2)+k:H=(O-=(G-k)/2)+G,_[0]=-1,_[1]=(O+H)/2,_[2]=(D+F)/2,_[3]=Math.max(H-O,F-D),_[4]=-1,_[5]=-1,_[6]=0,_[7]=0,_[8]=0,o=1,r=0;r<x;r+=t)for(s=0,$=3;;){if(!(_[s+5]>=0)){if(_[s+0]<0){_[s+0]=r;break}if(_[s+5]=9*o,h=_[s+3]/2,_[(d=_[s+5])+0]=-1,_[d+1]=_[s+1]-h,_[d+2]=_[s+2]-h,_[d+3]=h,_[d+4]=d+9,_[d+5]=-1,_[d+6]=0,_[d+7]=0,_[d+8]=0,_[(d+=9)+0]=-1,_[d+1]=_[s+1]-h,_[d+2]=_[s+2]+h,_[d+3]=h,_[d+4]=d+9,_[d+5]=-1,_[d+6]=0,_[d+7]=0,_[d+8]=0,_[(d+=9)+0]=-1,_[d+1]=_[s+1]+h,_[d+2]=_[s+2]-h,_[d+3]=h,_[d+4]=d+9,_[d+5]=-1,_[d+6]=0,_[d+7]=0,_[d+8]=0,_[(d+=9)+0]=-1,_[d+1]=_[s+1]+h,_[d+2]=_[s+2]+h,_[d+3]=h,_[d+4]=_[s+4],_[d+5]=-1,_[d+6]=0,_[d+7]=0,_[d+8]=0,o+=4,N=n[_[s+0]+0]<_[s+1]?n[_[s+0]+1]<_[s+2]?_[s+5]:_[s+5]+9:n[_[s+0]+1]<_[s+2]?_[s+5]+18:_[s+5]+27,_[s+6]=n[_[s+0]+6],_[s+7]=n[_[s+0]+0],_[s+8]=n[_[s+0]+1],_[N+0]=_[s+0],_[s+0]=-1,N===(R=n[r+0]<_[s+1]?n[r+1]<_[s+2]?_[s+5]:_[s+5]+9:n[r+1]<_[s+2]?_[s+5]+18:_[s+5]+27)){if($--){s=N;continue}$=3;break}_[R+0]=r;break}N=n[r+0]<_[s+1]?n[r+1]<_[s+2]?_[s+5]:_[s+5]+9:n[r+1]<_[s+2]?_[s+5]+18:_[s+5]+27,_[s+7]=(_[s+7]*_[s+6]+n[r+0]*n[r+6])/(_[s+6]+n[r+6]),_[s+8]=(_[s+8]*_[s+6]+n[r+1]*n[r+6])/(_[s+6]+n[r+6]),_[s+6]+=n[r+6],s=N}}if(e.barnesHutOptimize){for(g=e.scalingRatio,r=0;r<x;r+=t)for(s=0;;)if(_[s+5]>=0){if(w=Math.pow(n[r+0]-_[s+7],2)+Math.pow(n[r+1]-_[s+8],2),4*(m=_[s+3])*m/w<I){if(f=n[r+0]-_[s+7],y=n[r+1]-_[s+8],!0===L?w>0?(v=g*n[r+6]*_[s+6]/w,n[r+2]+=f*v,n[r+3]+=y*v):w<0&&(v=-g*n[r+6]*_[s+6]/Math.sqrt(w),n[r+2]+=f*v,n[r+3]+=y*v):w>0&&(v=g*n[r+6]*_[s+6]/w,n[r+2]+=f*v,n[r+3]+=y*v),(s=_[s+4])<0)break;continue}s=_[s+5]}else if((c=_[s+0])>=0&&c!==r&&(w=(f=n[r+0]-n[c+0])*f+(y=n[r+1]-n[c+1])*y,!0===L?w>0?(v=g*n[r+6]*n[c+6]/w,n[r+2]+=f*v,n[r+3]+=y*v):w<0&&(v=-g*n[r+6]*n[c+6]/Math.sqrt(w),n[r+2]+=f*v,n[r+3]+=y*v):w>0&&(v=g*n[r+6]*n[c+6]/w,n[r+2]+=f*v,n[r+3]+=y*v)),(s=_[s+4])<0)break}else for(g=e.scalingRatio,a=0;a<x;a+=t)for(l=0;l<a;l+=t)f=n[a+0]-n[l+0],y=n[a+1]-n[l+1],!0===L?(w=Math.sqrt(f*f+y*y)-n[a+8]-n[l+8])>0?(v=g*n[a+6]*n[l+6]/w/w,n[a+2]+=f*v,n[a+3]+=y*v,n[l+2]-=f*v,n[l+3]-=y*v):w<0&&(v=100*g*n[a+6]*n[l+6],n[a+2]+=f*v,n[a+3]+=y*v,n[l+2]-=f*v,n[l+3]-=y*v):(w=Math.sqrt(f*f+y*y))>0&&(v=g*n[a+6]*n[l+6]/w/w,n[a+2]+=f*v,n[a+3]+=y*v,n[l+2]-=f*v,n[l+3]-=y*v);for(d=e.gravity/e.scalingRatio,g=e.scalingRatio,r=0;r<x;r+=t)v=0,f=n[r+0],y=n[r+1],w=Math.sqrt(Math.pow(f,2)+Math.pow(y,2)),e.strongGravityMode?w>0&&(v=g*n[r+6]*d):w>0&&(v=g*n[r+6]*d/w),n[r+2]-=f*v,n[r+3]-=y*v;for(g=1*(e.outboundAttractionDistribution?p:1),u=0;u<P;u+=3)a=i[u+0],l=i[u+1],h=i[u+2],b=Math.pow(h,e.edgeWeightInfluence),f=n[a+0]-n[l+0],y=n[a+1]-n[l+1],!0===L?(w=Math.sqrt(f*f+y*y)-n[a+8]-n[l+8],e.linLogMode?e.outboundAttractionDistribution?w>0&&(v=-g*b*Math.log(1+w)/w/n[a+6]):w>0&&(v=-g*b*Math.log(1+w)/w):e.outboundAttractionDistribution?w>0&&(v=-g*b/n[a+6]):w>0&&(v=-g*b)):(w=Math.sqrt(Math.pow(f,2)+Math.pow(y,2)),e.linLogMode?e.outboundAttractionDistribution?w>0&&(v=-g*b*Math.log(1+w)/w/n[a+6]):w>0&&(v=-g*b*Math.log(1+w)/w):e.outboundAttractionDistribution?(w=1,v=-g*b/n[a+6]):(w=1,v=-g*b)),w>0&&(n[a+2]+=f*v,n[a+3]+=y*v,n[l+2]-=f*v,n[l+3]-=y*v);if(!0===L)for(r=0;r<x;r+=t)1!==n[r+9]&&((C=Math.sqrt(Math.pow(n[r+2],2)+Math.pow(n[r+3],2)))>10&&(n[r+2]=10*n[r+2]/C,n[r+3]=10*n[r+3]/C),A=n[r+6]*Math.sqrt((n[r+4]-n[r+2])*(n[r+4]-n[r+2])+(n[r+5]-n[r+3])*(n[r+5]-n[r+3])),T=Math.sqrt((n[r+4]+n[r+2])*(n[r+4]+n[r+2])+(n[r+5]+n[r+3])*(n[r+5]+n[r+3]))/2,E=.1*Math.log(1+T)/(1+Math.sqrt(A)),S=n[r+0]+n[r+2]*(E/e.slowDown),n[r+0]=S,M=n[r+1]+n[r+3]*(E/e.slowDown),n[r+1]=M);else for(r=0;r<x;r+=t)1!==n[r+9]&&(A=n[r+6]*Math.sqrt((n[r+4]-n[r+2])*(n[r+4]-n[r+2])+(n[r+5]-n[r+3])*(n[r+5]-n[r+3])),T=Math.sqrt((n[r+4]+n[r+2])*(n[r+4]+n[r+2])+(n[r+5]+n[r+3])*(n[r+5]+n[r+3]))/2,E=n[r+7]*Math.log(1+T)/(1+Math.sqrt(A)),n[r+7]=Math.min(1,Math.sqrt(E*(Math.pow(n[r+2],2)+Math.pow(n[r+3],2))/(1+Math.sqrt(A)))),S=n[r+0]+n[r+2]*(E/e.slowDown),n[r+0]=S,M=n[r+1]+n[r+3]*(E/e.slowDown),n[r+1]=M);return{}}},8153(e,t){function n(e){return"number"!=typeof e||isNaN(e)?1:e}t.Fd=function(e){return function(e,t){var n={},i=function(e){return void 0===e?t:e};"function"==typeof t&&(i=t);var o=function(t){return i(t[e])},s=function(){return i(void 0)};return"string"==typeof e?(n.fromAttributes=o,n.fromGraph=function(e,t){return o(e.getEdgeAttributes(t))},n.fromEntry=function(e,t){return o(t)},n.fromPartialEntry=n.fromEntry,n.fromMinimalEntry=n.fromEntry):"function"==typeof e?(n.fromAttributes=function(){throw new Error("graphology-utils/getters/createEdgeValueGetter: irrelevant usage.")},n.fromGraph=function(t,n){var o=t.extremities(n);return i(e(n,t.getEdgeAttributes(n),o[0],o[1],t.getNodeAttributes(o[0]),t.getNodeAttributes(o[1]),t.isUndirected(n)))},n.fromEntry=function(t,n,o,s,r,a,l){return i(e(t,n,o,s,r,a,l))},n.fromPartialEntry=function(t,n,o,s){return i(e(t,n,o,s))},n.fromMinimalEntry=function(t,n){return i(e(t,n))}):(n.fromAttributes=s,n.fromGraph=s,n.fromEntry=s,n.fromMinimalEntry=s),n}(e,n)}},1736(e){e.exports=function(e){return null!==e&&"object"==typeof e&&"function"==typeof e.addUndirectedEdgeWithKey&&"function"==typeof e.dropNode&&"boolean"==typeof e.multi}},934(e){e.exports=function(){"use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,i(e,t)}function n(e){return n=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},n(e)}function i(e,t){return i=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},i(e,t)}function o(e,t,n){return o=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}()?Reflect.construct.bind():function(e,t,n){var o=[null];o.push.apply(o,t);var s=new(Function.bind.apply(e,o));return n&&i(s,n.prototype),s},o.apply(null,arguments)}function s(e){var t="function"==typeof Map?new Map:void 0;return s=function(e){if(null===e||(s=e,-1===Function.toString.call(s).indexOf("[native code]")))return e;var s;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return o(e,arguments,n(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),i(r,e)},s(e)}function r(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}var a=function(){for(var e=arguments[0],t=1,n=arguments.length;t<n;t++)if(arguments[t])for(var i in arguments[t])e[i]=arguments[t][i];return e};function l(e,t,n,i){var o=e._nodes.get(t),s=null;return o?s="mixed"===i?o.out&&o.out[n]||o.undirected&&o.undirected[n]:"directed"===i?o.out&&o.out[n]:o.undirected&&o.undirected[n]:s}function c(t){return"object"===e(t)&&null!==t}function u(e){var t;for(t in e)return!1;return!0}function h(e,t,n){Object.defineProperty(e,t,{enumerable:!1,configurable:!1,writable:!0,value:n})}function d(e,t,n){var i={enumerable:!0,configurable:!0};"function"==typeof n?i.get=n:(i.value=n,i.writable=!1),Object.defineProperty(e,t,i)}function m(e){return!(!c(e)||e.attributes&&!Array.isArray(e.attributes))}"function"==typeof Object.assign&&(a=Object.assign);var p,g={exports:{}},f="object"==typeof Reflect?Reflect:null,y=f&&"function"==typeof f.apply?f.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};p=f&&"function"==typeof f.ownKeys?f.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var b=Number.isNaN||function(e){return e!=e};function w(){w.init.call(this)}g.exports=w,g.exports.once=function(e,t){return new Promise(function(n,i){function o(n){e.removeListener(t,s),i(n)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",o),n([].slice.call(arguments))}L(e,t,s,{once:!0}),"error"!==t&&function(e,t){"function"==typeof e.on&&L(e,"error",t,{once:!0})}(e,o)})},w.EventEmitter=w,w.prototype._events=void 0,w.prototype._eventsCount=0,w.prototype._maxListeners=void 0;var v=10;function C(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function A(e){return void 0===e._maxListeners?w.defaultMaxListeners:e._maxListeners}function T(e,t,n,i){var o,s,r,a;if(C(n),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),r=s[t]),void 0===r)r=s[t]=n,++e._eventsCount;else if("function"==typeof r?r=s[t]=i?[n,r]:[r,n]:i?r.unshift(n):r.push(n),(o=A(e))>0&&r.length>o&&!r.warned){r.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+r.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=r.length,a=l,console&&console.warn&&console.warn(a)}return e}function E(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function S(e,t,n){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},o=E.bind(i);return o.listener=n,i.wrapFn=o,o}function M(e,t,n){var i=e._events;if(void 0===i)return[];var o=i[t];return void 0===o?[]:"function"==typeof o?n?[o.listener||o]:[o]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(o):P(o,o.length)}function x(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function P(e,t){for(var n=new Array(t),i=0;i<t;++i)n[i]=e[i];return n}function L(e,t,n,i){if("function"==typeof e.on)i.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function o(s){i.once&&e.removeEventListener(t,o),n(s)})}}function I(e){if("function"!=typeof e)throw new Error("obliterator/iterator: expecting a function!");this.next=e}Object.defineProperty(w,"defaultMaxListeners",{enumerable:!0,get:function(){return v},set:function(e){if("number"!=typeof e||e<0||b(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");v=e}}),w.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},w.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||b(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},w.prototype.getMaxListeners=function(){return A(this)},w.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i="error"===e,o=this._events;if(void 0!==o)i=i&&void 0===o.error;else if(!i)return!1;if(i){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var r=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw r.context=s,r}var a=o[e];if(void 0===a)return!1;if("function"==typeof a)y(a,this,t);else{var l=a.length,c=P(a,l);for(n=0;n<l;++n)y(c[n],this,t)}return!0},w.prototype.addListener=function(e,t){return T(this,e,t,!1)},w.prototype.on=w.prototype.addListener,w.prototype.prependListener=function(e,t){return T(this,e,t,!0)},w.prototype.once=function(e,t){return C(t),this.on(e,S(this,e,t)),this},w.prototype.prependOnceListener=function(e,t){return C(t),this.prependListener(e,S(this,e,t)),this},w.prototype.removeListener=function(e,t){var n,i,o,s,r;if(C(t),void 0===(i=this._events))return this;if(void 0===(n=i[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(o=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){r=n[s].listener,o=s;break}if(o<0)return this;0===o?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,o),1===n.length&&(i[e]=n[0]),void 0!==i.removeListener&&this.emit("removeListener",e,r||t)}return this},w.prototype.off=w.prototype.removeListener,w.prototype.removeAllListeners=function(e){var t,n,i;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var o,s=Object.keys(n);for(i=0;i<s.length;++i)"removeListener"!==(o=s[i])&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},w.prototype.listeners=function(e){return M(this,e,!0)},w.prototype.rawListeners=function(e){return M(this,e,!1)},w.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):x.call(e,t)},w.prototype.listenerCount=x,w.prototype.eventNames=function(){return this._eventsCount>0?p(this._events):[]},"undefined"!=typeof Symbol&&(I.prototype[Symbol.iterator]=function(){return this}),I.of=function(){var e=arguments,t=e.length,n=0;return new I(function(){return n>=t?{done:!0}:{done:!1,value:e[n++]}})},I.empty=function(){return new I(function(){return{done:!0}})},I.fromSequence=function(e){var t=0,n=e.length;return new I(function(){return t>=n?{done:!0}:{done:!1,value:e[t++]}})},I.is=function(e){return e instanceof I||"object"==typeof e&&null!==e&&"function"==typeof e.next};var _=I,N={};N.ARRAY_BUFFER_SUPPORT="undefined"!=typeof ArrayBuffer,N.SYMBOL_SUPPORT="undefined"!=typeof Symbol;var R=_,$=N,O=$.ARRAY_BUFFER_SUPPORT,H=$.SYMBOL_SUPPORT,D=function(e){var t=function(e){return"string"==typeof e||Array.isArray(e)||O&&ArrayBuffer.isView(e)?R.fromSequence(e):"object"!=typeof e||null===e?null:H&&"function"==typeof e[Symbol.iterator]?e[Symbol.iterator]():"function"==typeof e.next?e:null}(e);if(!t)throw new Error("obliterator: target is not iterable nor a valid iterator.");return t},F=D,k=function(e,t){for(var n,i=arguments.length>1?t:1/0,o=i!==1/0?new Array(i):[],s=0,r=F(e);;){if(s===i)return o;if((n=r.next()).done)return s!==t&&(o.length=s),o;o[s++]=n.value}},G=function(e){function n(t){var n;return(n=e.call(this)||this).name="GraphError",n.message=t,n}return t(n,e),n}(s(Error)),B=function(e){function n(t){var i;return(i=e.call(this,t)||this).name="InvalidArgumentsGraphError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(r(i),n.prototype.constructor),i}return t(n,e),n}(G),V=function(e){function n(t){var i;return(i=e.call(this,t)||this).name="NotFoundGraphError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(r(i),n.prototype.constructor),i}return t(n,e),n}(G),U=function(e){function n(t){var i;return(i=e.call(this,t)||this).name="UsageGraphError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(r(i),n.prototype.constructor),i}return t(n,e),n}(G);function q(e,t){this.key=e,this.attributes=t,this.clear()}function W(e,t){this.key=e,this.attributes=t,this.clear()}function Y(e,t){this.key=e,this.attributes=t,this.clear()}function j(e,t,n,i,o){this.key=t,this.attributes=o,this.undirected=e,this.source=n,this.target=i}function K(e,t,n,i,o,s,r){var a,l,c,u;if(i=""+i,0===n){if(!(a=e._nodes.get(i)))throw new V("Graph.".concat(t,': could not find the "').concat(i,'" node in the graph.'));c=o,u=s}else if(3===n){if(o=""+o,!(l=e._edges.get(o)))throw new V("Graph.".concat(t,': could not find the "').concat(o,'" edge in the graph.'));var h=l.source.key,d=l.target.key;if(i===h)a=l.target;else{if(i!==d)throw new V("Graph.".concat(t,': the "').concat(i,'" node is not attached to the "').concat(o,'" edge (').concat(h,", ").concat(d,")."));a=l.source}c=s,u=r}else{if(!(l=e._edges.get(i)))throw new V("Graph.".concat(t,': could not find the "').concat(i,'" edge in the graph.'));a=1===n?l.source:l.target,c=o,u=s}return[a,c,u]}q.prototype.clear=function(){this.inDegree=0,this.outDegree=0,this.undirectedDegree=0,this.undirectedLoops=0,this.directedLoops=0,this.in={},this.out={},this.undirected={}},W.prototype.clear=function(){this.inDegree=0,this.outDegree=0,this.directedLoops=0,this.in={},this.out={}},Y.prototype.clear=function(){this.undirectedDegree=0,this.undirectedLoops=0,this.undirected={}},j.prototype.attach=function(){var e="out",t="in";this.undirected&&(e=t="undirected");var n=this.source.key,i=this.target.key;this.source[e][i]=this,this.undirected&&n===i||(this.target[t][n]=this)},j.prototype.attachMulti=function(){var e="out",t="in",n=this.source.key,i=this.target.key;this.undirected&&(e=t="undirected");var o=this.source[e],s=o[i];if(void 0===s)return o[i]=this,void(this.undirected&&n===i||(this.target[t][n]=this));s.previous=this,this.next=s,o[i]=this,this.target[t][n]=this},j.prototype.detach=function(){var e=this.source.key,t=this.target.key,n="out",i="in";this.undirected&&(n=i="undirected"),delete this.source[n][t],delete this.target[i][e]},j.prototype.detachMulti=function(){var e=this.source.key,t=this.target.key,n="out",i="in";this.undirected&&(n=i="undirected"),void 0===this.previous?void 0===this.next?(delete this.source[n][t],delete this.target[i][e]):(this.next.previous=void 0,this.source[n][t]=this.next,this.target[i][e]=this.next):(this.previous.next=this.next,void 0!==this.next&&(this.next.previous=this.previous))};var z=[{name:function(e){return"get".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o){var s=K(this,t,n,e,i,o),r=s[0],a=s[1];return r.attributes[a]}}},{name:function(e){return"get".concat(e,"Attributes")},attacher:function(e,t,n){e.prototype[t]=function(e,i){return K(this,t,n,e,i)[0].attributes}}},{name:function(e){return"has".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o){var s=K(this,t,n,e,i,o),r=s[0],a=s[1];return r.attributes.hasOwnProperty(a)}}},{name:function(e){return"set".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o,s){var r=K(this,t,n,e,i,o,s),a=r[0],l=r[1],c=r[2];return a.attributes[l]=c,this.emit("nodeAttributesUpdated",{key:a.key,type:"set",attributes:a.attributes,name:l}),this}}},{name:function(e){return"update".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o,s){var r=K(this,t,n,e,i,o,s),a=r[0],l=r[1],c=r[2];if("function"!=typeof c)throw new B("Graph.".concat(t,": updater should be a function."));var u=a.attributes,h=c(u[l]);return u[l]=h,this.emit("nodeAttributesUpdated",{key:a.key,type:"set",attributes:a.attributes,name:l}),this}}},{name:function(e){return"remove".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o){var s=K(this,t,n,e,i,o),r=s[0],a=s[1];return delete r.attributes[a],this.emit("nodeAttributesUpdated",{key:r.key,type:"remove",attributes:r.attributes,name:a}),this}}},{name:function(e){return"replace".concat(e,"Attributes")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o){var s=K(this,t,n,e,i,o),r=s[0],a=s[1];if(!c(a))throw new B("Graph.".concat(t,": provided attributes are not a plain object."));return r.attributes=a,this.emit("nodeAttributesUpdated",{key:r.key,type:"replace",attributes:r.attributes}),this}}},{name:function(e){return"merge".concat(e,"Attributes")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o){var s=K(this,t,n,e,i,o),r=s[0],l=s[1];if(!c(l))throw new B("Graph.".concat(t,": provided attributes are not a plain object."));return a(r.attributes,l),this.emit("nodeAttributesUpdated",{key:r.key,type:"merge",attributes:r.attributes,data:l}),this}}},{name:function(e){return"update".concat(e,"Attributes")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o){var s=K(this,t,n,e,i,o),r=s[0],a=s[1];if("function"!=typeof a)throw new B("Graph.".concat(t,": provided updater is not a function."));return r.attributes=a(r.attributes),this.emit("nodeAttributesUpdated",{key:r.key,type:"update",attributes:r.attributes}),this}}}],Z=[{name:function(e){return"get".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i){var o;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new U("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>2){if(this.multi)throw new U("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var s=""+e,r=""+i;if(i=arguments[2],!(o=l(this,s,r,n)))throw new V("Graph.".concat(t,': could not find an edge for the given path ("').concat(s,'" - "').concat(r,'").'))}else{if("mixed"!==n)throw new U("Graph.".concat(t,": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type."));if(e=""+e,!(o=this._edges.get(e)))throw new V("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'))}return o.attributes[i]}}},{name:function(e){return"get".concat(e,"Attributes")},attacher:function(e,t,n){e.prototype[t]=function(e){var i;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new U("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>1){if(this.multi)throw new U("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var o=""+e,s=""+arguments[1];if(!(i=l(this,o,s,n)))throw new V("Graph.".concat(t,': could not find an edge for the given path ("').concat(o,'" - "').concat(s,'").'))}else{if("mixed"!==n)throw new U("Graph.".concat(t,": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type."));if(e=""+e,!(i=this._edges.get(e)))throw new V("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'))}return i.attributes}}},{name:function(e){return"has".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i){var o;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new U("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>2){if(this.multi)throw new U("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var s=""+e,r=""+i;if(i=arguments[2],!(o=l(this,s,r,n)))throw new V("Graph.".concat(t,': could not find an edge for the given path ("').concat(s,'" - "').concat(r,'").'))}else{if("mixed"!==n)throw new U("Graph.".concat(t,": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type."));if(e=""+e,!(o=this._edges.get(e)))throw new V("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'))}return o.attributes.hasOwnProperty(i)}}},{name:function(e){return"set".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o){var s;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new U("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>3){if(this.multi)throw new U("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var r=""+e,a=""+i;if(i=arguments[2],o=arguments[3],!(s=l(this,r,a,n)))throw new V("Graph.".concat(t,': could not find an edge for the given path ("').concat(r,'" - "').concat(a,'").'))}else{if("mixed"!==n)throw new U("Graph.".concat(t,": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type."));if(e=""+e,!(s=this._edges.get(e)))throw new V("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'))}return s.attributes[i]=o,this.emit("edgeAttributesUpdated",{key:s.key,type:"set",attributes:s.attributes,name:i}),this}}},{name:function(e){return"update".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o){var s;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new U("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>3){if(this.multi)throw new U("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var r=""+e,a=""+i;if(i=arguments[2],o=arguments[3],!(s=l(this,r,a,n)))throw new V("Graph.".concat(t,': could not find an edge for the given path ("').concat(r,'" - "').concat(a,'").'))}else{if("mixed"!==n)throw new U("Graph.".concat(t,": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type."));if(e=""+e,!(s=this._edges.get(e)))throw new V("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'))}if("function"!=typeof o)throw new B("Graph.".concat(t,": updater should be a function."));return s.attributes[i]=o(s.attributes[i]),this.emit("edgeAttributesUpdated",{key:s.key,type:"set",attributes:s.attributes,name:i}),this}}},{name:function(e){return"remove".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i){var o;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new U("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>2){if(this.multi)throw new U("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var s=""+e,r=""+i;if(i=arguments[2],!(o=l(this,s,r,n)))throw new V("Graph.".concat(t,': could not find an edge for the given path ("').concat(s,'" - "').concat(r,'").'))}else{if("mixed"!==n)throw new U("Graph.".concat(t,": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type."));if(e=""+e,!(o=this._edges.get(e)))throw new V("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'))}return delete o.attributes[i],this.emit("edgeAttributesUpdated",{key:o.key,type:"remove",attributes:o.attributes,name:i}),this}}},{name:function(e){return"replace".concat(e,"Attributes")},attacher:function(e,t,n){e.prototype[t]=function(e,i){var o;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new U("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>2){if(this.multi)throw new U("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var s=""+e,r=""+i;if(i=arguments[2],!(o=l(this,s,r,n)))throw new V("Graph.".concat(t,': could not find an edge for the given path ("').concat(s,'" - "').concat(r,'").'))}else{if("mixed"!==n)throw new U("Graph.".concat(t,": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type."));if(e=""+e,!(o=this._edges.get(e)))throw new V("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'))}if(!c(i))throw new B("Graph.".concat(t,": provided attributes are not a plain object."));return o.attributes=i,this.emit("edgeAttributesUpdated",{key:o.key,type:"replace",attributes:o.attributes}),this}}},{name:function(e){return"merge".concat(e,"Attributes")},attacher:function(e,t,n){e.prototype[t]=function(e,i){var o;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new U("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>2){if(this.multi)throw new U("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var s=""+e,r=""+i;if(i=arguments[2],!(o=l(this,s,r,n)))throw new V("Graph.".concat(t,': could not find an edge for the given path ("').concat(s,'" - "').concat(r,'").'))}else{if("mixed"!==n)throw new U("Graph.".concat(t,": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type."));if(e=""+e,!(o=this._edges.get(e)))throw new V("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'))}if(!c(i))throw new B("Graph.".concat(t,": provided attributes are not a plain object."));return a(o.attributes,i),this.emit("edgeAttributesUpdated",{key:o.key,type:"merge",attributes:o.attributes,data:i}),this}}},{name:function(e){return"update".concat(e,"Attributes")},attacher:function(e,t,n){e.prototype[t]=function(e,i){var o;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new U("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>2){if(this.multi)throw new U("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var s=""+e,r=""+i;if(i=arguments[2],!(o=l(this,s,r,n)))throw new V("Graph.".concat(t,': could not find an edge for the given path ("').concat(s,'" - "').concat(r,'").'))}else{if("mixed"!==n)throw new U("Graph.".concat(t,": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type."));if(e=""+e,!(o=this._edges.get(e)))throw new V("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'))}if("function"!=typeof i)throw new B("Graph.".concat(t,": provided updater is not a function."));return o.attributes=i(o.attributes),this.emit("edgeAttributesUpdated",{key:o.key,type:"update",attributes:o.attributes}),this}}}],X=_,Q=D,J=function(){var e=arguments,t=null,n=-1;return new X(function(){for(var i=null;;){if(null===t){if(++n>=e.length)return{done:!0};t=Q(e[n])}if(!0!==(i=t.next()).done)break;t=null}return i})},ee=[{name:"edges",type:"mixed"},{name:"inEdges",type:"directed",direction:"in"},{name:"outEdges",type:"directed",direction:"out"},{name:"inboundEdges",type:"mixed",direction:"in"},{name:"outboundEdges",type:"mixed",direction:"out"},{name:"directedEdges",type:"directed"},{name:"undirectedEdges",type:"undirected"}];function te(e,t,n,i){var o=!1;for(var s in t)if(s!==i){var r=t[s];if(o=n(r.key,r.attributes,r.source.key,r.target.key,r.source.attributes,r.target.attributes,r.undirected),e&&o)return r.key}}function ne(e,t,n,i){var o,s,r,a=!1;for(var l in t)if(l!==i){o=t[l];do{if(s=o.source,r=o.target,a=n(o.key,o.attributes,s.key,r.key,s.attributes,r.attributes,o.undirected),e&&a)return o.key;o=o.next}while(void 0!==o)}}function ie(e,t){var n,i=Object.keys(e),o=i.length,s=0;return new _(function(){do{if(n)n=n.next;else{if(s>=o)return{done:!0};var r=i[s++];if(r===t){n=void 0;continue}n=e[r]}}while(!n);return{done:!1,value:{edge:n.key,attributes:n.attributes,source:n.source.key,target:n.target.key,sourceAttributes:n.source.attributes,targetAttributes:n.target.attributes,undirected:n.undirected}}})}function oe(e,t,n,i){var o=t[n];if(o){var s=o.source,r=o.target;return i(o.key,o.attributes,s.key,r.key,s.attributes,r.attributes,o.undirected)&&e?o.key:void 0}}function se(e,t,n,i){var o=t[n];if(o){var s=!1;do{if(s=i(o.key,o.attributes,o.source.key,o.target.key,o.source.attributes,o.target.attributes,o.undirected),e&&s)return o.key;o=o.next}while(void 0!==o)}}function re(e,t){var n=e[t];return void 0!==n.next?new _(function(){if(!n)return{done:!0};var e={edge:n.key,attributes:n.attributes,source:n.source.key,target:n.target.key,sourceAttributes:n.source.attributes,targetAttributes:n.target.attributes,undirected:n.undirected};return n=n.next,{done:!1,value:e}}):_.of({edge:n.key,attributes:n.attributes,source:n.source.key,target:n.target.key,sourceAttributes:n.source.attributes,targetAttributes:n.target.attributes,undirected:n.undirected})}function ae(e,t,n,i){if(0!==t.size)for(var o,s,r="mixed"!==n&&n!==t.type,a="undirected"===n,l=!1,c=t._edges.values();!0!==(o=c.next()).done;)if(s=o.value,!r||s.undirected===a){var u=s,h=u.key,d=u.attributes,m=u.source,p=u.target;if(l=i(h,d,m.key,p.key,m.attributes,p.attributes,s.undirected),e&&l)return h}}function le(e,t,n,i,o,s){var r,a=t?ne:te;if("undirected"!==n){if("out"!==i&&(r=a(e,o.in,s),e&&r))return r;if("in"!==i&&(r=a(e,o.out,s,i?void 0:o.key),e&&r))return r}if("directed"!==n&&(r=a(e,o.undirected,s),e&&r))return r}function ce(e,t,n,i,o,s,r){var a,l=n?se:oe;if("undirected"!==t){if(void 0!==o.in&&"out"!==i&&(a=l(e,o.in,s,r),e&&a))return a;if(void 0!==o.out&&"in"!==i&&(i||o.key!==s)&&(a=l(e,o.out,s,r),e&&a))return a}if("directed"!==t&&void 0!==o.undirected&&(a=l(e,o.undirected,s,r),e&&a))return a}var ue=[{name:"neighbors",type:"mixed"},{name:"inNeighbors",type:"directed",direction:"in"},{name:"outNeighbors",type:"directed",direction:"out"},{name:"inboundNeighbors",type:"mixed",direction:"in"},{name:"outboundNeighbors",type:"mixed",direction:"out"},{name:"directedNeighbors",type:"directed"},{name:"undirectedNeighbors",type:"undirected"}];function he(){this.A=null,this.B=null}function de(e,t,n,i,o){for(var s in i){var r=i[s],a=r.source,l=r.target,c=a===n?l:a;if(!t||!t.has(c.key)){var u=o(c.key,c.attributes);if(e&&u)return c.key}}}function me(e,t,n,i,o){if("mixed"!==t){if("undirected"===t)return de(e,null,i,i.undirected,o);if("string"==typeof n)return de(e,null,i,i[n],o)}var s,r=new he;if("undirected"!==t){if("out"!==n){if(s=de(e,null,i,i.in,o),e&&s)return s;r.wrap(i.in)}if("in"!==n){if(s=de(e,r,i,i.out,o),e&&s)return s;r.wrap(i.out)}}if("directed"!==t&&(s=de(e,r,i,i.undirected,o),e&&s))return s}function pe(e,t,n){var i=Object.keys(n),o=i.length,s=0;return new _(function(){var r=null;do{if(s>=o)return e&&e.wrap(n),{done:!0};var a=n[i[s++]],l=a.source,c=a.target;r=l===t?c:l,e&&e.has(r.key)&&(r=null)}while(null===r);return{done:!1,value:{neighbor:r.key,attributes:r.attributes}}})}function ge(e,t,n,i,o){for(var s,r,a,l,c,u,h,d=i._nodes.values(),m=i.type;!0!==(s=d.next()).done;){var p=!1;if(r=s.value,"undirected"!==m)for(a in l=r.out){c=l[a];do{if(u=c.target,p=!0,h=o(r.key,u.key,r.attributes,u.attributes,c.key,c.attributes,c.undirected),e&&h)return c;c=c.next}while(c)}if("directed"!==m)for(a in l=r.undirected)if(!(t&&r.key>a)){c=l[a];do{if((u=c.target).key!==a&&(u=c.source),p=!0,h=o(r.key,u.key,r.attributes,u.attributes,c.key,c.attributes,c.undirected),e&&h)return c;c=c.next}while(c)}if(n&&!p&&(h=o(r.key,null,r.attributes,null,null,null,null),e&&h))return null}}function fe(e){if(!c(e))throw new B('Graph.import: invalid serialized node. A serialized node should be a plain object with at least a "key" property.');if(!("key"in e))throw new B("Graph.import: serialized node is missing its key.");if("attributes"in e&&(!c(e.attributes)||null===e.attributes))throw new B("Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.")}function ye(e){if(!c(e))throw new B('Graph.import: invalid serialized edge. A serialized edge should be a plain object with at least a "source" & "target" property.');if(!("source"in e))throw new B("Graph.import: serialized edge is missing its source.");if(!("target"in e))throw new B("Graph.import: serialized edge is missing its target.");if("attributes"in e&&(!c(e.attributes)||null===e.attributes))throw new B("Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.");if("undirected"in e&&"boolean"!=typeof e.undirected)throw new B("Graph.import: invalid undirectedness information. Undirected should be boolean or omitted.")}he.prototype.wrap=function(e){null===this.A?this.A=e:null===this.B&&(this.B=e)},he.prototype.has=function(e){return null!==this.A&&e in this.A||null!==this.B&&e in this.B};var be,we=(be=255&Math.floor(256*Math.random()),function(){return be++}),ve=new Set(["directed","undirected","mixed"]),Ce=new Set(["domain","_events","_eventsCount","_maxListeners"]),Ae={allowSelfLoops:!0,multi:!1,type:"mixed"};function Te(e,t,n){var i=new e.NodeDataClass(t,n);return e._nodes.set(t,i),e.emit("nodeAdded",{key:t,attributes:n}),i}function Ee(e,t,n,i,o,s,r,a){if(!i&&"undirected"===e.type)throw new U("Graph.".concat(t,": you cannot add a directed edge to an undirected graph. Use the #.addEdge or #.addUndirectedEdge instead."));if(i&&"directed"===e.type)throw new U("Graph.".concat(t,": you cannot add an undirected edge to a directed graph. Use the #.addEdge or #.addDirectedEdge instead."));if(a&&!c(a))throw new B("Graph.".concat(t,': invalid attributes. Expecting an object but got "').concat(a,'"'));if(s=""+s,r=""+r,a=a||{},!e.allowSelfLoops&&s===r)throw new U("Graph.".concat(t,': source & target are the same ("').concat(s,"\"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false."));var l=e._nodes.get(s),u=e._nodes.get(r);if(!l)throw new V("Graph.".concat(t,': source node "').concat(s,'" not found.'));if(!u)throw new V("Graph.".concat(t,': target node "').concat(r,'" not found.'));var h={key:null,undirected:i,source:s,target:r,attributes:a};if(n)o=e._edgeKeyGenerator();else if(o=""+o,e._edges.has(o))throw new U("Graph.".concat(t,': the "').concat(o,'" edge already exists in the graph.'));if(!e.multi&&(i?void 0!==l.undirected[r]:void 0!==l.out[r]))throw new U("Graph.".concat(t,': an edge linking "').concat(s,'" to "').concat(r,"\" already exists. If you really want to add multiple edges linking those nodes, you should create a multi graph by using the 'multi' option."));var d=new j(i,o,l,u,a);e._edges.set(o,d);var m=s===r;return i?(l.undirectedDegree++,u.undirectedDegree++,m&&(l.undirectedLoops++,e._undirectedSelfLoopCount++)):(l.outDegree++,u.inDegree++,m&&(l.directedLoops++,e._directedSelfLoopCount++)),e.multi?d.attachMulti():d.attach(),i?e._undirectedSize++:e._directedSize++,h.key=o,e.emit("edgeAdded",h),o}function Se(e,t,n,i,o,s,r,l,u){if(!i&&"undirected"===e.type)throw new U("Graph.".concat(t,": you cannot merge/update a directed edge to an undirected graph. Use the #.mergeEdge/#.updateEdge or #.addUndirectedEdge instead."));if(i&&"directed"===e.type)throw new U("Graph.".concat(t,": you cannot merge/update an undirected edge to a directed graph. Use the #.mergeEdge/#.updateEdge or #.addDirectedEdge instead."));if(l)if(u){if("function"!=typeof l)throw new B("Graph.".concat(t,': invalid updater function. Expecting a function but got "').concat(l,'"'))}else if(!c(l))throw new B("Graph.".concat(t,': invalid attributes. Expecting an object but got "').concat(l,'"'));var h;if(s=""+s,r=""+r,u&&(h=l,l=void 0),!e.allowSelfLoops&&s===r)throw new U("Graph.".concat(t,': source & target are the same ("').concat(s,"\"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false."));var d,m,p=e._nodes.get(s),g=e._nodes.get(r);if(!n&&(d=e._edges.get(o))){if(!(d.source.key===s&&d.target.key===r||i&&d.source.key===r&&d.target.key===s))throw new U("Graph.".concat(t,': inconsistency detected when attempting to merge the "').concat(o,'" edge with "').concat(s,'" source & "').concat(r,'" target vs. ("').concat(d.source.key,'", "').concat(d.target.key,'").'));m=d}if(m||e.multi||!p||(m=i?p.undirected[r]:p.out[r]),m){var f=[m.key,!1,!1,!1];if(u?!h:!l)return f;if(u){var y=m.attributes;m.attributes=h(y),e.emit("edgeAttributesUpdated",{type:"replace",key:m.key,attributes:m.attributes})}else a(m.attributes,l),e.emit("edgeAttributesUpdated",{type:"merge",key:m.key,attributes:m.attributes,data:l});return f}l=l||{},u&&h&&(l=h(l));var b={key:null,undirected:i,source:s,target:r,attributes:l};if(n)o=e._edgeKeyGenerator();else if(o=""+o,e._edges.has(o))throw new U("Graph.".concat(t,': the "').concat(o,'" edge already exists in the graph.'));var w=!1,v=!1;p||(p=Te(e,s,{}),w=!0,s===r&&(g=p,v=!0)),g||(g=Te(e,r,{}),v=!0),d=new j(i,o,p,g,l),e._edges.set(o,d);var C=s===r;return i?(p.undirectedDegree++,g.undirectedDegree++,C&&(p.undirectedLoops++,e._undirectedSelfLoopCount++)):(p.outDegree++,g.inDegree++,C&&(p.directedLoops++,e._directedSelfLoopCount++)),e.multi?d.attachMulti():d.attach(),i?e._undirectedSize++:e._directedSize++,b.key=o,e.emit("edgeAdded",b),[o,!0,w,v]}function Me(e,t){e._edges.delete(t.key);var n=t.source,i=t.target,o=t.attributes,s=t.undirected,r=n===i;s?(n.undirectedDegree--,i.undirectedDegree--,r&&(n.undirectedLoops--,e._undirectedSelfLoopCount--)):(n.outDegree--,i.inDegree--,r&&(n.directedLoops--,e._directedSelfLoopCount--)),e.multi?t.detachMulti():t.detach(),s?e._undirectedSize--:e._directedSize--,e.emit("edgeDropped",{key:t.key,attributes:o,source:n.key,target:i.key,undirected:s})}var xe=function(n){function i(e){var t;if(t=n.call(this)||this,"boolean"!=typeof(e=a({},Ae,e)).multi)throw new B("Graph.constructor: invalid 'multi' option. Expecting a boolean but got \"".concat(e.multi,'".'));if(!ve.has(e.type))throw new B('Graph.constructor: invalid \'type\' option. Should be one of "mixed", "directed" or "undirected" but got "'.concat(e.type,'".'));if("boolean"!=typeof e.allowSelfLoops)throw new B("Graph.constructor: invalid 'allowSelfLoops' option. Expecting a boolean but got \"".concat(e.allowSelfLoops,'".'));var i="mixed"===e.type?q:"directed"===e.type?W:Y;h(r(t),"NodeDataClass",i);var o="geid_"+we()+"_",s=0;return h(r(t),"_attributes",{}),h(r(t),"_nodes",new Map),h(r(t),"_edges",new Map),h(r(t),"_directedSize",0),h(r(t),"_undirectedSize",0),h(r(t),"_directedSelfLoopCount",0),h(r(t),"_undirectedSelfLoopCount",0),h(r(t),"_edgeKeyGenerator",function(){var e;do{e=o+s++}while(t._edges.has(e));return e}),h(r(t),"_options",e),Ce.forEach(function(e){return h(r(t),e,t[e])}),d(r(t),"order",function(){return t._nodes.size}),d(r(t),"size",function(){return t._edges.size}),d(r(t),"directedSize",function(){return t._directedSize}),d(r(t),"undirectedSize",function(){return t._undirectedSize}),d(r(t),"selfLoopCount",function(){return t._directedSelfLoopCount+t._undirectedSelfLoopCount}),d(r(t),"directedSelfLoopCount",function(){return t._directedSelfLoopCount}),d(r(t),"undirectedSelfLoopCount",function(){return t._undirectedSelfLoopCount}),d(r(t),"multi",t._options.multi),d(r(t),"type",t._options.type),d(r(t),"allowSelfLoops",t._options.allowSelfLoops),d(r(t),"implementation",function(){return"graphology"}),t}t(i,n);var o=i.prototype;return o._resetInstanceCounters=function(){this._directedSize=0,this._undirectedSize=0,this._directedSelfLoopCount=0,this._undirectedSelfLoopCount=0},o.hasNode=function(e){return this._nodes.has(""+e)},o.hasDirectedEdge=function(e,t){if("undirected"===this.type)return!1;if(1===arguments.length){var n=""+e,i=this._edges.get(n);return!!i&&!i.undirected}if(2===arguments.length){e=""+e,t=""+t;var o=this._nodes.get(e);return!!o&&o.out.hasOwnProperty(t)}throw new B("Graph.hasDirectedEdge: invalid arity (".concat(arguments.length,", instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target."))},o.hasUndirectedEdge=function(e,t){if("directed"===this.type)return!1;if(1===arguments.length){var n=""+e,i=this._edges.get(n);return!!i&&i.undirected}if(2===arguments.length){e=""+e,t=""+t;var o=this._nodes.get(e);return!!o&&o.undirected.hasOwnProperty(t)}throw new B("Graph.hasDirectedEdge: invalid arity (".concat(arguments.length,", instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target."))},o.hasEdge=function(e,t){if(1===arguments.length){var n=""+e;return this._edges.has(n)}if(2===arguments.length){e=""+e,t=""+t;var i=this._nodes.get(e);return!!i&&(void 0!==i.out&&i.out.hasOwnProperty(t)||void 0!==i.undirected&&i.undirected.hasOwnProperty(t))}throw new B("Graph.hasEdge: invalid arity (".concat(arguments.length,", instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target."))},o.directedEdge=function(e,t){if("undirected"!==this.type){if(e=""+e,t=""+t,this.multi)throw new U("Graph.directedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.directedEdges instead.");var n=this._nodes.get(e);if(!n)throw new V('Graph.directedEdge: could not find the "'.concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new V('Graph.directedEdge: could not find the "'.concat(t,'" target node in the graph.'));var i=n.out&&n.out[t]||void 0;return i?i.key:void 0}},o.undirectedEdge=function(e,t){if("directed"!==this.type){if(e=""+e,t=""+t,this.multi)throw new U("Graph.undirectedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.undirectedEdges instead.");var n=this._nodes.get(e);if(!n)throw new V('Graph.undirectedEdge: could not find the "'.concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new V('Graph.undirectedEdge: could not find the "'.concat(t,'" target node in the graph.'));var i=n.undirected&&n.undirected[t]||void 0;return i?i.key:void 0}},o.edge=function(e,t){if(this.multi)throw new U("Graph.edge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.edges instead.");e=""+e,t=""+t;var n=this._nodes.get(e);if(!n)throw new V('Graph.edge: could not find the "'.concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new V('Graph.edge: could not find the "'.concat(t,'" target node in the graph.'));var i=n.out&&n.out[t]||n.undirected&&n.undirected[t]||void 0;if(i)return i.key},o.areDirectedNeighbors=function(e,t){e=""+e,t=""+t;var n=this._nodes.get(e);if(!n)throw new V('Graph.areDirectedNeighbors: could not find the "'.concat(e,'" node in the graph.'));return"undirected"!==this.type&&(t in n.in||t in n.out)},o.areOutNeighbors=function(e,t){e=""+e,t=""+t;var n=this._nodes.get(e);if(!n)throw new V('Graph.areOutNeighbors: could not find the "'.concat(e,'" node in the graph.'));return"undirected"!==this.type&&t in n.out},o.areInNeighbors=function(e,t){e=""+e,t=""+t;var n=this._nodes.get(e);if(!n)throw new V('Graph.areInNeighbors: could not find the "'.concat(e,'" node in the graph.'));return"undirected"!==this.type&&t in n.in},o.areUndirectedNeighbors=function(e,t){e=""+e,t=""+t;var n=this._nodes.get(e);if(!n)throw new V('Graph.areUndirectedNeighbors: could not find the "'.concat(e,'" node in the graph.'));return"directed"!==this.type&&t in n.undirected},o.areNeighbors=function(e,t){e=""+e,t=""+t;var n=this._nodes.get(e);if(!n)throw new V('Graph.areNeighbors: could not find the "'.concat(e,'" node in the graph.'));return"undirected"!==this.type&&(t in n.in||t in n.out)||"directed"!==this.type&&t in n.undirected},o.areInboundNeighbors=function(e,t){e=""+e,t=""+t;var n=this._nodes.get(e);if(!n)throw new V('Graph.areInboundNeighbors: could not find the "'.concat(e,'" node in the graph.'));return"undirected"!==this.type&&t in n.in||"directed"!==this.type&&t in n.undirected},o.areOutboundNeighbors=function(e,t){e=""+e,t=""+t;var n=this._nodes.get(e);if(!n)throw new V('Graph.areOutboundNeighbors: could not find the "'.concat(e,'" node in the graph.'));return"undirected"!==this.type&&t in n.out||"directed"!==this.type&&t in n.undirected},o.inDegree=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.inDegree: could not find the "'.concat(e,'" node in the graph.'));return"undirected"===this.type?0:t.inDegree},o.outDegree=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.outDegree: could not find the "'.concat(e,'" node in the graph.'));return"undirected"===this.type?0:t.outDegree},o.directedDegree=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.directedDegree: could not find the "'.concat(e,'" node in the graph.'));return"undirected"===this.type?0:t.inDegree+t.outDegree},o.undirectedDegree=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.undirectedDegree: could not find the "'.concat(e,'" node in the graph.'));return"directed"===this.type?0:t.undirectedDegree},o.inboundDegree=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.inboundDegree: could not find the "'.concat(e,'" node in the graph.'));var n=0;return"directed"!==this.type&&(n+=t.undirectedDegree),"undirected"!==this.type&&(n+=t.inDegree),n},o.outboundDegree=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.outboundDegree: could not find the "'.concat(e,'" node in the graph.'));var n=0;return"directed"!==this.type&&(n+=t.undirectedDegree),"undirected"!==this.type&&(n+=t.outDegree),n},o.degree=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.degree: could not find the "'.concat(e,'" node in the graph.'));var n=0;return"directed"!==this.type&&(n+=t.undirectedDegree),"undirected"!==this.type&&(n+=t.inDegree+t.outDegree),n},o.inDegreeWithoutSelfLoops=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.inDegreeWithoutSelfLoops: could not find the "'.concat(e,'" node in the graph.'));return"undirected"===this.type?0:t.inDegree-t.directedLoops},o.outDegreeWithoutSelfLoops=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.outDegreeWithoutSelfLoops: could not find the "'.concat(e,'" node in the graph.'));return"undirected"===this.type?0:t.outDegree-t.directedLoops},o.directedDegreeWithoutSelfLoops=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.directedDegreeWithoutSelfLoops: could not find the "'.concat(e,'" node in the graph.'));return"undirected"===this.type?0:t.inDegree+t.outDegree-2*t.directedLoops},o.undirectedDegreeWithoutSelfLoops=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.undirectedDegreeWithoutSelfLoops: could not find the "'.concat(e,'" node in the graph.'));return"directed"===this.type?0:t.undirectedDegree-2*t.undirectedLoops},o.inboundDegreeWithoutSelfLoops=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.inboundDegreeWithoutSelfLoops: could not find the "'.concat(e,'" node in the graph.'));var n=0,i=0;return"directed"!==this.type&&(n+=t.undirectedDegree,i+=2*t.undirectedLoops),"undirected"!==this.type&&(n+=t.inDegree,i+=t.directedLoops),n-i},o.outboundDegreeWithoutSelfLoops=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.outboundDegreeWithoutSelfLoops: could not find the "'.concat(e,'" node in the graph.'));var n=0,i=0;return"directed"!==this.type&&(n+=t.undirectedDegree,i+=2*t.undirectedLoops),"undirected"!==this.type&&(n+=t.outDegree,i+=t.directedLoops),n-i},o.degreeWithoutSelfLoops=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.degreeWithoutSelfLoops: could not find the "'.concat(e,'" node in the graph.'));var n=0,i=0;return"directed"!==this.type&&(n+=t.undirectedDegree,i+=2*t.undirectedLoops),"undirected"!==this.type&&(n+=t.inDegree+t.outDegree,i+=2*t.directedLoops),n-i},o.source=function(e){e=""+e;var t=this._edges.get(e);if(!t)throw new V('Graph.source: could not find the "'.concat(e,'" edge in the graph.'));return t.source.key},o.target=function(e){e=""+e;var t=this._edges.get(e);if(!t)throw new V('Graph.target: could not find the "'.concat(e,'" edge in the graph.'));return t.target.key},o.extremities=function(e){e=""+e;var t=this._edges.get(e);if(!t)throw new V('Graph.extremities: could not find the "'.concat(e,'" edge in the graph.'));return[t.source.key,t.target.key]},o.opposite=function(e,t){e=""+e,t=""+t;var n=this._edges.get(t);if(!n)throw new V('Graph.opposite: could not find the "'.concat(t,'" edge in the graph.'));var i=n.source.key,o=n.target.key;if(e===i)return o;if(e===o)return i;throw new V('Graph.opposite: the "'.concat(e,'" node is not attached to the "').concat(t,'" edge (').concat(i,", ").concat(o,")."))},o.hasExtremity=function(e,t){e=""+e,t=""+t;var n=this._edges.get(e);if(!n)throw new V('Graph.hasExtremity: could not find the "'.concat(e,'" edge in the graph.'));return n.source.key===t||n.target.key===t},o.isUndirected=function(e){e=""+e;var t=this._edges.get(e);if(!t)throw new V('Graph.isUndirected: could not find the "'.concat(e,'" edge in the graph.'));return t.undirected},o.isDirected=function(e){e=""+e;var t=this._edges.get(e);if(!t)throw new V('Graph.isDirected: could not find the "'.concat(e,'" edge in the graph.'));return!t.undirected},o.isSelfLoop=function(e){e=""+e;var t=this._edges.get(e);if(!t)throw new V('Graph.isSelfLoop: could not find the "'.concat(e,'" edge in the graph.'));return t.source===t.target},o.addNode=function(e,t){var n=function(e,t,n){if(n&&!c(n))throw new B('Graph.addNode: invalid attributes. Expecting an object but got "'.concat(n,'"'));if(t=""+t,n=n||{},e._nodes.has(t))throw new U('Graph.addNode: the "'.concat(t,'" node already exist in the graph.'));var i=new e.NodeDataClass(t,n);return e._nodes.set(t,i),e.emit("nodeAdded",{key:t,attributes:n}),i}(this,e,t);return n.key},o.mergeNode=function(e,t){if(t&&!c(t))throw new B('Graph.mergeNode: invalid attributes. Expecting an object but got "'.concat(t,'"'));e=""+e,t=t||{};var n=this._nodes.get(e);return n?(t&&(a(n.attributes,t),this.emit("nodeAttributesUpdated",{type:"merge",key:e,attributes:n.attributes,data:t})),[e,!1]):(n=new this.NodeDataClass(e,t),this._nodes.set(e,n),this.emit("nodeAdded",{key:e,attributes:t}),[e,!0])},o.updateNode=function(e,t){if(t&&"function"!=typeof t)throw new B('Graph.updateNode: invalid updater function. Expecting a function but got "'.concat(t,'"'));e=""+e;var n=this._nodes.get(e);if(n){if(t){var i=n.attributes;n.attributes=t(i),this.emit("nodeAttributesUpdated",{type:"replace",key:e,attributes:n.attributes})}return[e,!1]}var o=t?t({}):{};return n=new this.NodeDataClass(e,o),this._nodes.set(e,n),this.emit("nodeAdded",{key:e,attributes:o}),[e,!0]},o.dropNode=function(e){e=""+e;var t,n=this._nodes.get(e);if(!n)throw new V('Graph.dropNode: could not find the "'.concat(e,'" node in the graph.'));if("undirected"!==this.type){for(var i in n.out){t=n.out[i];do{Me(this,t),t=t.next}while(t)}for(var o in n.in){t=n.in[o];do{Me(this,t),t=t.next}while(t)}}if("directed"!==this.type)for(var s in n.undirected){t=n.undirected[s];do{Me(this,t),t=t.next}while(t)}this._nodes.delete(e),this.emit("nodeDropped",{key:e,attributes:n.attributes})},o.dropEdge=function(e){var t;if(arguments.length>1){var n=""+arguments[0],i=""+arguments[1];if(!(t=l(this,n,i,this.type)))throw new V('Graph.dropEdge: could not find the "'.concat(n,'" -> "').concat(i,'" edge in the graph.'))}else if(e=""+e,!(t=this._edges.get(e)))throw new V('Graph.dropEdge: could not find the "'.concat(e,'" edge in the graph.'));return Me(this,t),this},o.dropDirectedEdge=function(e,t){if(arguments.length<2)throw new U("Graph.dropDirectedEdge: it does not make sense to try and drop a directed edge by key. What if the edge with this key is undirected? Use #.dropEdge for this purpose instead.");if(this.multi)throw new U("Graph.dropDirectedEdge: cannot use a {source,target} combo when dropping an edge in a MultiGraph since we cannot infer the one you want to delete as there could be multiple ones.");var n=l(this,e=""+e,t=""+t,"directed");if(!n)throw new V('Graph.dropDirectedEdge: could not find a "'.concat(e,'" -> "').concat(t,'" edge in the graph.'));return Me(this,n),this},o.dropUndirectedEdge=function(e,t){if(arguments.length<2)throw new U("Graph.dropUndirectedEdge: it does not make sense to drop a directed edge by key. What if the edge with this key is undirected? Use #.dropEdge for this purpose instead.");if(this.multi)throw new U("Graph.dropUndirectedEdge: cannot use a {source,target} combo when dropping an edge in a MultiGraph since we cannot infer the one you want to delete as there could be multiple ones.");var n=l(this,e,t,"undirected");if(!n)throw new V('Graph.dropUndirectedEdge: could not find a "'.concat(e,'" -> "').concat(t,'" edge in the graph.'));return Me(this,n),this},o.clear=function(){this._edges.clear(),this._nodes.clear(),this._resetInstanceCounters(),this.emit("cleared")},o.clearEdges=function(){for(var e,t=this._nodes.values();!0!==(e=t.next()).done;)e.value.clear();this._edges.clear(),this._resetInstanceCounters(),this.emit("edgesCleared")},o.getAttribute=function(e){return this._attributes[e]},o.getAttributes=function(){return this._attributes},o.hasAttribute=function(e){return this._attributes.hasOwnProperty(e)},o.setAttribute=function(e,t){return this._attributes[e]=t,this.emit("attributesUpdated",{type:"set",attributes:this._attributes,name:e}),this},o.updateAttribute=function(e,t){if("function"!=typeof t)throw new B("Graph.updateAttribute: updater should be a function.");var n=this._attributes[e];return this._attributes[e]=t(n),this.emit("attributesUpdated",{type:"set",attributes:this._attributes,name:e}),this},o.removeAttribute=function(e){return delete this._attributes[e],this.emit("attributesUpdated",{type:"remove",attributes:this._attributes,name:e}),this},o.replaceAttributes=function(e){if(!c(e))throw new B("Graph.replaceAttributes: provided attributes are not a plain object.");return this._attributes=e,this.emit("attributesUpdated",{type:"replace",attributes:this._attributes}),this},o.mergeAttributes=function(e){if(!c(e))throw new B("Graph.mergeAttributes: provided attributes are not a plain object.");return a(this._attributes,e),this.emit("attributesUpdated",{type:"merge",attributes:this._attributes,data:e}),this},o.updateAttributes=function(e){if("function"!=typeof e)throw new B("Graph.updateAttributes: provided updater is not a function.");return this._attributes=e(this._attributes),this.emit("attributesUpdated",{type:"update",attributes:this._attributes}),this},o.updateEachNodeAttributes=function(e,t){if("function"!=typeof e)throw new B("Graph.updateEachNodeAttributes: expecting an updater function.");if(t&&!m(t))throw new B("Graph.updateEachNodeAttributes: invalid hints. Expecting an object having the following shape: {attributes?: [string]}");for(var n,i,o=this._nodes.values();!0!==(n=o.next()).done;)(i=n.value).attributes=e(i.key,i.attributes);this.emit("eachNodeAttributesUpdated",{hints:t||null})},o.updateEachEdgeAttributes=function(e,t){if("function"!=typeof e)throw new B("Graph.updateEachEdgeAttributes: expecting an updater function.");if(t&&!m(t))throw new B("Graph.updateEachEdgeAttributes: invalid hints. Expecting an object having the following shape: {attributes?: [string]}");for(var n,i,o,s,r=this._edges.values();!0!==(n=r.next()).done;)o=(i=n.value).source,s=i.target,i.attributes=e(i.key,i.attributes,o.key,s.key,o.attributes,s.attributes,i.undirected);this.emit("eachEdgeAttributesUpdated",{hints:t||null})},o.forEachAdjacencyEntry=function(e){if("function"!=typeof e)throw new B("Graph.forEachAdjacencyEntry: expecting a callback.");ge(!1,!1,!1,this,e)},o.forEachAdjacencyEntryWithOrphans=function(e){if("function"!=typeof e)throw new B("Graph.forEachAdjacencyEntryWithOrphans: expecting a callback.");ge(!1,!1,!0,this,e)},o.forEachAssymetricAdjacencyEntry=function(e){if("function"!=typeof e)throw new B("Graph.forEachAssymetricAdjacencyEntry: expecting a callback.");ge(!1,!0,!1,this,e)},o.forEachAssymetricAdjacencyEntryWithOrphans=function(e){if("function"!=typeof e)throw new B("Graph.forEachAssymetricAdjacencyEntryWithOrphans: expecting a callback.");ge(!1,!0,!0,this,e)},o.nodes=function(){return"function"==typeof Array.from?Array.from(this._nodes.keys()):k(this._nodes.keys(),this._nodes.size)},o.forEachNode=function(e){if("function"!=typeof e)throw new B("Graph.forEachNode: expecting a callback.");for(var t,n,i=this._nodes.values();!0!==(t=i.next()).done;)e((n=t.value).key,n.attributes)},o.findNode=function(e){if("function"!=typeof e)throw new B("Graph.findNode: expecting a callback.");for(var t,n,i=this._nodes.values();!0!==(t=i.next()).done;)if(e((n=t.value).key,n.attributes))return n.key},o.mapNodes=function(e){if("function"!=typeof e)throw new B("Graph.mapNode: expecting a callback.");for(var t,n,i=this._nodes.values(),o=new Array(this.order),s=0;!0!==(t=i.next()).done;)n=t.value,o[s++]=e(n.key,n.attributes);return o},o.someNode=function(e){if("function"!=typeof e)throw new B("Graph.someNode: expecting a callback.");for(var t,n,i=this._nodes.values();!0!==(t=i.next()).done;)if(e((n=t.value).key,n.attributes))return!0;return!1},o.everyNode=function(e){if("function"!=typeof e)throw new B("Graph.everyNode: expecting a callback.");for(var t,n,i=this._nodes.values();!0!==(t=i.next()).done;)if(!e((n=t.value).key,n.attributes))return!1;return!0},o.filterNodes=function(e){if("function"!=typeof e)throw new B("Graph.filterNodes: expecting a callback.");for(var t,n,i=this._nodes.values(),o=[];!0!==(t=i.next()).done;)e((n=t.value).key,n.attributes)&&o.push(n.key);return o},o.reduceNodes=function(e,t){if("function"!=typeof e)throw new B("Graph.reduceNodes: expecting a callback.");if(arguments.length<2)throw new B("Graph.reduceNodes: missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array.");for(var n,i,o=t,s=this._nodes.values();!0!==(n=s.next()).done;)o=e(o,(i=n.value).key,i.attributes);return o},o.nodeEntries=function(){var e=this._nodes.values();return new _(function(){var t=e.next();if(t.done)return t;var n=t.value;return{value:{node:n.key,attributes:n.attributes},done:!1}})},o.export=function(){var e=this,t=new Array(this._nodes.size),n=0;this._nodes.forEach(function(e,i){t[n++]=function(e,t){var n={key:e};return u(t.attributes)||(n.attributes=a({},t.attributes)),n}(i,e)});var i=new Array(this._edges.size);return n=0,this._edges.forEach(function(t,o){i[n++]=function(e,t,n){var i={key:t,source:n.source.key,target:n.target.key};return u(n.attributes)||(i.attributes=a({},n.attributes)),"mixed"===e&&n.undirected&&(i.undirected=!0),i}(e.type,o,t)}),{options:{type:this.type,multi:this.multi,allowSelfLoops:this.allowSelfLoops},attributes:this.getAttributes(),nodes:t,edges:i}},o.import=function(e){var t,n,o,s,r,a=this,l=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(e instanceof i)return e.forEachNode(function(e,t){l?a.mergeNode(e,t):a.addNode(e,t)}),e.forEachEdge(function(e,t,n,i,o,s,r){l?r?a.mergeUndirectedEdgeWithKey(e,n,i,t):a.mergeDirectedEdgeWithKey(e,n,i,t):r?a.addUndirectedEdgeWithKey(e,n,i,t):a.addDirectedEdgeWithKey(e,n,i,t)}),this;if(!c(e))throw new B("Graph.import: invalid argument. Expecting a serialized graph or, alternatively, a Graph instance.");if(e.attributes){if(!c(e.attributes))throw new B("Graph.import: invalid attributes. Expecting a plain object.");l?this.mergeAttributes(e.attributes):this.replaceAttributes(e.attributes)}if(e.nodes){if(o=e.nodes,!Array.isArray(o))throw new B("Graph.import: invalid nodes. Expecting an array.");for(t=0,n=o.length;t<n;t++){fe(s=o[t]);var u=s,h=u.key,d=u.attributes;l?this.mergeNode(h,d):this.addNode(h,d)}}if(e.edges){var m=!1;if("undirected"===this.type&&(m=!0),o=e.edges,!Array.isArray(o))throw new B("Graph.import: invalid edges. Expecting an array.");for(t=0,n=o.length;t<n;t++){ye(r=o[t]);var p=r,g=p.source,f=p.target,y=p.attributes,b=p.undirected,w=void 0===b?m:b;"key"in r?(l?w?this.mergeUndirectedEdgeWithKey:this.mergeDirectedEdgeWithKey:w?this.addUndirectedEdgeWithKey:this.addDirectedEdgeWithKey).call(this,r.key,g,f,y):(l?w?this.mergeUndirectedEdge:this.mergeDirectedEdge:w?this.addUndirectedEdge:this.addDirectedEdge).call(this,g,f,y)}}return this},o.nullCopy=function(e){var t=new i(a({},this._options,e));return t.replaceAttributes(a({},this.getAttributes())),t},o.emptyCopy=function(e){var t=this.nullCopy(e);return this._nodes.forEach(function(e,n){var i=a({},e.attributes);e=new t.NodeDataClass(n,i),t._nodes.set(n,e)}),t},o.copy=function(e){if("string"==typeof(e=e||{}).type&&e.type!==this.type&&"mixed"!==e.type)throw new U('Graph.copy: cannot create an incompatible copy from "'.concat(this.type,'" type to "').concat(e.type,'" because this would mean losing information about the current graph.'));if("boolean"==typeof e.multi&&e.multi!==this.multi&&!0!==e.multi)throw new U("Graph.copy: cannot create an incompatible copy by downgrading a multi graph to a simple one because this would mean losing information about the current graph.");if("boolean"==typeof e.allowSelfLoops&&e.allowSelfLoops!==this.allowSelfLoops&&!0!==e.allowSelfLoops)throw new U("Graph.copy: cannot create an incompatible copy from a graph allowing self loops to one that does not because this would mean losing information about the current graph.");for(var t,n,i=this.emptyCopy(e),o=this._edges.values();!0!==(t=o.next()).done;)Ee(i,"copy",!1,(n=t.value).undirected,n.key,n.source.key,n.target.key,a({},n.attributes));return i},o.toJSON=function(){return this.export()},o.toString=function(){return"[object Graph]"},o.inspect=function(){var t=this,n={};this._nodes.forEach(function(e,t){n[t]=e.attributes});var i={},o={};this._edges.forEach(function(e,n){var s,r=e.undirected?"--":"->",a="",l=e.source.key,c=e.target.key;e.undirected&&l>c&&(s=l,l=c,c=s);var u="(".concat(l,")").concat(r,"(").concat(c,")");n.startsWith("geid_")?t.multi&&(void 0===o[u]?o[u]=0:o[u]++,a+="".concat(o[u],". ")):a+="[".concat(n,"]: "),i[a+=u]=e.attributes});var s={};for(var r in this)this.hasOwnProperty(r)&&!Ce.has(r)&&"function"!=typeof this[r]&&"symbol"!==e(r)&&(s[r]=this[r]);return s.attributes=this._attributes,s.nodes=n,s.edges=i,h(s,"constructor",this.constructor),s},i}(g.exports.EventEmitter);"undefined"!=typeof Symbol&&(xe.prototype[Symbol.for("nodejs.util.inspect.custom")]=xe.prototype.inspect),[{name:function(e){return"".concat(e,"Edge")},generateKey:!0},{name:function(e){return"".concat(e,"DirectedEdge")},generateKey:!0,type:"directed"},{name:function(e){return"".concat(e,"UndirectedEdge")},generateKey:!0,type:"undirected"},{name:function(e){return"".concat(e,"EdgeWithKey")}},{name:function(e){return"".concat(e,"DirectedEdgeWithKey")},type:"directed"},{name:function(e){return"".concat(e,"UndirectedEdgeWithKey")},type:"undirected"}].forEach(function(e){["add","merge","update"].forEach(function(t){var n=e.name(t),i="add"===t?Ee:Se;e.generateKey?xe.prototype[n]=function(o,s,r){return i(this,n,!0,"undirected"===(e.type||this.type),null,o,s,r,"update"===t)}:xe.prototype[n]=function(o,s,r,a){return i(this,n,!1,"undirected"===(e.type||this.type),o,s,r,a,"update"===t)}})}),function(e){z.forEach(function(t){var n=t.name,i=t.attacher;i(e,n("Node"),0),i(e,n("Source"),1),i(e,n("Target"),2),i(e,n("Opposite"),3)})}(xe),function(e){Z.forEach(function(t){var n=t.name,i=t.attacher;i(e,n("Edge"),"mixed"),i(e,n("DirectedEdge"),"directed"),i(e,n("UndirectedEdge"),"undirected")})}(xe),function(e){ee.forEach(function(t){!function(e,t){var n=t.name,i=t.type,o=t.direction;e.prototype[n]=function(e,t){if("mixed"!==i&&"mixed"!==this.type&&i!==this.type)return[];if(!arguments.length)return function(e,t){if(0===e.size)return[];if("mixed"===t||t===e.type)return"function"==typeof Array.from?Array.from(e._edges.keys()):k(e._edges.keys(),e._edges.size);for(var n,i,o="undirected"===t?e.undirectedSize:e.directedSize,s=new Array(o),r="undirected"===t,a=e._edges.values(),l=0;!0!==(n=a.next()).done;)(i=n.value).undirected===r&&(s[l++]=i.key);return s}(this,i);if(1===arguments.length){e=""+e;var s=this._nodes.get(e);if(void 0===s)throw new V("Graph.".concat(n,': could not find the "').concat(e,'" node in the graph.'));return function(e,t,n,i){var o=[];return le(!1,e,t,n,i,function(e){o.push(e)}),o}(this.multi,"mixed"===i?this.type:i,o,s)}if(2===arguments.length){e=""+e,t=""+t;var r=this._nodes.get(e);if(!r)throw new V("Graph.".concat(n,': could not find the "').concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new V("Graph.".concat(n,': could not find the "').concat(t,'" target node in the graph.'));return function(e,t,n,i,o){var s=[];return ce(!1,e,t,n,i,o,function(e){s.push(e)}),s}(i,this.multi,o,r,t)}throw new B("Graph.".concat(n,": too many arguments (expecting 0, 1 or 2 and got ").concat(arguments.length,")."))}}(e,t),function(e,t){var n=t.name,i=t.type,o=t.direction,s="forEach"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[s]=function(e,t,n){if("mixed"===i||"mixed"===this.type||i===this.type){if(1===arguments.length)return ae(!1,this,i,n=e);if(2===arguments.length){e=""+e,n=t;var r=this._nodes.get(e);if(void 0===r)throw new V("Graph.".concat(s,': could not find the "').concat(e,'" node in the graph.'));return le(!1,this.multi,"mixed"===i?this.type:i,o,r,n)}if(3===arguments.length){e=""+e,t=""+t;var a=this._nodes.get(e);if(!a)throw new V("Graph.".concat(s,': could not find the "').concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new V("Graph.".concat(s,': could not find the "').concat(t,'" target node in the graph.'));return ce(!1,i,this.multi,o,a,t,n)}throw new B("Graph.".concat(s,": too many arguments (expecting 1, 2 or 3 and got ").concat(arguments.length,")."))}};var r="map"+n[0].toUpperCase()+n.slice(1);e.prototype[r]=function(){var e,t=Array.prototype.slice.call(arguments),n=t.pop();if(0===t.length){var o=0;"directed"!==i&&(o+=this.undirectedSize),"undirected"!==i&&(o+=this.directedSize),e=new Array(o);var r=0;t.push(function(t,i,o,s,a,l,c){e[r++]=n(t,i,o,s,a,l,c)})}else e=[],t.push(function(t,i,o,s,r,a,l){e.push(n(t,i,o,s,r,a,l))});return this[s].apply(this,t),e};var a="filter"+n[0].toUpperCase()+n.slice(1);e.prototype[a]=function(){var e=Array.prototype.slice.call(arguments),t=e.pop(),n=[];return e.push(function(e,i,o,s,r,a,l){t(e,i,o,s,r,a,l)&&n.push(e)}),this[s].apply(this,e),n};var l="reduce"+n[0].toUpperCase()+n.slice(1);e.prototype[l]=function(){var e,t,n=Array.prototype.slice.call(arguments);if(n.length<2||n.length>4)throw new B("Graph.".concat(l,": invalid number of arguments (expecting 2, 3 or 4 and got ").concat(n.length,")."));if("function"==typeof n[n.length-1]&&"function"!=typeof n[n.length-2])throw new B("Graph.".concat(l,": missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array."));2===n.length?(e=n[0],t=n[1],n=[]):3===n.length?(e=n[1],t=n[2],n=[n[0]]):4===n.length&&(e=n[2],t=n[3],n=[n[0],n[1]]);var i=t;return n.push(function(t,n,o,s,r,a,l){i=e(i,t,n,o,s,r,a,l)}),this[s].apply(this,n),i}}(e,t),function(e,t){var n=t.name,i=t.type,o=t.direction,s="find"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[s]=function(e,t,n){if("mixed"!==i&&"mixed"!==this.type&&i!==this.type)return!1;if(1===arguments.length)return ae(!0,this,i,n=e);if(2===arguments.length){e=""+e,n=t;var r=this._nodes.get(e);if(void 0===r)throw new V("Graph.".concat(s,': could not find the "').concat(e,'" node in the graph.'));return le(!0,this.multi,"mixed"===i?this.type:i,o,r,n)}if(3===arguments.length){e=""+e,t=""+t;var a=this._nodes.get(e);if(!a)throw new V("Graph.".concat(s,': could not find the "').concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new V("Graph.".concat(s,': could not find the "').concat(t,'" target node in the graph.'));return ce(!0,i,this.multi,o,a,t,n)}throw new B("Graph.".concat(s,": too many arguments (expecting 1, 2 or 3 and got ").concat(arguments.length,")."))};var r="some"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[r]=function(){var e=Array.prototype.slice.call(arguments),t=e.pop();return e.push(function(e,n,i,o,s,r,a){return t(e,n,i,o,s,r,a)}),!!this[s].apply(this,e)};var a="every"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[a]=function(){var e=Array.prototype.slice.call(arguments),t=e.pop();return e.push(function(e,n,i,o,s,r,a){return!t(e,n,i,o,s,r,a)}),!this[s].apply(this,e)}}(e,t),function(e,t){var n=t.name,i=t.type,o=t.direction,s=n.slice(0,-1)+"Entries";e.prototype[s]=function(e,t){if("mixed"!==i&&"mixed"!==this.type&&i!==this.type)return _.empty();if(!arguments.length)return function(e,t){if(0===e.size)return _.empty();var n="mixed"!==t&&t!==e.type,i="undirected"===t,o=e._edges.values();return new _(function(){for(var e,t;;){if((e=o.next()).done)return e;if(t=e.value,!n||t.undirected===i)break}return{value:{edge:t.key,attributes:t.attributes,source:t.source.key,target:t.target.key,sourceAttributes:t.source.attributes,targetAttributes:t.target.attributes,undirected:t.undirected},done:!1}})}(this,i);if(1===arguments.length){e=""+e;var n=this._nodes.get(e);if(!n)throw new V("Graph.".concat(s,': could not find the "').concat(e,'" node in the graph.'));return function(e,t,n){var i=_.empty();return"undirected"!==e&&("out"!==t&&void 0!==n.in&&(i=J(i,ie(n.in))),"in"!==t&&void 0!==n.out&&(i=J(i,ie(n.out,t?void 0:n.key)))),"directed"!==e&&void 0!==n.undirected&&(i=J(i,ie(n.undirected))),i}(i,o,n)}if(2===arguments.length){e=""+e,t=""+t;var r=this._nodes.get(e);if(!r)throw new V("Graph.".concat(s,': could not find the "').concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new V("Graph.".concat(s,': could not find the "').concat(t,'" target node in the graph.'));return function(e,t,n,i){var o=_.empty();return"undirected"!==e&&(void 0!==n.in&&"out"!==t&&i in n.in&&(o=J(o,re(n.in,i))),void 0!==n.out&&"in"!==t&&i in n.out&&(t||n.key!==i)&&(o=J(o,re(n.out,i)))),"directed"!==e&&void 0!==n.undirected&&i in n.undirected&&(o=J(o,re(n.undirected,i))),o}(i,o,r,t)}throw new B("Graph.".concat(s,": too many arguments (expecting 0, 1 or 2 and got ").concat(arguments.length,")."))}}(e,t)})}(xe),function(e){ue.forEach(function(t){(function(e,t){var n=t.name,i=t.type,o=t.direction;e.prototype[n]=function(e){if("mixed"!==i&&"mixed"!==this.type&&i!==this.type)return[];e=""+e;var t=this._nodes.get(e);if(void 0===t)throw new V("Graph.".concat(n,': could not find the "').concat(e,'" node in the graph.'));return function(e,t,n){if("mixed"!==e){if("undirected"===e)return Object.keys(n.undirected);if("string"==typeof t)return Object.keys(n[t])}var i=[];return me(!1,e,t,n,function(e){i.push(e)}),i}("mixed"===i?this.type:i,o,t)}})(e,t),function(e,t){var n=t.name,i=t.type,o=t.direction,s="forEach"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[s]=function(e,t){if("mixed"===i||"mixed"===this.type||i===this.type){e=""+e;var n=this._nodes.get(e);if(void 0===n)throw new V("Graph.".concat(s,': could not find the "').concat(e,'" node in the graph.'));me(!1,"mixed"===i?this.type:i,o,n,t)}};var r="map"+n[0].toUpperCase()+n.slice(1);e.prototype[r]=function(e,t){var n=[];return this[s](e,function(e,i){n.push(t(e,i))}),n};var a="filter"+n[0].toUpperCase()+n.slice(1);e.prototype[a]=function(e,t){var n=[];return this[s](e,function(e,i){t(e,i)&&n.push(e)}),n};var l="reduce"+n[0].toUpperCase()+n.slice(1);e.prototype[l]=function(e,t,n){if(arguments.length<3)throw new B("Graph.".concat(l,": missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array."));var i=n;return this[s](e,function(e,n){i=t(i,e,n)}),i}}(e,t),function(e,t){var n=t.name,i=t.type,o=t.direction,s=n[0].toUpperCase()+n.slice(1,-1),r="find"+s;e.prototype[r]=function(e,t){if("mixed"===i||"mixed"===this.type||i===this.type){e=""+e;var n=this._nodes.get(e);if(void 0===n)throw new V("Graph.".concat(r,': could not find the "').concat(e,'" node in the graph.'));return me(!0,"mixed"===i?this.type:i,o,n,t)}};var a="some"+s;e.prototype[a]=function(e,t){return!!this[r](e,t)};var l="every"+s;e.prototype[l]=function(e,t){return!this[r](e,function(e,n){return!t(e,n)})}}(e,t),function(e,t){var n=t.name,i=t.type,o=t.direction,s=n.slice(0,-1)+"Entries";e.prototype[s]=function(e){if("mixed"!==i&&"mixed"!==this.type&&i!==this.type)return _.empty();e=""+e;var t=this._nodes.get(e);if(void 0===t)throw new V("Graph.".concat(s,': could not find the "').concat(e,'" node in the graph.'));return function(e,t,n){if("mixed"!==e){if("undirected"===e)return pe(null,n,n.undirected);if("string"==typeof t)return pe(null,n,n[t])}var i=_.empty(),o=new he;return"undirected"!==e&&("out"!==t&&(i=J(i,pe(o,n,n.in))),"in"!==t&&(i=J(i,pe(o,n,n.out)))),"directed"!==e&&(i=J(i,pe(o,n,n.undirected))),i}("mixed"===i?this.type:i,o,t)}}(e,t)})}(xe);var Pe=function(e){function n(t){var n=a({type:"directed"},t);if("multi"in n&&!1!==n.multi)throw new B("DirectedGraph.from: inconsistent indication that the graph should be multi in given options!");if("directed"!==n.type)throw new B('DirectedGraph.from: inconsistent "'+n.type+'" type in given options!');return e.call(this,n)||this}return t(n,e),n}(xe),Le=function(e){function n(t){var n=a({type:"undirected"},t);if("multi"in n&&!1!==n.multi)throw new B("UndirectedGraph.from: inconsistent indication that the graph should be multi in given options!");if("undirected"!==n.type)throw new B('UndirectedGraph.from: inconsistent "'+n.type+'" type in given options!');return e.call(this,n)||this}return t(n,e),n}(xe),Ie=function(e){function n(t){var n=a({multi:!0},t);if("multi"in n&&!0!==n.multi)throw new B("MultiGraph.from: inconsistent indication that the graph should be simple in given options!");return e.call(this,n)||this}return t(n,e),n}(xe),_e=function(e){function n(t){var n=a({type:"directed",multi:!0},t);if("multi"in n&&!0!==n.multi)throw new B("MultiDirectedGraph.from: inconsistent indication that the graph should be simple in given options!");if("directed"!==n.type)throw new B('MultiDirectedGraph.from: inconsistent "'+n.type+'" type in given options!');return e.call(this,n)||this}return t(n,e),n}(xe),Ne=function(e){function n(t){var n=a({type:"undirected",multi:!0},t);if("multi"in n&&!0!==n.multi)throw new B("MultiUndirectedGraph.from: inconsistent indication that the graph should be simple in given options!");if("undirected"!==n.type)throw new B('MultiUndirectedGraph.from: inconsistent "'+n.type+'" type in given options!');return e.call(this,n)||this}return t(n,e),n}(xe);function Re(e){e.from=function(t,n){var i=a({},t.options,n),o=new e(i);return o.import(t),o}}return Re(xe),Re(Pe),Re(Le),Re(Ie),Re(_e),Re(Ne),xe.Graph=xe,xe.DirectedGraph=Pe,xe.UndirectedGraph=Le,xe.MultiGraph=Ie,xe.MultiDirectedGraph=_e,xe.MultiUndirectedGraph=Ne,xe.InvalidArgumentsGraphError=B,xe.NotFoundGraphError=V,xe.UsageGraphError=U,xe}()},944(e,t){"use strict";t.Vb=void 0,t.Vb=function(e,t,n){var i=function(e,t,n){if(0===e.length||0===t.length)return 0;if(n&&!n.caseSensitive&&(e=e.toUpperCase(),t=t.toUpperCase()),e===t)return 1;for(var i=0,o=e.length,s=t.length,r=Math.floor(Math.max(o,s)/2)-1,a=new Array(o),l=new Array(s),c=0;c<o;c++)for(var u=Math.max(0,c-r);u<=Math.min(s,c+r+1);u++)if(!a[c]&&!l[u]&&e[c]===t[u]){++i,a[c]=l[u]=!0;break}if(0===i)return 0;var h=0,d=0;for(c=0;c<o;c++)if(a[c]){for(;!l[d];)d++;e.charAt(c)!==t.charAt(d++)&&h++}return(i/o+i/s+(i-(h/=2))/i)/3}(e,t,n),o=0;if(i>.7){for(var s=Math.min(e.length,t.length),r=0;e[r]===t[r]&&r<4&&r<s;)++o,r++;i+=.1*o*(1-i)}return i}},7106(e){"use strict";var t=e.exports=function(e,t,i){"function"==typeof t&&(i=t,t={}),n(t,"function"==typeof(i=t.cb||i)?i:i.pre||function(){},i.post||function(){},e,"",e)};function n(e,o,s,r,a,l,c,u,h,d){if(r&&"object"==typeof r&&!Array.isArray(r)){for(var m in o(r,a,l,c,u,h,d),r){var p=r[m];if(Array.isArray(p)){if(m in t.arrayKeywords)for(var g=0;g<p.length;g++)n(e,o,s,p[g],a+"/"+m+"/"+g,l,a,m,r,g)}else if(m in t.propsKeywords){if(p&&"object"==typeof p)for(var f in p)n(e,o,s,p[f],a+"/"+m+"/"+i(f),l,a,m,r,f)}else(m in t.keywords||e.allKeys&&!(m in t.skipKeywords))&&n(e,o,s,p,a+"/"+m,l,a,m,r)}s(r,a,l,c,u,h,d)}}function i(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},t.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0}},5072(e){"use strict";var t=[];function n(e){for(var n=-1,i=0;i<t.length;i++)if(t[i].identifier===e){n=i;break}return n}function i(e,i){for(var s={},r=[],a=0;a<e.length;a++){var l=e[a],c=i.base?l[0]+i.base:l[0],u=s[c]||0,h="".concat(c," ").concat(u);s[c]=u+1;var d=n(h),m={css:l[1],media:l[2],sourceMap:l[3],supports:l[4],layer:l[5]};if(-1!==d)t[d].references++,t[d].updater(m);else{var p=o(m,i);i.byIndex=a,t.splice(a,0,{identifier:h,updater:p,references:1})}r.push(h)}return r}function o(e,t){var n=t.domAPI(t);return n.update(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap&&t.supports===e.supports&&t.layer===e.layer)return;n.update(e=t)}else n.remove()}}e.exports=function(e,o){var s=i(e=e||[],o=o||{});return function(e){e=e||[];for(var r=0;r<s.length;r++){var a=n(s[r]);t[a].references--}for(var l=i(e,o),c=0;c<s.length;c++){var u=n(s[c]);0===t[u].references&&(t[u].updater(),t.splice(u,1))}s=l}}},7659(e){"use strict";var t={};e.exports=function(e,n){var i=function(e){if(void 0===t[e]){var n=document.querySelector(e);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(e){n=null}t[e]=n}return t[e]}(e);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(e){"use strict";e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}},5056(e,t,n){"use strict";e.exports=function(e){var t=n.nc;t&&e.setAttribute("nonce",t)}},7825(e){"use strict";e.exports=function(e){if("undefined"==typeof document)return{update:function(){},remove:function(){}};var t=e.insertStyleElement(e);return{update:function(n){!function(e,t,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))))," */")),t.styleTagTransform(i,e,t.options)}(t,e,n)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}},1113(e){"use strict";e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}},3328(e,t,n){"use strict";n.d(t,{PackageFunctions:()=>Wo,_package:()=>Uo});var i,o=n(4328),s=n(7389),r=n(6082),a=n(684),l=n(9039);!function(e){e.EUCLIDEAN="EUCLIDEAN",e.MANHATTAN="MANHATTAN"}(i||(i={}));var c=n(1858),u=n(5072),h=n.n(u),d=n(7825),m=n.n(d),p=n(7659),g=n.n(p),f=n(5056),y=n.n(f),b=n(540),w=n.n(b),v=n(1113),C=n.n(v),A=n(7939),T={};T.styleTagTransform=C(),T.setAttributes=y(),T.insert=g().bind(null,"head"),T.domAPI=m(),T.insertStyleElement=w(),h()(A.A,T),A.A&&A.A.locals&&A.A.locals;var E=function(e,t,n,i){return new(n||(n=Promise))(function(o,s){function r(e){try{l(i.next(e))}catch(e){s(e)}}function a(e){try{l(i.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};let S=null,M=null;function x(e,t){return e&&""!=e?e:t}n(2780);class P{constructor(){this.learningRate={uiName:"Learninig Rate",value:1,tooltip:"The initial learning rate for the embedding optimization"},this.nEpochs={uiName:"Epochs",value:0,tooltip:"The number of epochs to optimize embeddings via SGD. Computed automatically if set to 0"},this.nNeighbors={uiName:"Neighbors",value:15,tooltip:"The number of nearest neighbors to construct the fuzzy manifold"},this.spread={uiName:"Spread",value:1,tooltip:"The effective scale of embedded points, used with min distance to control \n the clumped/dispersed nature of the embedding"},this.minDist={uiName:"Min Distance",value:.1,tooltip:"The effective minimum distance between embedded points, \n used with spread to control the clumped/dispersed nature of the embedding"},this.randomSeed={uiName:"Random Seed",value:null,tooltip:"Random seed",type:"string"},this.useWebGPU={uiName:"Use WebGPU",value:!1,tooltip:"Use WebGPU for Distance and UMAP computations",type:"boolean",disableTooltip:"WebGPU is not available"},function(){return E(this,void 0,void 0,function*(){if(!navigator.gpu)return console.error("WebGPU is not supported in this browser"),null;if(!S&&(S=yield navigator.gpu.requestAdapter(),null==S))return null;let e=null;return"info"in S&&(e=S.info),e?x(e.description,x(e.vendor,"No GPU description available")):"No GPU description available"})}().then(e=>{e?(this.useWebGPU.tooltip+=` (${e})`,this.useWebGPU.value=!0):(this.useWebGPU.value=!1,this.useWebGPU.disable=!0)})}}class L{constructor(){this.epsilon={uiName:"Epsilon",value:10,tooltip:"Epsilon is learning rate"},this.perplexity={uiName:"Perplexity",value:30,tooltip:"Roughly how many neighbors each point influences"}}}Promise.resolve(),n(934),n(8903);const I="MCL";r.SEMTYPE.MOLECULE,r.SEMTYPE.MACROMOLECULE;class _{constructor(){this.epsilon={uiName:"Epsilon",value:.01,tooltip:"Minimum distance between cluster points",min:0,max:2,step:.005},this.minPts={uiName:"Minimum points",value:4,tooltip:"Minimum number of points in cluster",min:1,max:1e3,step:1}}}class N{get algorithmOptions(){const e=this.methodsParams[this.methodInput.value],t={};return Object.keys(e).forEach(n=>{null!=e[n].value&&(t[n]=e[n].value)}),t}get dbScanOptions(){return{dbScanEpsilon:this.dbScanParams.epsilon.value??.01,dbScanMinPts:this.dbScanParams.minPts.value??4}}constructor(e={}){this.editorSettings={},this.plotEmbeddingsInput=s.input.bool("Plot embeddings",{value:!0}),this.clusterEmbeddingsInput=s.input.bool("Cluster embeddings",{value:!0}),this.preprocessingFunctionInputRoot=null,this.methods=[l.c.UMAP,l.c.T_SNE],this.columnFunctionsMap={},this.supportedFunctions={},this.availableMetrics=[],this.methodSettingsDiv=s.inputs([]),this.dbScanSettingsDiv=s.inputs([]),this.preprocessingFuncSettingsDiv=s.inputs([]),this.preprocessingFunctionSettings={},this.methodsParams={[l.c.UMAP]:new P,[l.c.T_SNE]:new L},this.dbScanParams=new _,this.editorSettings=e,this.editorSettings.enableMCL&&this.methods.push(I);const t=r.Func.find({tags:[a.GP]}),n=r.Func.find({meta:{role:a.GP}});Array.from(new Set([...t,...n])).forEach(e=>{const t=e.options.get(a.n3)??"",n=e.friendlyName??e.name,i=e.options.get(a.C0)??"",o=e.options.get(a._X)??"",s=e.options.get(a.Gi)??"";this.editorSettings.semtype&&!t.includes(this.editorSettings.semtype)||this.editorSettings.type&&!i.includes(this.editorSettings.type)||this.editorSettings.units&&!o.includes(this.editorSettings.units)||(this.supportedFunctions[n]={func:e,semTypes:t?t.split(","):[],types:i?i.split(","):[],units:o?o.split(","):[],distanceFunctions:s?s.split(","):[]})}),this.tableInput=s.input.table("Table",{value:o.shell.tv.dataFrame,items:o.shell.tables,onValueChanged:()=>{this.onTableInputChanged()}}),this.onTableInputChanged(),this.regenerateColInput(),this.onColumnInputChanged();let i=!1,c=!1;this.methodInput=s.input.choice("Method",{value:l.c.UMAP,items:this.methods,onValueChanged:e=>{i&&this.createAlgorithmSettingsDiv(this.methodSettingsDiv,this.methodsParams[e])}}),this.methodSettingsIcon=s.icons.settings(()=>{i=!i,i?this.createAlgorithmSettingsDiv(this.methodSettingsDiv,this.methodsParams[this.methodInput.value]):s.empty(this.methodSettingsDiv)},"Modify methods parameters"),this.dbScanSettingsIcon=s.icons.settings(()=>{c=!c,c?this.createAlgorithmSettingsDiv(this.dbScanSettingsDiv,this.dbScanParams):s.empty(this.dbScanSettingsDiv)},"Modify clustering parameters"),this.clusterEmbeddingsInput.classList.add("ml-dim-reduction-settings-input"),this.clusterEmbeddingsInput.root.prepend(this.dbScanSettingsIcon),this.methodInput.root.classList.add("ml-dim-reduction-settings-input"),this.methodInput.root.prepend(this.methodSettingsIcon),this.methodSettingsDiv=s.inputs([]);const u=this.columnFunctionsMap[this.colInput.value.name];this.preprocessingFunctionInput=s.input.choice("Encoding function",{value:u[0],items:u,onValueChanged:()=>{this.onPreprocessingFunctionChanged()}});let h=!1;this.preprocessingFunctionInputRoot||(this.preprocessingFunctionInputRoot=this.preprocessingFunctionInput.root,h=!0),h||(s.empty(this.preprocessingFunctionInputRoot),Array.from(this.preprocessingFunctionInput.root.children).forEach(e=>this.preprocessingFunctionInputRoot.append(e))),this.preprocessingFunctionInputRoot.classList.add("ml-dim-reduction-settings-input");let d=!1;this.preprocessingFuncSettingsIcon=s.icons.settings(async()=>{d?s.empty(this.preprocessingFuncSettingsDiv):await this.createPreprocessingFuncParamsDiv(this.preprocessingFuncSettingsDiv,this.supportedFunctions[this.preprocessingFunctionInput.value].func),d=!d},"Modify encoding function parameters"),this.preprocessingFunctionInputRoot.prepend(this.preprocessingFuncSettingsIcon),this.similarityMetricInput=s.input.choice("Similarity",{value:"",items:[]}),this.similarityMetricInput.nullable=!1,this.similarityMetricInputRoot||(this.similarityMetricInputRoot=this.similarityMetricInput.root),this.onPreprocessingFunctionChanged()}getColInput(){const e=this.tableInput.value?.columns.toList().find(e=>!!this.columnFunctionsMap[e.name])??null,t=s.input.column("Column",{table:this.tableInput.value,value:e,nullable:!1,onValueChanged:()=>this.onColumnInputChanged(),filter:e=>!!this.columnFunctionsMap[e.name]});return this.colInputRoot||(this.colInputRoot=t.root),t}regenerateColInput(){let e=!1;this.colInputRoot&&(e=!0,s.empty(this.colInputRoot)),this.colInput=this.getColInput(),e&&Array.from(this.colInput.root.children).forEach(e=>this.colInputRoot.append(e)),this.onColumnInputChanged()}onTableInputChanged(){const e=this.tableInput.value;if(!e)return;const t=()=>{this.columnFunctionsMap={},e.columns.toList().forEach(e=>{Object.keys(this.supportedFunctions).forEach(t=>{const n=this.supportedFunctions[t].semTypes,i=this.supportedFunctions[t].types,o=this.supportedFunctions[t].units,s=!n.length||e.semType&&n.includes(e.semType),r=!i.length||i.includes(e.type),a=!o.length||e.meta.units&&o.includes(e.meta.units);s&&r&&a&&(this.columnFunctionsMap[e.name]||(this.columnFunctionsMap[e.name]=[]),this.columnFunctionsMap[e.name].push(t))})}),this.regenerateColInput()};t(),e.columns.toList().some(e=>!!e.getTag(r.Tags.SemanticDetectionDuration))||e.meta.detectSemanticTypes().then(()=>{t()})}onColumnInputChanged(){const e=this.colInput.value;if(!e)return;const t=this.columnFunctionsMap[e.name];this.preprocessingFunctionInput=s.input.choice("Preprocessing function",{value:t[0],items:t,onValueChanged:()=>{this.onPreprocessingFunctionChanged()}});let n=!1;this.preprocessingFunctionInputRoot||(this.preprocessingFunctionInputRoot=this.preprocessingFunctionInput.root,n=!0),n||(s.empty(this.preprocessingFunctionInputRoot),Array.from(this.preprocessingFunctionInput.root.children).forEach(e=>this.preprocessingFunctionInputRoot.append(e))),this.onPreprocessingFunctionChanged()}onPreprocessingFunctionChanged(){s.empty(this.preprocessingFuncSettingsDiv),this.preprocessingFunctionSettings={};const e=this.preprocessingFunctionInput.value,t=this.supportedFunctions[e].distanceFunctions;this.availableMetrics=[...t],this.similarityMetricInput=s.input.choice("Similarity",{value:this.availableMetrics[0],items:this.availableMetrics}),this.similarityMetricInput.nullable=!1,this.similarityMetricInputRoot||(this.similarityMetricInputRoot=this.similarityMetricInput.root),s.empty(this.similarityMetricInputRoot),Array.from(this.similarityMetricInput.root.children).forEach(e=>this.similarityMetricInputRoot.append(e)),this.preprocessingFuncSettingsIcon&&(this.supportedFunctions[e].func.inputs.length<3?this.preprocessingFuncSettingsIcon.style.display="none":this.preprocessingFuncSettingsIcon.style.display="flex")}createAlgorithmSettingsDiv(e,t){return s.empty(e),Object.keys(t).forEach(n=>{const i=t[n],o="string"===i.type?s.input.string(i.uiName,{value:i.value??"",onValueChanged:e=>{i.value=e}}):"boolean"===i.type?s.input.bool(i.uiName,{value:i.value??!1,onValueChanged:e=>{i.value=e}}):s.input.float(i.uiName,{value:i.value,onValueChanged:e=>{i.value=e}});e.append(o.root),i.disable?(o.enabled=!1,s.tooltip.bind(o.input??o.root,i.disableTooltip??"")):s.tooltip.bind(o.input??o.root,i.tooltip)}),e}async createPreprocessingFuncParamsDiv(e,t){if(s.empty(e),t.inputs.length<3)return s.div();const n=t.prepare(),i=await n.buildEditor(s.div());for(let o=2;o<t.inputs.length;o++){const s=t.inputs[o];(this.preprocessingFunctionSettings[s.name]||n.inputParams[t.inputs[o].name].value||s.defaultValue)&&(this.preprocessingFunctionSettings[s.name]=this.preprocessingFunctionSettings[s.name]??n.inputParams[s.name].value??s.defaultValue);const r=i.find(e=>e.property.name===s.name);r&&(null!==this.preprocessingFunctionSettings[s.name]&&void 0!==this.preprocessingFunctionSettings[s.name]&&(r.value=this.preprocessingFunctionSettings[s.name]),r.onChanged.subscribe(e=>{this.preprocessingFunctionSettings[s.name]=e}),e.append(r.root))}return e}getEditor(){return s.div([this.tableInput,this.colInputRoot,this.preprocessingFunctionInputRoot,this.preprocessingFuncSettingsDiv,this.methodInput,this.methodSettingsDiv,this.similarityMetricInputRoot,this.plotEmbeddingsInput,this.clusterEmbeddingsInput,this.dbScanSettingsDiv],{style:{minWidth:"420px"},classes:"ui-form dim-reduction-dialog-form"})}getParams(){return{table:this.tableInput.value,col:this.colInput.value,methodName:this.methodInput.value,preprocessingFunction:this.supportedFunctions[this.preprocessingFunctionInput.value].func,similarityMetric:this.similarityMetricInput.value,plotEmbeddings:this.plotEmbeddingsInput.value,clusterEmbeddings:this.clusterEmbeddingsInput.value,options:{...this.algorithmOptions,...this.dbScanOptions,preprocessingFuncArgs:this.preprocessingFunctionSettings??{}}}}getInput(){return{table:this.tableInput.value.name,col:this.colInput.value.name,methodName:this.methodInput.value,preprocessingFunction:this.preprocessingFunctionInput.value,similarityMetric:this.similarityMetricInput.value,plotEmbeddings:this.plotEmbeddingsInput.value,clusterEmbeddings:this.clusterEmbeddingsInput.value,options:{...this.algorithmOptions,...this.dbScanOptions,preprocessingFuncArgs:this.preprocessingFunctionSettings??{}}}}getStringInput(){return JSON.stringify(this.getInput())}async applyStringInput(e){try{const t=JSON.parse(e);await this.applyInput(t)}catch(e){o.shell.error("Error applying input from history"),console.error(e)}}async applyInput(e){try{const t=this.tableInput.value?.col(e.col);if(!t)throw new Error("Column not found");this.colInput.value=t,this.preprocessingFunctionInput.value=e.preprocessingFunction,this.similarityMetricInput.value=e.similarityMetric,this.plotEmbeddingsInput.value=e.plotEmbeddings,this.clusterEmbeddingsInput.value=e.clusterEmbeddings;const n=this.methodsParams[this.methodInput.value];Object.keys(n).forEach(t=>{null!=e.options[t]&&(this.methodsParams[e.methodName][t].value=e.options[t])}),this.methodInput.value=e.methodName,this.preprocessingFunctionSettings=e.options.preprocessingFuncArgs,await this.createPreprocessingFuncParamsDiv(this.preprocessingFuncSettingsDiv,this.supportedFunctions[this.preprocessingFunctionInput.value].func)}catch(e){o.shell.error("Error applying input from history"),console.error(e)}}}var R=n(9713),$=n(6295);const O=e=>null==e;function H(e,t,n,i){if(n>e[e.length-1])return;const o=e.findIndex(e=>n<e);e.pop(),e.splice(o,0,n),t.pop(),t.splice(o,0,i)}class D{constructor(e=!0,t=!0){const i=navigator.hardwareConcurrency;this._workerCount=e?Math.max(i-2,1):1,this._workers=new Array(this._workerCount).fill(null).map(()=>new Worker(new URL(n.p+n.u(793),n.b))),this._terminateOnComplete=t}async calc(e,t,n=!0,o){return await this.calcMulti([e],[t],n,[o??{}],[1],i.MANHATTAN)}async calcMulti(e,t,n=!0,o=[{}],s=[1],r=i.MANHATTAN){if(e.length<1)throw new Error("values must contain at least one array");if(t.length!==e.length||o.length!==e.length||s.length!==e.length)throw new Error("values, fnNames, weights and opts must have the same length");return new Promise(async(i,a)=>{try{const a=e[0].length,l=new Array(this._workerCount),c=a*(a-1)/2;this._workerCount=Math.min(this._workerCount,c);const u=c/this._workerCount,h=new Float32Array(c);let d=0,m=1,p=0,g=Number.MIN_VALUE;for(let n=0;n<this._workerCount;n++){const i=Math.floor(n*u),f=n===this._workerCount-1?c:Math.floor((n+1)*u),y=d,b=m;n!==this._workerCount-1&&(d=a-2-Math.floor(Math.sqrt(-8*f+4*a*(a-1)-7)/2-.5),m=f-a*d+Math.floor((d+1)*(d+2)/2)),this._workers[n].postMessage({values:e,fnNames:t,startRow:y,startCol:b,chunckSize:f-i,opts:o,weights:s,aggregationMethod:r}),l[n]=new Promise((e,t)=>{this._workers[n].onmessage=({data:{error:o,distanceMatrixData:s,min:r,max:a}})=>{this._terminateOnComplete&&setTimeout(()=>this._workers[n].terminate()),o?t(o):(h.set(s,i),r<p&&(p=r),a>g&&(g=a),e())}})}await Promise.all(l),n&&h.forEach((e,t)=>{h[t]=(e-p)/(g-p)}),i(h)}catch(e){a(e)}})}terminate(){this._workers.forEach(e=>e.terminate())}}class F{constructor(){this._workerCount=Math.max(navigator.hardwareConcurrency-2,1)}static pruneSparseMatrix(e,t=1e6){const n=200,i=new Uint32Array(n),o=e.distance.length,s=e.distance;for(let e=0;e<o;e++)i[Math.floor(s[e]*n)]++;let r=0,a=0;for(let e=0;e<n&&(r+=i[e],a=e,!(r>=t));e++);const l=new Uint32Array(r),c=new Uint32Array(r),u=new Float32Array(r),h=e.i,d=e.j;let m=0;const p=(a+1)/n;for(let e=0;e<o;e++)s[e]<p&&(l[m]=h[e],c[m]=d[e],u[m]=s[e],m++);return{i:l,j:c,distance:u}}async calcMultiColumn(e,t,o,s=[{}],r=[1],a=i.EUCLIDEAN){const l=e[0].length*(e[0].length-1)/2,c=Math.floor(l/this._workerCount),u=e[0].length>2e4?await this.getMinimalThreshold(e,t,s,r,a):0;o<u&&(console.log(`using threshold ${u}`),o=u),s.forEach((e,t)=>s[t].threshold=o);const h=new Array(this._workerCount),d=new Array(this._workerCount).fill(null).map(()=>new Worker(new URL(n.p+n.u(111),n.b)));for(let n=0;n<this._workerCount;n++)h[n]=new Promise((i,u)=>{const h=n*c,m=n===this._workerCount-1?l:(n+1)*c;m<=h&&i({i:new Int32Array(0),j:new Int32Array(0),distance:new Float32Array(0),idx:n}),d[n].postMessage({values:e,startIdx:h,endIdx:m,threshold:o,fnNames:t,opts:s,weights:r,aggregationMethod:a}),d[n].onmessage=({data:{error:e,i:t,j:o,distance:s}})=>{e?(d[n].terminate(),u(e)):(d[n].terminate(),i({i:t,j:o,distance:s,idx:n}))}});const m=await Promise.all(h),p=m.reduce((e,t)=>e+t.i.length,0),g=new Int32Array(p),f=new Int32Array(p),y=new Float32Array(p);let b=0;for(const e of m)g.set(e.i,b),f.set(e.j,b),y.set(e.distance,b),b+=e.i.length;return{i:g,j:f,distance:y}}async calc(e,t,n,i={}){return await this.calcMultiColumn([e],[t],n,[i],[1])}async getKNN(e,t,n=15,i={}){return await this.multiColumnKNN([e],[t],n,[i],[1])}async getThresholdKNN(e,t,n=.8,i={}){return await this.multiColumnThresholdKnn([e],[t],n,[i],[1])}async multiColumnThresholdKnn(e,t,o=.8,s,r,a=i.EUCLIDEAN){if(e.length!==t.length||e.length!==s.length||e.length!==r.length)throw new Error("values, distance functions, options and weights arrays should have the same length");if(e.some(t=>t.length!==e[0].length))throw new Error("all values arrays should have the same length");const l=e[0].length*(e[0].length-1)/2,c=Math.floor(l/this._workerCount),u=new Array(this._workerCount),h=new Array(this._workerCount).fill(null).map(()=>new Worker(new URL(n.p+n.u(603),n.b)));for(let n=0;n<this._workerCount;n++)u[n]=new Promise((i,u)=>{const d=n*c,m=n===this._workerCount-1?l:(n+1)*c;m<=d&&i({knnDistances:new Array(0),knnIndexes:new Array(0)}),h[n].postMessage({values:e,startIdx:d,endIdx:m,fnNames:t,opts:s,threshold:o,weights:r,aggregationMethod:a}),h[n].onmessage=({data:{error:e,knnDistances:t,knnIndexes:o}})=>{e?(h[n].terminate(),u(e)):(h[n].terminate(),i({knnDistances:t,knnIndexes:o}))}});const d=await Promise.all(u),m=new Int32Array(e[0].length);for(const t of d)for(let n=0;n<e[0].length;++n)m[n]+=t.knnIndexes[n]?.length??0;const p={knnDistances:new Array(e[0].length).fill(null).map((e,t)=>new Array(m[t])),knnIndexes:new Array(e[0].length).fill(null).map((e,t)=>new Array(m[t]))};for(const t of d)for(let n=0;n<e[0].length;++n)for(let e=0;e<(t.knnDistances[n]?.length??0);++e)p.knnDistances[n][m[n]-1]=t.knnDistances[n][e],p.knnIndexes[n][m[n]-1]=t.knnIndexes[n][e],m[n]-=1;return p}async multiColumnSingleValueKNN(e,t,o,s=15,r,a,l=i.EUCLIDEAN){if(e.length!==o.length||e.length!==r.length||e.length!==a.length)throw new Error("values, distance functions, options and weights arrays should have the same length");if(e.some(t=>t.length!==e[0].length))throw new Error("all values arrays should have the same length");const c=new Array(this._workerCount).fill(null).map(()=>new Worker(new URL(n.p+n.u(810),n.b))),u=new Array(this._workerCount),h=e[0].length,d=e.map(e=>e[t]),m=Math.ceil(h/this._workerCount);for(let t=0;t<this._workerCount;t++)u[t]=new Promise((n,i)=>{const u=t*m,p=t===this._workerCount-1?h:(t+1)*m;p<=u&&n({knnDistances:new Array(0),knnIndexes:new Array(0)}),c[t].postMessage({values:e.map(e=>e.slice(u,p)),target:d,fnNames:o,opts:r,nNeighbours:s,weights:a,aggregationMethod:l,startIdx:u}),c[t].onmessage=({data:{error:e,knnDistances:o,knnIndexes:s}})=>{e?(c[t].terminate(),i(e)):(c[t].terminate(),n({knnDistances:o,knnIndexes:s}))}});const p=await Promise.all(u),g={knnDistances:new Array(s).fill(99999),knnIndexes:new Array(s).fill(-1)};for(const e of p)for(let t=0;t<(e.knnDistances?.length??0);++t)H(g.knnDistances,g.knnIndexes,e.knnDistances[t],e.knnIndexes[t]);return g}async multiColumnKNN(e,t,o=15,s,r,a=i.EUCLIDEAN){if(e.length!==t.length||e.length!==s.length||e.length!==r.length)throw new Error("values, distance functions, options and weights arrays should have the same length");if(e.some(t=>t.length!==e[0].length))throw new Error("all values arrays should have the same length");const l=e[0].length*(e[0].length-1)/2,c=Math.floor(l/this._workerCount),u=new Array(this._workerCount),h=new Array(this._workerCount).fill(null).map(()=>new Worker(new URL(n.p+n.u(950),n.b)));for(let n=0;n<this._workerCount;n++)u[n]=new Promise((i,u)=>{const d=n*c,m=n===this._workerCount-1?l:(n+1)*c;m<=d&&i({knnDistances:new Array(0),knnIndexes:new Array(0)}),h[n].postMessage({values:e,startIdx:d,endIdx:m,fnNames:t,opts:s,nNeighbours:o,weights:r,aggregationMethod:a}),h[n].onmessage=({data:{error:e,knnDistances:t,knnIndexes:o}})=>{e?(h[n].terminate(),u(e)):(h[n].terminate(),i({knnDistances:t,knnIndexes:o}))}});const d=await Promise.all(u),m={knnDistances:new Array(e[0].length).fill(null).map(()=>new Array(o).fill(99999)),knnIndexes:new Array(e[0].length).fill(null).map(()=>new Array(o).fill(-1))};for(const t of d)for(let n=0;n<e[0].length;++n)for(let e=0;e<(t.knnDistances[n]?.length??0);++e)H(m.knnDistances[n],m.knnIndexes[n],t.knnDistances[n][e],t.knnIndexes[n][e]);return m}async getSampleDistances(e,t,o=[],s,r=i.EUCLIDEAN){const a=new Array(this._workerCount).fill(null).map(()=>new Worker(new URL(n.p+n.u(778),n.b)));try{const n=e[0].length*(e[0].length-1)/2,i=Math.floor(n/this._workerCount),l=1e6,c=Math.max(Math.min(n/1e3,l),Math.min(n,l)),u=Math.floor(c/this._workerCount),h=new Array(this._workerCount);for(let l=0;l<this._workerCount;l++)h[l]=new Promise((c,h)=>{const d=l*i,m=l===this._workerCount-1?n:(l+1)*i;a[l].postMessage({values:e,startIdx:d,endIdx:m,sampleLength:u,fnNames:t,opts:o,weights:s,aggregationMethod:r}),a[l].onmessage=({data:{error:e,distance:t}})=>{a[l].terminate(),e?h(e):c({distance:t})}});const d=await Promise.all(h),m=d.reduce((e,t)=>e+t.distance.length,0),p=new Float32Array(m);let g=0;for(const e of d)p.set(e.distance,g),g+=e.distance.length;return p.sort(),p}catch(e){return a?.forEach(e=>e?.terminate()),console.error(e),new Float32Array(1).fill(.5)}}async getMinimalThreshold(e,t,n=[],o,s=i.EUCLIDEAN){try{const i=e.length*(e.length-1)/2,r=await this.getSampleDistances(e,t,n,o,s);return 1-r[Math.floor(7e7/i*r.length)]}catch(e){return console.error(e),.5}}static calcSync(e,t,n,i){const o=[],s=[],r=[];let a=0,l=0,c=0;const u=e.length*(e.length-1)/2;for(;a<u;){const t=O(e[l])||O(e[c])?1:n(e[l],e[c]);1-t>=i&&(o.push(l),s.push(c),r.push(t)),a++,c++,c===e.length&&(l++,c=l+1)}return{i:new Int32Array(o),j:new Int32Array(s),distance:new Float32Array(r)}}}var k,G=n(8774);!function(e){e.none="none",e.bold="bold",e.dashed="dashed"}(k||(k={}));class B{get currentLineId(){return this._currentLineIdx}set currentLineId(e){e!==this._currentLineIdx&&(this._currentLineIdx=e,this.sp.render(this.ctx))}set linesToRender(e){this.updateLines(e),this.sp.render(this.ctx)}set linesVisibility(e){this.visibility=e,this.sp.render(this.ctx)}constructor(e,t,n,i,o=k.none){var s;this._currentLineIdx=-1,this.lineClicked=new c.Subject,this.lineHover=new c.Subject,this.mouseOverLineId=-1,this.arrowWidth=15,this.sp=e,this.xAxisCol=this.sp.dataFrame.columns.byName(t),this.yAxisCol=this.sp.dataFrame.columns.byName(n),this.canvas=this.sp.getInfo().canvas,this.ctx=this.canvas.getContext("2d"),this.currentLineStyle=o,this.updateLines(i),this.visibility=null!==(s=i.visibility)&&void 0!==s?s:new G.A(this.lines.from.length),i.visibility||this.visibility.setAll(!0,!1),i.arrowSize&&(this.arrowWidth=i.arrowSize),this.canvas.onmousedown=e=>{var t;(null===(t=this.lines)||void 0===t?void 0:t.skipMouseOverDetection)&&(this.mouseOverLineId=this.checkCoordsOnLine(e.offsetX,e.offsetY)),-1!==this.mouseOverLineId&&this.lineClicked.next({x:e.clientX,y:e.clientY,id:this.mouseOverLineId,event:e})},this.canvas.onmousemove=e=>{var t;this.mouseOverLineId=(null===(t=this.lines)||void 0===t?void 0:t.skipMouseOverDetection)?-1:this.checkCoordsOnLine(e.offsetX,e.offsetY),-1!==this.mouseOverLineId&&this.lineHover.next({x:e.clientX,y:e.clientY,id:this.mouseOverLineId,event:e})},e.onEvent("d4-before-draw-scene").subscribe(e=>{this.renderLines()})}updateLines(e){this.lines=e,this.multipleLinesCounts=new Uint8Array(this.lines.from.length),e.skipMultiLineCalculation?this.multipleLinesCounts.fill(0):this.createMultiLinesIndices()}renderLines(){var e,t,n,i,o,s,r,a,l,c,u,h,d,m,p,g,f;const y=this.lines.colors||this.lines.widths||this.lines.opacities||this.lines.drawArrowsArr;y||(this.ctx.lineWidth=null!==(e=this.lines.width)&&void 0!==e?e:1,this.ctx.strokeStyle=`rgba(${null!==(t=this.lines.color)&&void 0!==t?t:"0,128,0"},${null!==(n=this.lines.opacity)&&void 0!==n?n:1})`);const b=this.sp.dataFrame.filter,w=Math.pow(null!==(i=this.lines.shortLineThreshold)&&void 0!==i?i:5,2);for(let e=0;e<this.lines.from.length;e++)if(b.get(this.lines.from[e])&&b.get(this.lines.to[e])&&this.visibility.getBit(e)){let t=0;const n=this.sp.getMarkerSize(this.lines.from[e])/2,i=this.sp.getMarkerSize(this.lines.to[e])/2,b=this.sp.pointToScreen(this.lines.from[e]);let v=null==b?void 0:b.x,C=null==b?void 0:b.y;const A=this.sp.pointToScreen(this.lines.to[e]);let T=null==A?void 0:A.x,E=null==A?void 0:A.y;const S=Math.min(this.sp.viewBox.width,this.sp.viewBox.height);if(this.ctx.beginPath(),v&&C&&T&&E&&Math.hypot(T-v,E-C)/S>.01){if(y){const t=(null===(o=this.lines.colors)||void 0===o?void 0:o[e])?null===(s=this.lines.colors)||void 0===s?void 0:s[e]:null!==(r=this.lines.color)&&void 0!==r?r:"0,128,0",n=(null===(a=this.lines.opacities)||void 0===a?void 0:a[e])?null===(l=this.lines.opacities)||void 0===l?void 0:l[e]:null!==(c=this.lines.opacity)&&void 0!==c?c:1;this.ctx.strokeStyle=`rgba(${t},${n})`,this.ctx.lineWidth=(null===(u=this.lines.widths)||void 0===u?void 0:u[e])?null===(h=this.lines.widths)||void 0===h?void 0:h[e]:null!==(d=this.lines.width)&&void 0!==d?d:1}e===this._currentLineIdx&&this.toggleCurrentLineStyle(!0);const b=this.multipleLinesCounts[e];let A=null;if(b){t=this.getLineLength(v,C,T,E);const o=this.getPointOnDistance(v,C,T,E,i,t),s=this.getPointOnDistance(T,E,v,C,n,t);v=o.x,C=o.y,T=s.x,E=s.y,A=this.lines.from[e]>this.lines.to[e]?this.findControlPoint(b,v,C,T,E,e):this.findControlPoint(b,T,E,v,C,e),this.ctx.moveTo(v,C),this.ctx.quadraticCurveTo(A.x,A.y,T,E)}else(!this.lines.skipShortLines||Math.pow(T-v,2)+Math.pow(E-C,2)>w)&&(this.ctx.moveTo(v,C),this.ctx.lineTo(T,E));if((null!==(m=this.lines.drawArrows)&&void 0!==m?m:null===(p=this.lines.drawArrowsArr)||void 0===p?void 0:p.getBit(e))&&(t||(t=this.getLineLength(v,C,T,E)),t>this.arrowWidth)){const e=b?null:this.getPointOnDistance(v,C,T,E,i,t),n=b?A.x:v,o=b?A.y:C;this.canvasArrow(this.ctx,null!==(g=null==e?void 0:e.x)&&void 0!==g?g:v,null!==(f=null==e?void 0:e.y)&&void 0!==f?f:C,n,o)}this.ctx.stroke(),this.ctx.closePath(),e===this._currentLineIdx&&this.toggleCurrentLineStyle(!1)}}this.fillLeftBottomRect()}toggleCurrentLineStyle(e){switch(this.currentLineStyle){case k.bold:e?this.ctx.lineWidth+=2:this.ctx.lineWidth-=2;break;case k.dashed:e?this.ctx.setLineDash([5,5]):this.ctx.setLineDash([]);break;default:return}}fillLeftBottomRect(){const e=new Path2D;e.rect(this.sp.yAxisBox.minX,this.sp.yAxisBox.maxY,this.sp.yAxisBox.width,this.sp.xAxisBox.height),this.ctx.fillStyle="white",this.ctx.beginPath(),this.ctx.fill(e),this.ctx.closePath()}createMultiLinesIndices(){const e={};for(let t=0;t<this.lines.from.length;t++){let n=0,i=0;this.lines.from[t]<this.lines.to[t]?(n=this.lines.from[t],i=this.lines.to[t]):(n=this.lines.to[t],i=this.lines.from[t]),e[`${n}|${i}`]?(1===e[`${n}|${i}`].length&&(this.multipleLinesCounts[e[`${n}|${i}`][0]]=1,e[`${n}|${i}`].push(1)),this.multipleLinesCounts[t]=++e[`${n}|${i}`][1]):e[`${n}|${i}`]=[t]}}checkCoordsOnLine(e,t){let n=-1,i=null,o=null;const s=this.sp.dataFrame.filter;for(let r=0;r<this.lines.from.length;r++)if(s.get(this.lines.from[r])&&s.get(this.lines.to[r])&&this.visibility.getBit(r)){const s=this.sp.getMarkerSize(this.lines.from[r])/2,a=this.sp.getMarkerSize(this.lines.to[r])/2,l=this.sp.worldToScreen(this.xAxisCol.get(this.lines.from[r]),this.yAxisCol.get(this.lines.from[r])),c=this.sp.worldToScreen(this.xAxisCol.get(this.lines.to[r]),this.yAxisCol.get(this.lines.to[r]));if(this.multipleLinesCounts[r]){const n=this.getLineLength(l.x,l.y,c.x,c.y),i=this.getPointOnDistance(l.x,l.y,c.x,c.y,a,n),u=this.getPointOnDistance(c.x,c.y,null==l?void 0:l.x,null==l?void 0:l.y,s,n),h=this.lines.from[r]>this.lines.to[r]?this.findControlPoint(this.multipleLinesCounts[r],i.x,i.y,u.x,u.y,r):this.findControlPoint(this.multipleLinesCounts[r],u.x,u.y,i.x,i.y,r);o=this.calculateDistToCurveLine(r,e,t,i,u,h)}else o=this.calculateDistToStraightLine(e,t,l,c);(!i&&null!==o&&o<5||i&&null!==o&&o<i)&&(i=o,n=r)}return n}calculateDistToStraightLine(e,t,n,i){const o=Math.min(n.x,i.x),s=Math.max(n.x,i.x),r=Math.min(n.y,i.y),a=Math.max(n.y,i.y);return e>=o-2&&e<=s+2&&t>=r-2&&t<=a+2?this.distToStraightLineSegment(e,t,n,i):null}distToStraightLineSegment(e,t,n,i){const o=(e,t,n,i)=>Math.pow(e-n,2)+Math.pow(t-i,2),s=o(n.x,n.y,i.x,i.y);if(0==s)return o(e,t,n.x,n.y);let r=((e-n.x)*(i.x-n.x)+(t-n.y)*(i.y-n.y))/s;return r=Math.max(0,Math.min(1,r)),o(e,t,n.x+r*(i.x-n.x),n.y+r*(i.y-n.y))}calculateDistToCurveLine(e,t,n,i,o,s){const r=Math.min(i.x,o.x,s.x),a=Math.max(i.x,o.x,s.x),l=Math.min(i.y,o.y,s.y),c=Math.max(i.y,o.y,s.y);if(t>=r-2&&t<=a+2&&n>=l-2&&n<=c+2){const e=a-r,u=c-l;return this.calculateDistToCurveInRect(t,n,i,s,o,e,u)}return null}calculateDistToCurveInRect(e,t,n,i,o,s,r){const a=Math.floor((s+r)/3),l=1/a,c=new Uint32Array(a),u=new Uint32Array(a),h=new Uint32Array(a);let d=null;const m=new G.A(a);for(let s=0;s<c.length;s++){const r=s*l,a=Math.pow(1-r,2)*n.x+2*r*(1-r)*i.x+Math.pow(r,2)*o.x,m=Math.pow(1-r,2)*n.y+2*r*(1-r)*i.y+Math.pow(r,2)*o.y,p=Math.abs(e-a),g=Math.abs(t-m),f=p+g;(!d||d>f)&&(d=f),h[s]=Math.max(p,g),c[s]=a,u[s]=m}for(let e=0;e<c.length;e++)h[e]<d&&m.setBit(e,!0,!1);let p=null;for(let n=-1;-1!==(n=m.findNext(n));){const i=Math.hypot(c[n]-e,u[n]-t);(!p||p>i)&&(p=i)}return p}getLineLength(e,t,n,i){return Math.sqrt(Math.pow(n-e,2)+Math.pow(i-t,2))}getPointOnDistance(e,t,n,i,o,s){const a=n-o*((n-e)/s),l=i-o*((i-t)/s);return new r.Point(a,l)}findControlPoint(e,t,n,i,o,s){const a=t+(i-t)/2,l=n+(o-n)/2;let c=a-t,u=l-n;const h=Math.sqrt(c*c+u*u);c/=h,u/=h;const d=50*Math.ceil(e/2);return e%2==0?new r.Point(a+d/2*u,l-d/2*c):new r.Point(a-d/2*u,l+d/2*c)}canvasArrow(e,t,n,i,o){const s=Math.atan2(i-t,o-n)+Math.PI;e.moveTo(t-this.arrowWidth*Math.sin(s-Math.PI/10),n-this.arrowWidth*Math.cos(s-Math.PI/10)),e.lineTo(t,n),e.lineTo(t-this.arrowWidth*Math.sin(s+Math.PI/10),n-this.arrowWidth*Math.cos(s+Math.PI/10))}}const V="dimensionality-reducer-terminate-event";var U,q=n(3629);async function W(e,t,i,s,r,a,l){let c=await async function(e,t,i,s,r,a,l){if(!a.distanceFnArgs)throw new Error("options.distanceFnArgs must be defined");if(e.length!==t.length||e.length!==a.distanceFnArgs.length||e.length!==s.length)throw new Error("data, metrics and options and weights must have the same length");return new Promise(function(c,u){const h=new Worker(new URL(n.p+n.u(234),n.b));h.postMessage({columnsData:e,distanceMetrics:t,method:i,options:a,weights:s,aggregationMethod:r});const d=o.events.onCustomEvent(V).subscribe(()=>{try{h?.terminate()}finally{d.unsubscribe()}});h.onmessage=({data:{error:e,embedding:t,epochNum:n,epochsLength:i}})=>{O(n)||O(i)?(d.unsubscribe(),e?u(e):c(t),setTimeout(()=>h.terminate(),100)):l&&l(n,i,t)}})}(e,i,t,s,r,a,l);return c=c.map(e=>(0,q.S8)(e)),c}!function(e){e.EUCLIDEAN="EUCLIDEAN",e.MANHATTAN="MANHATTAN"}(U||(U={}));const Y={[U.EUCLIDEAN]:function(e){return`\n var sum = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n sum = sum + distances[i] * distances[i] * computeInfo.weights[i] * computeInfo.weights[i];\n }\n return sqrt(sum);\n `},[U.MANHATTAN]:function(e){return`\n var sum = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n sum = sum + abs(distances[i]) * computeInfo.weights[i];\n }\n return sum;\n `}};var j;!function(e){e.HAMMING="Hamming",e.EUCLIDEAN="Euclidean",e.VECTOR_COSINE="Vector Cosine",e.MANHATTAN="Manhattan",e.TANIMOTO="Tanimoto",e.LEVENSTEIN="Levenshtein",e.NEEDLEMAN_WUNSCH="Needlemann-Wunsch",e.MONOMER_CHEMICAL_DISTANCE="Monomer chemical distance",e.SOKAL="Sokal",e.COSINE="Cosine",e.ASYMMETRIC="Asymmetric",e.Difference="Difference",e.OneHot="One-Hot"}(j||(j={}));const K={[j.HAMMING]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n let maxLength: u32 = max(aLength, bLength);\n let minLength: u32 = min(aLength, bLength);\n let sizeDiff: u32 = maxLength - minLength;\n \n let maxIntDistance = ceil(maxDistance * f32(maxLength)) - f32(sizeDiff);\n\n var diff: f32 = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n diff = diff + f32(a[i] != b[i]);\n if (diff > maxIntDistance) {\n return 1.0;\n }\n }\n diff += f32(sizeDiff);\n return diff / ${e};\n `},[j.EUCLIDEAN]:function(e,t){return`\n var dist: f32 = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n dist = dist + f32(a[i] - b[i]) * f32(a[i] - b[i]);\n }\n return sqrt(dist);\n `},[j.MANHATTAN]:function(e,t){return`\n var dist: f32 = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n dist = dist + abs(f32(a[i] - b[i]));\n }\n return dist;\n `},[j.VECTOR_COSINE]:function(e,t){return`\n var dist: f32 = 0.0;\n var productSum: f32 = 0.0;\n var aSquareSum: f32 = 0.0;\n var bSquareSum: f32 = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n productSum = productSum + f32(a[i] * b[i]);\n aSquareSum = aSquareSum + f32(a[i] * a[i]);\n bSquareSum = bSquareSum + f32(b[i] * b[i]);\n }\n var sim = productSum / (sqrt(aSquareSum) * sqrt(bSquareSum));\n return (1.0 - sim) / 2.0;\n `},[j.TANIMOTO]:function(e,t){return`\n var onBitsa: u32 = 0u;\n var onBitsb: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n onBitsa = onBitsa + countOneBits(a[i]);\n onBitsb = onBitsb + countOneBits(b[i]);\n }\n\n if (onBitsa == 0u && onBitsb == 0u) {\n return 0.0;\n }\n\n let totalOnBits = onBitsa + onBitsb;\n var commonBits: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n commonBits = commonBits + countOneBits(a[i] & b[i]);\n }\n\n return 1.0 - f32(commonBits) / f32(totalOnBits - commonBits);\n `},[j.LEVENSTEIN]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n let maxLength: u32 = max(aLength, bLength);\n let minLength: u32 = min(aLength, bLength);\n\n let maxIntDistance = ceil(maxDistance * f32(maxLength));\n\n // we will store two arrays as matrix and swap the working indices per pass.\n // this way we can reduce memory usage per computation to just O(aLength)\n // the grid will have aLength + 1 columns and bLength + 1 rows\n // this will be guaranteed by iteration, but the array sizes must be known at compile time, so we will use a fixed size of maxArraySize\n var dynamicPassMat: array<array<f32, ${e+1}u>, 2>; // initialize to 0\n \n var prevIndex: u32 = 0;\n var curIndex: u32 = 1; // we will swap these indices per pass\n\n // initialize the first row\n for (var i = 0u; i <= aLength; i = i + 1u) {\n dynamicPassMat[prevIndex][i] = f32(i);\n }\n\n // iterate over the rows\n for (var i = 1u; i <= bLength; i = i + 1u) {\n dynamicPassMat[curIndex][0] = f32(i);\n var minEntry: f32 = f32(maxLength);\n let prevRow = &dynamicPassMat[prevIndex];\n let curRow = &dynamicPassMat[curIndex];\n let bMon = u32(b[i - 1]);\n for (var j = 1u; j <= aLength; j = j + 1u) {\n var cost: f32 = f32(a[j - 1] != bMon);\n var res: f32 = min(\n min(\n (*prevRow)[j] + 1.0, // deletion\n (*curRow)[j - 1] + 1.0, // insertion\n ),\n (*prevRow)[j - 1] + cost // substitution\n );\n (*curRow)[j] = res;\n if (res < minEntry) {\n minEntry = res;\n }\n }\n // swap the indices\n let temp: u32 = prevIndex;\n prevIndex = curIndex;\n curIndex = temp;\n if (minEntry > maxIntDistance) {\n return 1.0;\n }\n }\n\n return dynamicPassMat[prevIndex][aLength] / f32(maxLength);\n `},[j.NEEDLEMAN_WUNSCH]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n let maxLength: u32 = max(aLength, bLength);\n let minLength: u32 = min(aLength, bLength);\n \n let maxIntDistance = ceil(maxDistance * f32(maxLength));\n // we will store two arrays as matrix and swap the working indices per pass.\n // this way we can reduce memory usage per computation to just O(aLength)\n // the grid will have aLength + 1 columns and bLength + 1 rows\n // this will be guaranteed by iteration, but the array sizes must be known at compile time, so we will use a fixed size of maxArraySize\n var dynamicPassMat: array<array<f32, ${e+1}u>, 2>; // initialize to 0\n \n // we need to keep track of which operation led to the current cell\n // i.e. whether we came from the left, top or diagonal to assign gap open/gap extend penalty\n var verticalGaps: array<u32, ${e+1}u>;\n var horizontalGaps: array<u32, ${e+1}u>;\n\n let gapOpenPenalty: f32 = suppInfo.gapOpenPenalty${t};\n let gapExtensionPenalty: f32 = suppInfo.gapExtensionPenalty${t};\n var prevIndex: u32 = 0;\n var curIndex: u32 = 1; // we will swap these indices per pass\n // initialize the first row\n for (var i = 0u; i <= aLength; i = i + 1u) {\n dynamicPassMat[prevIndex][i] = gapExtensionPenalty + f32(i - 1) * gapExtensionPenalty; // accounting for the fact that left and right gaps are less costly\n dynamicPassMat[curIndex][i] = 0.0;\n }\n dynamicPassMat[0][0] = 0.0;\n\n let simMatrix = &suppInfo.similarityMatrix${t}; // using pointers make things faster\n // iterate over the rows\n for (var i = 1u; i <= bLength; i = i + 1u) {\n let prevRow = &dynamicPassMat[prevIndex];\n let curRow = &dynamicPassMat[curIndex];\n (*curRow)[0] = gapExtensionPenalty + f32(i - 1) * gapExtensionPenalty;\n var minEntry: f32 = f32(maxLength);\n let monB = u32(b[i - 1]);\n for (var j = 1u; j <= aLength; j = j + 1u) {\n let monA = u32(a[j - 1]);\n \n let cost: f32 = (*prevRow)[j - 1] + 1f - (*simMatrix)[monA][monB];\n var top = (*prevRow)[j]; // deletion\n if (verticalGaps[j] > 0 || i == 1 || i == bLength) {\n top = top + gapExtensionPenalty;\n } else {\n top = top + gapOpenPenalty;\n }\n var left = (*curRow)[j - 1]; // insertion\n if (horizontalGaps[j - 1] > 0 || j == 1 || j == aLength) {\n left = left + gapExtensionPenalty;\n } else {\n left = left + gapOpenPenalty;\n }\n var res: f32 = min(\n min(\n top, // deletion\n left, // insertion\n ),\n cost // substitution\n );\n (*curRow)[j] = res;\n if (res < minEntry) {\n minEntry = res;\n }\n // update the horizontal and vertical gaps\n if (res == cost) {\n verticalGaps[j] = 0;\n horizontalGaps[j] = 0;\n } else if (res == left) {\n verticalGaps[j] = 0;\n horizontalGaps[j] = 1;\n } else {\n verticalGaps[j] = 1;\n horizontalGaps[j] = 0;\n }\n }\n // swap the indices\n let temp: u32 = prevIndex;\n prevIndex = curIndex;\n curIndex = temp;\n if (minEntry > maxIntDistance) {\n return 1.0;\n }\n }\n return dynamicPassMat[prevIndex][aLength] / f32(minLength);\n\n `},[j.MONOMER_CHEMICAL_DISTANCE]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n let maxLength: u32 = max(aLength, bLength);\n let minLength: u32 = min(aLength, bLength);\n let sizeDiff: u32 = maxLength - minLength;\n \n let maxIntDistance = ceil(maxDistance * f32(maxLength)) - f32(sizeDiff);\n\n let simMatrix = &(suppInfo.similarityMatrix${t}); // using pointers make things faster\n var diff: f32 = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n diff = diff + 1.0 - (*simMatrix)[u32(a[i])][u32(b[i])];\n if (diff > maxIntDistance) {\n return 1.0;\n }\n }\n diff += f32(sizeDiff);\n return diff / ${e};\n `},[j.SOKAL]:function(e,t){return`\n var onBitsa: u32 = 0u;\n var onBitsb: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n onBitsa = onBitsa + countOneBits(a[i]);\n onBitsb = onBitsb + countOneBits(b[i]);\n }\n let total = onBitsa + onBitsb;\n if (total == 0u) {\n return 1.0;\n }\n var commonBits: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n commonBits = commonBits + countOneBits(a[i] & b[i]);\n }\n return 1.0 - f32(commonBits) / f32(total * 2 - commonBits * 3);\n `},[j.COSINE]:function(e,t){return`\n var onBitsa: u32 = 0u;\n var onBitsb: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n onBitsa = onBitsa + countOneBits(a[i]);\n onBitsb = onBitsb + countOneBits(b[i]);\n }\n let total = onBitsa * onBitsb; // p.s. here total is taken by multiplying\n if (total == 0u) {\n return 1.0;\n }\n var commonBits: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n commonBits = commonBits + countOneBits(a[i] & b[i]);\n }\n return 1.0 - f32(commonBits) / sqrt(f32(total));\n `},[j.ASYMMETRIC]:function(e,t){return`\n var onBitsa: u32 = 0u;\n var onBitsb: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n onBitsa = onBitsa + countOneBits(a[i]);\n onBitsb = onBitsb + countOneBits(b[i]);\n }\n let min = min(onBitsa, onBitsb);\n if (min == 0u) {\n return 1.0;\n }\n var commonBits: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n commonBits = commonBits + countOneBits(a[i] & b[i]);\n }\n return 1.0 - f32(commonBits) / f32(min);\n `},[j.Difference]:function(e,t){return`\n let range = suppInfo.range${t};\n return f32(abs(f32(a[0]) - f32(b[0])) / range);\n `},[j.OneHot]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n if (aLength != bLength) {\n return 1.0;\n }\n for (var i = 0u; i < aLength; i = i + 1u) {\n if(a[i] != b[i]) {\n return 1.0;\n }\n }\n return 0.0;\n `}},z={[j.HAMMING]:e=>Math.ceil(e/30),[j.EUCLIDEAN]:e=>Math.ceil(e/30),[j.MANHATTAN]:e=>Math.ceil(e/30),[j.TANIMOTO]:e=>Math.ceil(e/30),[j.SOKAL]:e=>Math.ceil(e/30),[j.COSINE]:e=>Math.ceil(e/30),[j.ASYMMETRIC]:e=>Math.ceil(e/30),[j.LEVENSTEIN]:e=>Math.ceil(e*e/60),[j.NEEDLEMAN_WUNSCH]:e=>Math.ceil(e*e/60),[j.MONOMER_CHEMICAL_DISTANCE]:e=>Math.ceil(e/25),[j.Difference]:e=>1,[j.OneHot]:e=>Math.ceil(e/40),[j.VECTOR_COSINE]:e=>Math.ceil(e/30)},Z={STRING:new Set([j.HAMMING,j.LEVENSTEIN,j.NEEDLEMAN_WUNSCH,j.MONOMER_CHEMICAL_DISTANCE,j.OneHot]),UINT32ARRAY:new Set([j.HAMMING,j.EUCLIDEAN,j.MANHATTAN,j.MONOMER_CHEMICAL_DISTANCE,j.LEVENSTEIN,j.NEEDLEMAN_WUNSCH,j.TANIMOTO,j.COSINE,j.VECTOR_COSINE,j.SOKAL,j.ASYMMETRIC,j.OneHot,j.Difference]),INT32ARRAY:new Set([j.EUCLIDEAN,j.MANHATTAN,j.OneHot,j.Difference,j.VECTOR_COSINE]),FLOAT32ARRAY:new Set([j.EUCLIDEAN,j.MANHATTAN,j.Difference,j.VECTOR_COSINE]),NUMBER:new Set([j.EUCLIDEAN,j.MANHATTAN,j.Difference]),BITARRAY:new Set([j.TANIMOTO,j.COSINE,j.SOKAL,j.ASYMMETRIC])};function X(e,t=.8,n,i,o,s){return function(e,t,n,i){return new(n||(n=Promise))(function(o,s){function r(e){try{l(i.next(e))}catch(e){s(e)}}function a(e){try{l(i.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})}(this,void 0,void 0,function*(){const r=yield function(){return E(this,void 0,void 0,function*(){if(!navigator.gpu)return console.error("WebGPU is not supported in this browser"),null;if(!S&&(S=yield navigator.gpu.requestAdapter({powerPreference:"high-performance"}),null==S))return null;let e=!1;if(M&&(M.lost.then(()=>{e=!0}),yield new Promise(e=>setTimeout(e,10))),!M||e){const e=1e9,t=S.limits,n=t.maxBufferSize,i=t.maxStorageBufferBindingSize;try{return M=yield S.requestDevice({requiredLimits:{maxBufferSize:Math.min(n,e),maxStorageBufferBindingSize:Math.min(i,e)}}),M}catch(e){return console.error("Failed to create device with required limits",e),M=yield S.requestDevice(),M}}return M})}();if(!r)return null;const a=Object.values(j);if(n.some(e=>!a.includes(e)))throw new Error("Invalid distance metrics provided: "+n.join(", "));if(!Object.values(U).includes(i))throw new Error("Invalid aggregation function provided: "+i);const l=1-t;if(s.length!==e.length||s.length!==n.length||s.length!==o.length)throw new Error("Options, weigths and distance functions must be provided for each column");if(e.some(t=>t.length!==e[0].length))throw new Error("All entry lists must be the same length");const c=e.length,u=e[0].length,h=e.map((e,t)=>function(e,t=j.HAMMING,n,i={gapOpenPenalty:1,gapExtensionPenalty:.6}){var o,s;let r=null;const a=e.some(e=>"string"==typeof e)?(r="STRING",e.map(e=>new Uint32Array(e.split("").map(e=>e.charCodeAt(0))))):e.some(e=>"number"==typeof e)?(r="NUMBER",e.map(e=>new Float32Array([e]))):"object"==typeof e[0]&&e.some(e=>"_data"in e&&"_length"in e)?(r="BITARRAY",e.map(e=>e._data)):e.some(e=>e instanceof Float32Array)?(r="FLOAT32ARRAY",e):e.some(e=>e instanceof Uint32Array)?(r="UINT32ARRAY",e):e.some(e=>e instanceof Int32Array)?(r="INT32ARRAY",e):void 0;if(!a||!r)throw new Error("Invalid entry type, could not determine entry type from input list");const l=a[0]instanceof Int32Array?"INT32ARRAY":a[0]instanceof Float32Array?"FLOAT32ARRAY":"UINT32ARRAY",c=new Uint32Array(a.map(e=>e.length));if(!Z[r]||!Z[r].has(t))throw new Error(`Distance metric '${t}' not supported for entry type '${r}'`);const u=c.reduce((e,t)=>Math.max(e,t),0),h=z[t](u),d="INT32ARRAY"===l?Int32Array:"FLOAT32ARRAY"===l?Float32Array:Uint32Array,m=new d(a.length*u);a.forEach((e,t)=>{m.set(e,t*u)});let p="",g=0,f="FLOAT32ARRAY",y=null;if(t===j.NEEDLEMAN_WUNSCH||t===j.MONOMER_CHEMICAL_DISTANCE){let e=i.scoringMatrix&&i.alphabetIndexes?Object.keys(i.alphabetIndexes).reduce((e,t)=>Math.max(e,t.charCodeAt(0)),0):-1;if(!i.alphabetIndexes||!i.scoringMatrix){for(let t=0;t<m.length;t++)m[t]>e&&(e=m[t]);i.scoringMatrix=new Array(e+1).fill(null).map(()=>new Array(e+1).fill(0)),i.alphabetIndexes={};for(let e=0;e<i.scoringMatrix.length;e++)i.scoringMatrix[e][e]=1,i.alphabetIndexes[String.fromCharCode(e)]=e}const t=(e+1)*(e+1),r=new Array(e+1).fill(null).map(()=>new Float32Array(e+1));for(let t=0;t<e+1;t++)r[t][t]=1;const a=i.alphabetIndexes;for(const e of Object.keys(a))for(const t of Object.keys(a))e!==t&&(r[e.charCodeAt(0)][t.charCodeAt(0)]=i.scoringMatrix[a[e]][a[t]]);g=2+t,f="FLOAT32ARRAY",y=new Float32Array(g),y[0]=null!==(o=i.gapOpenPenalty)&&void 0!==o?o:1,y[1]=null!==(s=i.gapExtensionPenalty)&&void 0!==s?s:.6;let l=2;for(let e=0;e<r.length;e++)y.set(r[e],l),l+=r[e].length;p=`\n gapOpenPenalty${n}: f32,\n gapExtensionPenalty${n}: f32,\n similarityMatrix${n}: array<array<f32, ${e+1}>, ${e+1}>`}else if(t===j.Difference){if(!i.range||"number"!=typeof i.range||i.range<=0){const e=m.reduce((e,t)=>Math.min(e,t),m[0]),t=m.reduce((e,t)=>Math.max(e,t),m[0]);i.range=t-e}i.range<=0&&(i.range=1),g=1,f="FLOAT32ARRAY",y=new Float32Array([i.range]),p=`\n range${n}: f32`}const b=m instanceof Int32Array?"i32":m instanceof Float32Array?"f32":"u32",w=`data${n}: array<array<${b}, ${u}>, ${a.length}>`;return{flatSourceArray:m,sourceArraySize:m.length,maxEntryLen:u,arraySizes:c,complexity:h,suppInfoBuffer:y,suppInfoSize:g,suppInfoType:f,suppInfoStructWgsl:p,entryType:r,dataTypeWGSL:b,dataStructWgsl:w,EncodedArrayConstructor:d}}(e,n[t],t,s[t]));if(0===c)throw new Error("No columns provided. Please provide at least one column of data.");1===c&&(i=U.MANHATTAN);let d=h.map(e=>e.suppInfoStructWgsl).filter(e=>!!e&&""!=e).join(",\n"),m=!1;d&&""!=d.trim()||(m=!0,d="\ndummy: f32\n");const p=h.map(e=>e.dataStructWgsl).filter(e=>!!e&&""!=e).join(",\n"),g=new Uint32Array(c*u);h.forEach((e,t)=>{g.set(e.arraySizes,t*u)});const f=1e4,y=100,b=h.reduce((e,t)=>e+t.complexity,0),w=Math.ceil(6e3/b),v=Math.ceil(Math.sqrt(Math.ceil(100))),C=10*v,A=u*(u-1)/2,T=Math.ceil(A/f),x=r.createShaderModule({label:"Sparse matrix compute shader",code:`\n // each thread will perform 100 iterations at one time, comparing 100 pairs of entries.\n // in total, each thread will perform at most ${T} comparisons.\n // first is the result struct, containing is, js, and distances. each array with length of 100,\n // and also integer for how many pairs were found to be below threshold.\n struct SparseResult {\n i: array<array<u32, 100>, 10000>,\n j: array<array<u32, 100>, 10000>,\n distances: array<array<f32, 100>, 10000>,\n found: array<u32, 10000>,\n done: array<u32, 10000>\n }\n // struct for the data\n struct ComputeInfo {\n // start at cols and rows, and end at cols and rows for each thread, these will be calculated on cpu and passed to gpu.\n startAtCols: array<u32, 10000>,\n startAtRows: array<u32, 10000>,\n endAtCols: array<u32, 10000>,\n endAtRows: array<u32, 10000>,\n\n // the ACTUALLY sizes of each entry\n entrySizes: array<array<u32, ${u}>, ${c}>,\n // the weights for each entry\n weights: array<f32, ${c}>,\n // the data for each entry\n ${p} // an example of the dataWgsl would be:\n //data0: array<array<u32,20>,100>,\n //data1: array<array<u32,20>,100>\n }\n\n // struct for the supplementary information\n struct SuppInfo {\n // struct containing all the supplementary info, like scoring matrix, alphabet indexes, range, etc.\n ${d}\n };\n\n @group(0) @binding(0) var<storage, read_write> computeInfo: ComputeInfo;\n @group(0) @binding(1) var<storage, read_write> suppInfo: SuppInfo;\n @group(0) @binding(2) var<storage, read_write> results: SparseResult;\n @compute @workgroup_size(10, 10) fn calcSparseMatrix(\n @builtin(global_invocation_id) id: vec3<u32>\n ) {\n ${m?"let otherDummy = suppInfo.dummy * 2;":""} // just to make sure that the suppInfo is not optimized out\n let threadCol = id.x;\n let threadRow = id.y;\n let linearIndex = threadRow * ${C} + threadCol;\n if (linearIndex >= 10000) {\n return; // if we are out of bounds, return\n } \n var startAtCol: u32 = computeInfo.startAtCols[linearIndex];\n var startAtRow: u32 = computeInfo.startAtRows[linearIndex];\n let endAtCol: u32 = min(computeInfo.endAtCols[linearIndex], ${u}u);\n let endAtRow: u32 = min(computeInfo.endAtRows[linearIndex], ${u}u);\n let is = &results.i[linearIndex];\n let js = &results.j[linearIndex];\n let distances = &results.distances[linearIndex];\n results.found[linearIndex] = 0; // initialize the found counter\n var found: u32 = 0;\n if (results.done[linearIndex] > 0) {\n return; // if we are done, return\n }\n for (var i = 0; i < ${w}; i++) {\n if (startAtCol >= endAtCol && startAtRow >= endAtRow) {\n results.done[linearIndex] = 1;\n break;\n }\n if (found >= 100) {\n break;\n }\n let dist = combinedDistance(startAtCol, startAtRow);\n if (dist <= ${l}) {\n (*is)[found] = startAtCol;\n (*js)[found] = startAtRow;\n (*distances)[found] = dist;\n found = found + 1;\n }\n startAtCol = startAtCol + 1;\n if (startAtCol >= ${u}u) {\n startAtRow += 1;\n startAtCol = startAtRow + 1;\n }\n }\n results.found[linearIndex] = found;\n // update the startAtCols and startAtRows\n computeInfo.startAtCols[linearIndex] = startAtCol;\n computeInfo.startAtRows[linearIndex] = startAtRow;\n\n }\n\n // this will generate the distance script for each distance metric and then combine them into one\n ${Q(n,h.map(e=>e.maxEntryLen),l,i)}\n\n\n `}),P=r.createComputePipeline({label:"sparse matrix compute pipeline",layout:"auto",compute:{module:x,entryPoint:"calcSparseMatrix"}}),L=new Uint32Array(f),I=new Uint32Array(f),_=new Uint32Array(f),N=new Uint32Array(f),R=Math.floor(A/f);let $=0,O=1;console.time("GPUthreadStarts");for(let e=0;e<f;e++){const t=9999===e?A-1:(e+1)*R,n=u-2-Math.floor(Math.sqrt(-8*t+4*u*(u-1)-7)/2-.5),i=t-u*n+Math.floor((n+1)*(n+2)/2);L[e]=O,I[e]=$,_[e]=i,N[e]=n,$=n,O=i}console.timeEnd("GPUthreadStarts");const H=4e4+u*c+c+h.reduce((e,t)=>e+t.sourceArraySize,0),D=h.reduce((e,t)=>e+t.suppInfoSize,0),F=1e6,k=H*Uint32Array.BYTES_PER_ELEMENT;let G=k;const B=15&k;0!==B&&(G+=16-B);const V=r.createBuffer({label:"compute info buffer",size:G,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST,mappedAtCreation:!0}),q=V.getMappedRange();let W=0;new Uint32Array(q,W,f).set(L),W+=f*Uint32Array.BYTES_PER_ELEMENT,new Uint32Array(q,W,f).set(I),W+=f*Uint32Array.BYTES_PER_ELEMENT,new Uint32Array(q,W,f).set(_),W+=f*Uint32Array.BYTES_PER_ELEMENT,new Uint32Array(q,W,f).set(N),W+=f*Uint32Array.BYTES_PER_ELEMENT,new Uint32Array(q,W,g.length).set(g),W+=g.length*Uint32Array.BYTES_PER_ELEMENT,new Float32Array(q,W,c).set(o),W+=c*Float32Array.BYTES_PER_ELEMENT;for(const e of h){const t=e.EncodedArrayConstructor,n=e.sourceArraySize;new t(q,W,n).set(e.flatSourceArray),W+=n*t.BYTES_PER_ELEMENT}V.unmap();const Y=D*Uint32Array.BYTES_PER_ELEMENT;let K=Y;const X=15&Y;0!==X&&(K+=16-X),K=Math.max(K,16);const J=r.createBuffer({label:"supp info buffer",size:K,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST,mappedAtCreation:!0}),ee=J.getMappedRange();let te=0;for(const e of h)e.suppInfoBuffer&&e.suppInfoBuffer.byteLength>0&&e.suppInfoSize>0&&(new("UINT32ARRAY"===e.suppInfoType?Uint32Array:Float32Array)(ee,te,e.suppInfoBuffer.length).set(e.suppInfoBuffer),te+=e.suppInfoBuffer.byteLength);0===te&&new Uint32Array(ee,0,4).set([1,1,1,1]),J.unmap();const ne=302e4*Uint32Array.BYTES_PER_ELEMENT;let ie=ne;const oe=15≠0!==oe&&(ie+=16-oe);const se=r.createBuffer({label:"results buffer",size:ie,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),re=r.createBindGroup({label:"bindGroup for sparse matrix buffer",layout:P.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:V}},{binding:1,resource:{buffer:J}},{binding:2,resource:{buffer:se}}]}),ae=r.createBuffer({label:"results out buffer",size:se.size,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),le=[],ce=[],ue=[];let he=!1;for(;!he;){const e=r.createCommandEncoder({label:"distance encoder"}),t=e.beginComputePass({label:"distance compute pass"});t.setPipeline(P),t.setBindGroup(0,re),t.dispatchWorkgroups(v,v),t.end(),e.copyBufferToBuffer(se,0,ae,0,ae.size);const n=e.finish();r.queue.submit([n]),yield r.queue.onSubmittedWorkDone(),yield ae.mapAsync(GPUMapMode.READ);const i=ae.getMappedRange();let o=0;const s=new Uint32Array(i,o,F);o+=F*Uint32Array.BYTES_PER_ELEMENT;const a=new Uint32Array(i,o,F);o+=F*Uint32Array.BYTES_PER_ELEMENT;const l=new Float32Array(i,o,F);o+=F*Float32Array.BYTES_PER_ELEMENT;const c=new Uint32Array(i,o,f);o+=f*Uint32Array.BYTES_PER_ELEMENT,he=new Uint32Array(i,o,f).every(e=>1===e);const u=c.reduce((e,t)=>e+t,0),h=new Uint32Array(u),d=new Uint32Array(u),m=new Float32Array(u);let p=0;for(let e=0;e<c.length;e++){const t=c[e];0!==t&&(h.set(s.subarray(e*y,e*y+t),p),d.set(a.subarray(e*y,e*y+t),p),m.set(l.subarray(e*y,e*y+t),p),p+=t)}le.push(h),ce.push(d),ue.push(m),ae.unmap()}const de=le.reduce((e,t)=>e+t.length,0),me=new Uint32Array(de),pe=new Uint32Array(de),ge=new Float32Array(de);let fe=0;for(let e=0;e<le.length;e++)me.set(le[e],fe),pe.set(ce[e],fe),ge.set(ue[e],fe),fe+=le[e].length;return V.destroy(),J.destroy(),se.destroy(),ae.destroy(),{i:me,j:pe,distance:ge}})}function Q(e,t,n,i){return e.map((e,i)=>`\n fn distanceScript${i}(aIndex: u32, bIndex: u32) -> f32 {\n let a = computeInfo.data${i}[aIndex];\n let b = computeInfo.data${i}[bIndex];\n let maxDistance: f32 = ${n};\n ${K[e](t[i],i)}\n }\n `).join("\n")+"\n"+`\n fn combinedDistance(aIndex: u32, bIndex: u32) -> f32 {\n var distances: array<f32, ${e.length}>;\n ${e.map((e,t)=>`distances[${t}] = distanceScript${t}(aIndex, bIndex);`).join("\n")}\n ${Y[i](e.length)}\n }\n \n `}var J=n(1991),ee=n.n(J);let te=0;const ne="cliffsDf",ie=new c.Subject,oe="SALI",se="line index",re=["From","To"],ae="filterCliffs";async function le(e,t,n,i,a,l,c,u,h,d,m,p,g,f,y,b){te++;const w=c/100;let v,C=!1;const A=o.shell.tv?.dataFrame===t?o.shell.tv:o.shell.getTableView(t.name);let T=null;if(h.useWebGPU)try{T=await X([i.entries],w,[u],U.MANHATTAN,[1],[i.options??{}])}catch(e){console.error(e)}T||(h.useWebGPU&&console.error("WebGPU sparse matrix calculation failed, falling back to CPU implementation"),T=await(new F).calc(i.entries,u,w,i.options));const E=await async function(e,t){const n=e.distance.map((n,i)=>{const o=Math.abs(t.get(e.i[i])-t.get(e.j[i]));return 0!=n?o/n:1/0}),i=e.distance.map(e=>1-e),o=e.i,s=e.j,a=r.BitSet.create(t.length);return e.distance.forEach((t,n)=>{a.set(e.i[n],!0),a.set(e.j[n],!0)}),{simVals:i,saliVals:n,n1:o,n2:s,cliffsBitSet:a}}(T,a),S=`sali_${l[0].substring(l[0].lastIndexOf("_"))}`;if(!t.columns.names().includes(S)){const i=function(e,t,n,i,o,s,a){const l=new Array(e).fill(0);for(let e=0;e!=i.length;++e)n[e]!=1/0&&(a.get(i[e])>a.get(o[e])?l[i[e]]+=n[e]:l[o[e]]+=n[e]);return r.Column.fromList("double",t,l)}(n.length,S,E.saliVals,E.n1,E.n2,0,a);t.columns.add(i),e.setOptions({size:i.name})}const M=function(e){const t=e.filter(e=>e!==1/0),n=t.reduce((e,t)=>Math.min(e,t),Number.MAX_VALUE);return{max:t.reduce((e,t)=>Math.max(e,t),n),min:n}}(E.saliVals),x=.8/(M.max-M.min),P=function(e,t,n,i,o,s,a,l){const c={from:new Uint32Array(t.n1.length),to:new Uint32Array(t.n1.length),opacities:new Float32Array(t.n1.length),colors:new Array(t.n1.length),widths:new Float32Array(t.n1.length)};for(let n=0;n<t.n1.length;n++)c.from[n]=t.n1[n],c.to[n]=t.n2[n],c.opacities[n]=t.saliVals[n]===1/0?1:.2+(t.saliVals[n]-a.min)*l,c.colors[n]=e.selection.get(c.from[n])&&e.selection.get(c.to[n])?"255,255,0":"0,128,0",c.widths[n]=1;const u=r.DataFrame.create(c.from.length);return re.forEach((e,t)=>{u.columns.addNewString(e).init(e=>n.get(0===t?c.from[e]:c.to[e])),function(e,t){Object.keys(t).forEach(n=>{e.tags[n]=t[n]})}(u.col(e),s),u.col(e).semType=o}),u.columns.addNewFloat("Δ activity").init(e=>Math.abs(i.get(c.from[e])-i.get(c.to[e]))),u.columns.addNewInt(se).init(e=>e),u.columns.addNewFloat(oe).init(e=>t.saliVals[e]),u.columns.addNewFloat("Similarity").init(e=>t.simVals[e]),u.name=`${ne}${te}`,{lines:c,linesDf:u}}(t,E,n,a,d,m,M,x);P.lines.skipMultiLineCalculation=!0,P.linesDf.col(oe).setTag("description","Structure−Activity Landscape Index (activity difference divided by 1 minus similarity)");const L=new B(e,l[0],l[1],P.lines,k.none);let I=null;const _=s.button(`${P.linesDf.rowCount} cliffs`,()=>{if(!I?.dataFrame){I=(()=>{const e=f?f(P.linesDf,re).sort([oe],[!1]):P.linesDf.plot.grid().sort([oe],[!1]);return e.col(se)&&(e.col(se).visible=!1),t.temp[".cliffsDfGrid"]=I,e})();const e=ee()(A.viewers).some(e=>e.dataFrame.name===`${ne}${te}`);b&&!e&&A.addViewer(I),A.dockManager.dock(I,"down",void 0,"Activity cliffs",y??.2)}});_.classList.add("scatter_plot_link","cliffs_grid");const N=s.input.toggle("Show only cliffs",{value:!1,onValueChanged:n=>{n?(e.dataFrame.setTag(ae,l[0]),t.filter.and(E.cliffsBitSet),ie.next(l[0])):(e.dataFrame.setTag(ae,""),t.filter.setAll(!0),ie.next(""))}});e.root.prepend(s.divH([_,N.root],"cliffs_div")),ie.subscribe(e=>{N.enabled=""===e||e===l[0]}),t.onRowsFiltering.subscribe(()=>{N.value&&t.filter.and(E.cliffsBitSet)});const $=o.events.onViewerClosed.subscribe(t=>{t.args.viewer===e&&(I&&A.dockManager.close(I.root),$.unsubscribe(),A.subs=A.subs.filter(e=>e!==$))});A.subs.push($),P.linesDf.onCurrentCellChanged.subscribe(()=>{for(let e=0;e<P.linesDf.rowCount;e++)P.lines.widths[e]=e===P.linesDf.currentRowIdx?3:1;L.linesToRender=P.lines;const i=P.linesDf.currentCol&&P.linesDf.currentCol.name===re[1]?P.lines.to:P.lines.from,r=-1!==P.linesDf.currentRowIdx?P.linesDf.currentRowIdx:null;if(e.dataFrame.currentRowIdx=r?i[r]:-1,null!==r){const i=P.linesDf.currentRowIdx;L.currentLineId=i;const{zoomLeft:c,zoomRight:u,zoomTop:h,zoomBottom:d}=function(e,t,n,i,o,s){const r=Math.abs(n-o),a=Math.abs(i-s),l=e/r,c=t/a,u=Math.min(l,c),h=e/u*5,d=t/u*5,m=(n<o?n:o)+r/2-h/2,p=(i>s?i:s)-a/2+d/2;return{zoomLeft:m,zoomRight:m+h,zoomTop:p,zoomBottom:p-d}}(e.viewport.width,e.viewport.height,e.dataFrame.get(l[0],P.lines.from[i]),e.dataFrame.get(l[1],P.lines.from[i]),e.dataFrame.get(l[0],P.lines.to[i]),e.dataFrame.get(l[1],P.lines.to[i]));e.zoom(c,h,u,d),N.value?t.filter.and(E.cliffsBitSet):!0===N.enabled&&t.filter.setAll(!0),setTimeout(()=>{!function(e,t,n,i,r,a,l,c,u){const h=t.getPane("Cliff Details");s.empty(h.root);const d=u({points:[n,i],lineId:r,df:e,seqCol:a,activityCol:l,sali:c});h.root.append(d),setTimeout(()=>{o.shell.o=t.root},500)}(t,v,P.lines.from[r],P.lines.to[r],r,n,a,P.linesDf.get(oe,r),g);const i=e.dataFrame.getSortedOrder(A.grid.sortByColumns,A.grid.sortTypes);A.grid.scrollToCell(n.name,i.indexOf(e.dataFrame.currentRowIdx))},1e3)}}),P.linesDf.onSelectionChanged.subscribe(e=>{setTimeout(()=>(()=>{const e=r.BitSet.create(t.rowCount);for(let t=0;t<P.linesDf.rowCount;t++){const n=P.linesDf.selection.get(t);n&&(e.set(P.lines.from[t],!0),e.set(P.lines.to[t],!0)),P.lines.colors[t]=n?"255,255,0":"0,128,0"}t.selection.copyFrom(e),L.linesToRender=P.lines})(),100)}),t.onSelectionChanged.subscribe(e=>{!1===t.selection.anyTrue&&"number"==typeof e&&(!C&&I?.dataFrame?(e=>{e.selection.setAll(!1);for(let e=0;e<P.lines.colors.length;e++)P.lines.colors[e]="0,128,0";L.linesToRender=P.lines})(I.dataFrame):C=!1)}),L.lineClicked.subscribe(e=>{if(C=!0,L.currentLineId=e.id,-1!==e.id){const n=P.linesDf.selection.clone();setTimeout(()=>{if(e.event.ctrlKey?(n.set(e.id,!n.get(e.id)),P.linesDf.selection.copyFrom(n)):(P.linesDf.currentRowIdx!==e.id&&(P.linesDf.currentRowIdx=e.id,t.currentRowIdx=P.lines.from[e.id]),P.linesDf.selection.copyFrom(n)),I?.dataFrame){const t=P.linesDf.getSortedOrder(I.sortByColumns,I.sortTypes);I.scrollToCell(re[0],t.indexOf(e.id))}},500)}}),L.lineHover.pipe((0,R.debounceTime)(500)).subscribe(e=>{-1!==e.id&&-1===t.mouseOverRowIdx&&s.tooltip.show(p({lineId:e.id,points:[P.lines.from[e.id],P.lines.to[e.id]],df:t,seqCol:n,activityCol:a}),e.x,e.y)}),e.addProperty("similarityLimit","double",w),v=function(){const e=s.accordion(),t=s.element("i");return t.className="grok-icon svg-icon svg-view-layout",e.addTitle(s.span([t,s.label("Activity cliffs")])),e.addPane("Cliff Details",()=>s.divText("Cliff has not been selected"),!0),o.shell.o=e.root,e}()}var ce=n(6863),ue=n(2003),he=n(3516),de=n(3151),me=n(4025),pe=n(439);function ge(e,t){const n=e=>o[e]??null,i=e=>{const t=a.columns.addNewString((e+1).toString());return o.push(t),t},o=[],s=e.length,a=r.DataFrame.create(s),l=t.getSeqHandler(e);for(let e=0;e<s;++e){const t=l.getSplitted(e);for(let o=0;o<t.length;++o){const s=t.getOriginal(o);(n(o)||i(o)).set(e,s,!1)}}const c=e.temp[me.j.notationProvider]??null,u=c?.monomerCanonicalizerFuncName;if(u)for(const e of o)e.setTag(pe.jz,u);return a}var fe,ye=n(4971);async function be(e){const t=(await(0,ye.pj)()).getMonomerLib(),n=[],i={},s=e.map(e=>t.getMonomer("PEPTIDE",e)?.smiles??""),a=r.Column.fromStrings("smiles",s);for(let t=0;t<s.length;++t){i[e[t]]=t;const r=s[t],l=""===r?new Array(s.length).fill(0):(await o.chem.getSimilarities(a,r)).getRawData();l[t]=1,n[t]=Array.from(l)}return{scoringMatrix:n,alphabetIndexes:i}}!function(e){e.IDENTITY="identity",e.SIMILARITY="similarity"}(fe||(fe={}));var we=n(9192);class ve{constructor(){this.maxIterations={uiName:"Max iterations",value:0,tooltip:"Maximum iterations for MCL process.Default is \n 0 which will construct the clusters with plain sparse matrix. Values greater than 0 will \n perform MCL with the given number of iterations and will result in trans-cluster activity cliff lines."},this.useWebGPU={uiName:"Use WebGPU",value:!1,tooltip:"Use WebGPU for MCL calculation. (Experimental)",type:"boolean"}}}class Ce extends N{constructor(e={}){super({...e,enableMCL:!0});const t=Array.from(this.tableInput.value.columns.numericalNoDateTime);this.activitiesInput=s.input.column("Activities",{table:this.tableInput.value,value:t.length?t[0]:null,filter:e=>t.includes(e)}),this.activitiesInputRoot=this.activitiesInput.root,this.similarityInput=s.input.int("Similarity cutoff",{value:80}),this.methodsParams[I]=new ve}onTableInputChanged(){if(super.onTableInputChanged(),this.activitiesInputRoot){s.empty(this.activitiesInputRoot);const e=Array.from(this.tableInput.value.columns.numerical);this.activitiesInput=s.input.column("Activities",{table:this.tableInput.value,value:e.length?e[0]:null,filter:t=>e.includes(t)}),Array.from(this.activitiesInput.root.children).forEach(e=>this.activitiesInputRoot.append(e))}}getEditor(){return s.div([this.tableInput,this.colInputRoot,this.preprocessingFunctionInputRoot,this.preprocessingFuncSettingsDiv,this.activitiesInputRoot,this.similarityMetricInputRoot,this.methodInput,this.methodSettingsDiv,this.similarityMetricInputRoot,this.similarityInput],{style:{minWidth:"320px"},classes:"ui-form dim-reduction-dialog-form"})}getParams(){return{...super.getParams(),activities:this.activitiesInput.value,similarityThreshold:this.similarityInput.value}}getInput(){return{...super.getInput(),activityCol:this.activitiesInput.value.name,simThreshold:this.similarityInput.value}}async applyInput(e){super.applyInput(e),this.activitiesInput.value=this.tableInput.value.col(e.activityCol),this.similarityInput.value=e.simThreshold}}var Ae,Te,Ee;function Se(e){const t=["Embed_X","Embed_Y"],n=e.columns.names().filter(e=>e.includes(t[0])).length+1;return t.map(e=>`${e}_${n}`)}function Me(e,t){return`${t} (${e.length>4?`${e.length} columns`:e.map(e=>e.name).join(", ")})`}async function xe(e,t,i,l,c,u,h,d=!0,m=!1,p={preprocessingFuncArgs:[]},g={},f=null,y={},b){const w={showXAxis:!1,showYAxis:!1,showXSelector:!1,showYSelector:!1};if(t.length!==l.length||t.length!==u.length||t.length!==c.length||t.length!==p.preprocessingFuncArgs.length)throw new Error("columns, metrics and preprocessing functions, weights and function argumentsmust have the same length");const v=d?g.tableView??o.shell.tableView(e.name)??o.shell.addTableView(e):null,C=async()=>{const C=r.TaskBarProgressIndicator.create(`Initializing ${g.scatterPlotName??"dimensionality reduction"} ...`);let A;try{const T=g.embedColsNames??Se(e);function E(n,o,l){let c=null,u=null;e.columns.names().includes(T[0])?(c=e.columns.byName(T[0]),u=e.columns.byName(T[1])):(c=e.columns.add(r.Column.float(T[0],e.rowCount)),u=e.columns.add(r.Column.float(T[1],e.rowCount)),d&&!A&&(A=v.scatterPlot({...w,x:T[0],y:T[1],title:g.scatterPlotName??Me(t,i)}))),g[a.YP]&&(A?.root&&s.setUpdateIndicator(A.root,!1),c.init(e=>l[0]?l[0][e]:void 0),u.init(e=>l[1]?l[1][e]:void 0));const h=n/o*100;C.update(h,`Running ${g.scatterPlotName??"dimensionality reduction"}... ${h.toFixed(0)}%`)}async function S(){e.columns.add(r.Column.float(T[0],e.rowCount)),e.columns.add(r.Column.float(T[1],e.rowCount));let n=null;d&&(A=v.scatterPlot({...w,x:T[0],y:T[1],title:g.scatterPlotName??Me(t,i)}),s.setUpdateIndicator(A.root,!0));const m=o.events.onViewerClosed.subscribe(e=>{const t=e.args.viewer;t?.getOptions()?.look?.title&&A?.getOptions()?.look?.title&&t?.getOptions()?.look?.title===A?.getOptions()?.look?.title&&(o.events.fireCustomEvent(V,{}),m.unsubscribe(),n?.(),C.close())}),f=new Promise(async(o,s)=>{try{n=o;const s=[];let r=l,d=c,m=h;if(b&&t.every(e=>e.isNumerical)){const n=t.map(e=>e.toList()),i=new Array(e.rowCount).fill(0).map((e,n)=>new Float32Array(t.length));for(let o=0;o<t.length;++o)for(let t=0;t<e.rowCount;++t)i[t][o]=n[o][t];p.distanceFnArgs=[{}],s.push({entries:i,options:{}}),r=[b],d=[1],m="MANHATTAN"}else for(let e=0;e<u.length;++e){const n=u[e];if(p.distanceFnArgs||(p.distanceFnArgs=[]),n){const i=n.inputs[0].name,o=n.inputs[1].name,{entries:r,options:a}=await n.apply({[i]:t[e],[o]:l[e],...p.preprocessingFuncArgs[e]??{}});s.push({entries:r,options:a}),p.distanceFnArgs.push(a)}else{const n=t[e].toList(),i={};s.push({entries:n,options:i}),p.distanceFnArgs.push(i)}}o(await W(s.map(e=>e.entries),i,r,d,h,p,g[a.vb]?void 0:E))}catch(e){s(e)}}),y=await f;return C.close(),m.unsubscribe(),y}const M=await S();if(m&&M){const x=r.TaskBarProgressIndicator.create("Clustering embeddings ...");try{const P=await function(e,t,i,o){return function(e,t,n,i){return new(n||(n=Promise))(function(o,s){function r(e){try{l(i.next(e))}catch(e){s(e)}}function a(e){try{l(i.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})}(this,void 0,void 0,function*(){return new Promise(function(s,r){const a=new Worker(new URL(n.p+n.u(682),n.b));a.postMessage({embedX:e,embedY:t,minPts:o,epsilon:i}),a.onmessage=({data:{error:e,clusters:t}})=>{a.terminate(),e?r(e):s(t)}})})}(M[0],M[1],p.dbScanEpsilon??.01,p.dbScanMinPts??4),L=g.clusterColName??e.columns.getUnusedName("Cluster (DBSCAN)");e.columns.addNewString(L).init(e=>P[e].toString()),A&&(A.props.colorColumnName=L)}catch(I){o.shell.error("Clustering embeddings failed"),console.error(I)}finally{x.close()}}if(M){const _=e.columns.byName(T[0]),N=e.columns.byName(T[1]);if(_.init(e=>M[0][e]),N.init(e=>M[1][e]),f)try{const R=f.inputs[0].name,$=f.inputs[1].name;await f.prepare({[R]:_,[$]:N,...y}).call(!0)}catch(O){o.shell.error("Post-processing failed"),console.error(O)}if(A)return s.setUpdateIndicator(A.root,!1),A.helpUrl="/help/compute/sequence-space",A}}catch(H){o.shell.error("Dimensionality reduction failed"),console.error(H),C.close(),A&&s.setUpdateIndicator(A.root,!1)}};return new Promise(async(t,n)=>{try{if(g.fastRowCount&&e.rowCount>g.fastRowCount&&!g[a.vb])s.dialog().add(s.divText("Analysis might take several minutes. Do you want to continue?")).onOK(async()=>{try{const e=await C();t(e)}catch(e){n(e)}}).onCancel(()=>t(void 0)).show();else{const e=await C();t(e)}}catch(e){n(e)}})}n(5540),function(e){e.ADD="ADD",e.SUB="SUB",e.MULT="MULT"}(Ae||(Ae={})),function(e){e.SQUARE="SQUARE",e.INVERSE="INVERSE",e.TRANSPOSE="TRANSPOSE",e.NORM="NORM",e.COLUMN_NORM="COLUMN_NORM"}(Te||(Te={})),function(e){e.SCALARMULT="SCALARMULT",e.SCALARADD="SCALARADD",e.SCALARPOW="SCALARPOW"}(Ee||(Ee={})),Object.prototype.toString;var Pe=n(6873),Le=n(4356),Ie=n(6717);function _e(e){var t;if((null===(t=o.shell.tv)||void 0===t?void 0:t.dataFrame)===e)return;const n=o.shell.tableView(e.name);n?o.shell.v=n:o.shell.addTableView(e)}var Ne=n(4870),Re=n(3856),$e=n(819),Oe=n(7278),He=n(5553),De=n(6642),Fe=n(3599),ke=n(673),Ge=n(8312);class Be extends De.sD{monomerLib=null;seqHelper=null;constructor(e,t){super(e,t,Uo.logger),(0,ye.pj)().then(e=>{this.monomerLib=e.getMonomerLib(),this.dirty=!0,this.gridCol?.grid?.invalidate(),this.subs.push(this.monomerLib.onChanged.subscribe(()=>{this.dirty=!0,this.gridCol?.grid?.invalidate()}))}),(0,Ge.Q)().then(e=>{this.seqHelper=e,this.dirty=!0,this.gridCol?.grid?.invalidate()})}}var Ve=n(4139);const Ue=ue.zS;function qe(e){const t=!ee().enumerate(e).some(([t,n])=>t.length>1&&0!=n&&n!=e.length-1),n=[],i=t?"":" ";for(const[t,o]of ee().enumerate(e)){let s=t;o<e.length&&(s+=`${t?"":"-"}${i}`),n.push(s)}return[n,t]}class We extends r.GridCellRenderer{seqHelper;get name(){return"sequence"}get cellType(){return"sequence"}get defaultHeight(){return 30}get defaultWidth(){return 230}hasMouseOver=!1;constructor(){super(),this.seqHelper=Uo.seqHelper}getRendererBack(e){const[t,n,i]=(0,De.BG)(e);if(i.rendererBack)return i.rendererBack;let o=null;return this.seqHelper&&(o=this.seqHelper.getSeqHandler(n).getRendererBack(t,n)),o}onClick(e,t){e.cell.column.temp["current-word"]=e.cell.value,e.grid.invalidate();const n=this.getRendererBack(e);n?.onClick(e,t)}onMouseEnter(e,t){const n=this.getRendererBack(e);n?.onMouseEnter(e,t),this.hasMouseOver=!0}onMouseMove(e,t){const n=this.getRendererBack(e);n?.onMouseMove(e,t)}onMouseLeave(e,t){if((0,He.WN)(e,null),e?.grid){const t=e.grid.onEvent("d4-grid-show-tooltip").subscribe(e=>{t.unsubscribe(),this.hasMouseOver&&e.preventDefault()})}this.hasMouseOver=!1}onDoubleClick(e,t){const n=this.getRendererBack(e);n?.onDoubleClick(e,t)}onKeyDown(e,t){const n=this.getRendererBack(e);n?.onKeyDown(e,t)}onKeyPress(e,t){const n=this.getRendererBack(e);n?.onKeyPress(e,t)}renderInt(e,t,n,i,o,s,r){const[a,l,c]=(0,De.BG)(s);if(!l)return;const u=l.temp,h=this.seqHelper.getSeqHandler(l);let d=(Uo.properties?Uo.properties.maxMonomerLength:4)??50;if(Re.gp.maxMonomerLength in l.tags){const e=parseInt(l.getTag(Re.gp.maxMonomerLength));d=!isNaN(e)&&e?e:50}if(".mm.cellRenderer.maxMonomerLength"in u){const e=u[".mm.cellRenderer.maxMonomerLength"];d=!isNaN(e)&&e?e:50}let m=c.rendererBack;m||(m=c.rendererBack=new $e.Jy(a,l,Uo.logger,d,()=>{const{font:e,fontWidth:t}=$e.Jy.getFontSettings(l);return{font:e,fontCharWidth:t,separatorWidth:h.isMsa()?8:0,monomerToShort:Ue}}),l.temp[".mm.cellRenderer.settingsChanged"],ke.s.true,m.init().then(()=>{})),m.render(e,t,n,i,o,s,r)}render(e,t,n,i,o,s,r){const a=this.getRendererBack(s);a?a?.render(e,t,n,i,o,s,r):this.renderInt(e,t,n,i,o,s,r)}}class Ye extends Be{constructor(e,t){super(e,t)}render(e,t,n,i,o,s,r){const a=window.devicePixelRatio,l=s.grid,c=s.cell.value??"",u=this.tableCol.tags[ue.gp.separator];let h=this.tableCol.meta.units;i=(0,$e.U0)(l,e,t,i,a);const[d,m]=c.split("#");h!==ue.Hi.CUSTOM||this.tableCol.temp[me.j.notationProvider]||(h=ue.Hi.SEPARATOR);const p=this.tableCol.temp[me.j.notationProvider]?.separatorSplitter??this.tableCol.temp[me.j.notationProvider]?.splitter??(0,Oe.Iv)(h,u),g=p(d),f=p(m),y=ee().count(0).take(g.length).map(e=>g.getOriginal(e)).toArray(),b=ee().count(0).take(f.length).map(e=>f.getOriginal(e)).toArray(),w=this.tableCol.getTag(ue.gp.alphabet);Ke(e,t,n,i,o,y,b,w===ue.YI.RNA||w===ue.YI.DNA?Fe.o.NUCLEOTIDE:Fe.o.AA,this.monomerLib,void 0,void 0)}async awaitRendered(e=1e4,t=`${e} timeout`){return Promise.resolve()}static getOrCreate(e){const[t,n,i]=(0,De.BG)(e);let o=i.rendererBack;return o||(o=i.rendererBack=new Ye(t,n)),o}}class je extends r.GridCellRenderer{get name(){return"MacromoleculeDifferenceCR"}get cellType(){return Ve.uF.MACROMOLECULE_DIFFERENCE}get defaultHeight(){return 30}get defaultWidth(){return 230}render(e,t,n,i,o,s,r){Ye.getOrCreate(s).render(e,t,n,i,o,s,r)}}function Ke(e,t,n,i,o,s,r,a,l,c,u){if(s.length!==r.length){const e=function(e,t){let n=0,i=0;const o=e.length>t.length?e:t,s=e.length>t.length?t:e;for(let e=0;e<s.length;e++)o[e]===s[e]&&n++;const r=o.length-s.length;for(let e=o.length-1;e>r;e--)o[e]===s[e-r]&&i++;const a=new Array(Math.abs(e.length-t.length)).fill(pe.b9[ue.Hi.FASTA]);function l(e){return n>i?e.concat(a):a.concat(e)}return e.length>t.length?t=l(ee()(t).toArray()):e=l(ee()(e).toArray()),{subParts1:e,subParts2:t}}(s,r);s=e.subParts1,r=e.subParts2}const h=e.measureText(qe(s).join("")),d=e.measureText(qe(r).join("")),m=Math.max(h.width,d.width);c&&(i=m+4*s.length,e.canvas.width=m+4*s.length);let p=Math.max(t,t+(i-(m+4*s.length))/2)+5;const g=Math.max(n,n+(o-28)/2);e.save();try{e.beginPath(),e.rect(t,n,c?m+4*s.length:i,o),e.clip(),e.font="12px monospace",e.textBaseline="top";const h=7;for(let t=0;t<s.length;t++){const n=s[t],c=r[t];let d=$e.S$;if(l&&(d=l.getMonomerTextColor(a,n)),n!=c){let s=$e.S$;l&&(s=l.getMonomerTextColor(a,c));const r=(0,Re.oZ)(e,n,p,g-h,i,o,{color:d,pivot:0,left:!0}),m=(0,Re.oZ)(e,c,p,g+h,i,o,{color:s,pivot:0,left:!0});p=Math.max(m,r),u&&(u[t]=ze(n,c,d,s,g,h,o))}else p=(0,Re.oZ)(e,n,p,g,i,o,{color:d,pivot:0,left:!0,transparencyRate:.5});p+=4}}finally{e.restore()}}function ze(e,t,n,i,o,s,r){const a=document.createElement("canvas"),l=a.getContext("2d");l.font="12px monospace";const c=l.measureText(qe([e]).join("")).width,u=l.measureText(qe([t]).join("")).width,h=Math.max(c,u);return a.height=r,a.width=h+4,l.font="12px monospace",l.textBaseline="top",(0,Re.oZ)(l,e,0,o-s,h,r,{color:n,pivot:0,left:!0}),(0,Re.oZ)(l,t,0,o+s,h,r,{color:i,pivot:0,left:!0}),a}var Ze,Xe=n(8070),Qe=n(4326);!function(e){e.Unknown="unknown",e.FR="framework",e.CDR="cdr"}(Ze||(Ze={}));const Je=new class{constructor(){this.regionTypes=[Ze.CDR],this.chains=["Heavy","Light"],this.skipEmptyPositions=!1,this.fitWidth=!1,this.positionWidth=16,this.positionHeight=Qe.fH.Entropy,this.filterSource=Qe.Fo.filterSource}};var et=n(7602),tt=n(250);const nt=Ze;var it,ot;!function(e){e.STYLE="Style",e.BEHAVIOR="Behavior",e.LAYOUT="Layout",e.DATA="Data"}(it||(it={})),function(e){e.skipEmptyPositions="skipEmptyPositions",e.regionTypes="regionTypes",e.chains="chains",e.fitWidth="fitWidth",e.positionWidth="positionWidth",e.positionHeight="positionHeight",e.filterSource="filterSource"}(ot||(ot={}));const st=Je;class rt extends r.JsViewer{viewed=!1;regionsFg=null;regionsRoot=null;isOpened=!1;panelNode=null;regions=[];regionTypes;chains;skipEmptyPositions;fitWidth;positionWidth;positionHeight;filterSource;constructor(){super(),this.skipEmptyPositions=this.bool(ot.skipEmptyPositions,st.skipEmptyPositions,{category:it.DATA}),this.regionTypes=this.stringList(ot.regionTypes,st.regionTypes,{category:it.DATA,choices:Object.values(nt).filter(e=>e!=nt.Unknown)}),this.chains=this.stringList(ot.chains,st.chains,{category:it.DATA,choices:["Heavy","Light"]}),this.fitWidth=this.bool(ot.fitWidth,st.fitWidth,{category:it.LAYOUT}),this.positionWidth=this.float(ot.positionWidth,st.positionWidth,{category:it.LAYOUT,editor:"slider",min:0,max:64,description:"Internal WebLogo viewers property width of position."}),this.positionHeight=this.string(ot.positionHeight,st.positionHeight,{category:it.LAYOUT,choices:Object.keys(Qe.fH)}),this.filterSource=this.string(ot.filterSource,st.filterSource,{category:it.BEHAVIOR,choices:Object.values(Qe.lT)}),this.viewSyncer=new et.g(Uo.logger)}static viewerCounter=-1;viewerId=++rt.viewerCounter;viewerToLog(){return`VdRegionsViewer<${this.viewerId}>`}async init(){this.subs.push((0,c.fromEvent)(this.root,"mousemove").subscribe(this.rootOnMouseMove.bind(this)))}detach(){const e=`${this.viewerToLog()}.detach()`,t=super.detach.bind(this);this.viewSyncer.sync(`${e}`,async()=>{this.setDataInProgress||(this.viewed&&(await this.destroyView("detach"),this.viewed=!1),t())})}onTableAttached(){super.onTableAttached(),this.setData(this.regions)}onPropertyChanged(e){if(super.onPropertyChanged(e),e){switch(e.name){case ot.regionTypes:case ot.chains:this.setData(this.regions)}switch(e.name){case ot.skipEmptyPositions:for(let e=0;e<this.logos.length;++e)for(const t of this.chains)this.logos[e][t].setOptions({[tt.n5.skipEmptyPositions]:this.skipEmptyPositions});this.calcSize();break;case ot.fitWidth:case ot.positionWidth:this.calcSize();break;case ot.positionHeight:for(let e=0;e<this.logos.length;++e)for(const t of this.chains)this.logos[e][t].setOptions({[tt.n5.positionHeight]:this.positionHeight});this.calcSize();break;case ot.filterSource:this.filterSourceInput.value=this.filterSource;break;default:this.setData(this.regions)}}else console.warn("Bio: VdRegionsViewer.onPropertyChanged() property is null")}setData(e){const t=`${this.viewerToLog()}.setData()`;Uo.logger.debug(`${t}, in, regions.length = ${e.length}`),this.viewSyncer.sync(`${t}`,async()=>{if(!this.setDataInProgress){this.setDataInProgress=!0;try{this.viewed&&(await this.destroyView("setData"),this.viewed=!1),this.regions=e,this.viewed||(await this.buildView("setData"),this.viewed=!0)}finally{this.setDataInProgress=!1}}})}viewSyncer;setDataInProgress=!1;host=null;filterSourceInput;mainLayout=null;logos=[];viewSubs=[];async destroyView(e){Uo.logger.debug(`Bio: VdRegionsViewer.destroyView( mainLayout = ${this.mainLayout?"value":"none"} ), purpose = '${e}', this.regions.length = ${this.regions.length}`),this.filterSourceInput&&s.empty(this.filterSourceInput.root),null!=this.mainLayout&&(this.mainLayout.remove(),this.host.remove(),this.host=null,this.mainLayout=null);for(const e of this.viewSubs)e.unsubscribe()}async buildView(e){Uo.logger.debug(`Bio: VdRegionsViewer.buildView() begin, purpose = '${e}', this.regions.length = ${this.regions.length}`);const t=this.regions.filter(e=>this.regionTypes.includes(e.type)),n=Array.from(new Set(t.map(e=>e.order))).sort(),i=[];for(let e=0;e<n.length;e++)for(const o of this.chains){const s=t.find(t=>t.order==n[e]&&t.chain==o);s&&i.push((async()=>{const t=await this.dataFrame.plot.fromType("WebLogo",{sequenceColumnName:s.sequenceColumnName,startPositionName:s.positionStartName,endPositionName:s.positionEndName,fixWidth:!0,skipEmptyPositions:this.skipEmptyPositions,positionWidth:this.positionWidth,positionHeight:this.positionHeight,filterSource:this.filterSource});return t.onSizeChanged.subscribe(()=>{this.calcSize()}),[e,o,t]})())}const o=await Promise.all(i);this.logos=new Array(n.length);for(let e=0;e<n.length;++e)this.logos[e]={};for(const[e,t,n]of o)this.logos[e][t]=n,this.viewSubs.push(n.onFreqsCalculated.subscribe(()=>{this.calcSize()}));this.mainLayout=s.table(this.chains,e=>[...n.length>0?[s.div(e,{style:{transform:"rotate(-90deg)",font:"12px Roboto, Roboto Local, sans-serif",textAlign:"center",width:"16px",marginTop:"24px",marginLeft:"6px"}})]:[],...[...Array(n.length).keys()].map(t=>{const n=this.logos[t][e];return n.root.style.height="100%",s.div([n.root],{style:{marginTop:"4px",marginBottom:"4px"}})})],["",...[...Array(n.length).keys()].map(e=>t.find(t=>t.order==n[e]&&t.chain==this.chains[0]).name||"Name")]),this.mainLayout.className="mlb-vd-regions-viewer-table2",this.filterSourceInput=s.input.choice("Data source",{value:this.filterSource,items:Object.values(Qe.lT),onValueChanged:this.filterSourceInputOnValueChanged.bind(this)}),this.filterSourceInput.root.style.position="absolute",this.filterSourceInput.root.style.right="9px",this.filterSourceInput.root.style.top="-4px",Math.ceil(255*Math.random()).toString(16),this.host=s.div([this.mainLayout,this.filterSourceInput.root],{}),this.root.appendChild(this.host),this.root.style.overflowX="auto",this.calcSize(),this.viewSubs.push(s.onSizeChanged(this.root).subscribe(this.rootOnSizeChanged.bind(this))),Uo.logger.debug("Bio: VdRegionsViewer.buildView() end")}calcSizeRequested=!1;calcSize(){Uo.logger.debug("Bio: VdRegionsViewer.calcSize(), start");const e=()=>{if(!this.host)return;const e=(this.root.clientHeight-54)/this.chains.length;let t=0;for(let n=0;n<this.logos.length;n++){for(const t of this.chains)this.logos[n][t].root.style.height=`${e}px`;t+=Math.max(...this.chains.map(e=>this.logos[n][e].Length))}if(this.fitWidth){if(this.logos.length>0&&t>0){const e=22,n=13,i=9,o=(this.root.clientWidth-e-(this.logos.length-1)*i-n)/t;for(let e=0;e<this.logos.length;e++)for(const t of this.chains){const n=this.logos[e][t];n.setOptions({[tt.n5.positionWidth]:o-n.positionMarginValue}),n.root.style.width=o*n.Length+"px"}}this.host.style.setProperty("overflow","hidden","important")}else{for(let e=0;e<this.logos.length;e++)for(const t of this.chains)this.logos[e][t].setOptions({[tt.n5.positionWidth]:this.positionWidth});this.host.style.removeProperty("overflow")}0===this.positionWidth?this.host.style.setProperty("overflow-x","hidden","important"):this.host.style.removeProperty("overflow-x")};this.calcSizeRequested||(this.calcSizeRequested=!0,window.setTimeout(()=>{e(),this.calcSizeRequested=!1},0))}rootOnSizeChanged(e){this.calcSize()}rootOnMouseMove(e){}filterSourceInputOnValueChanged(){const e=`${this.viewerToLog()}.filterSourceInputOnValueChanged()`,t=this.filterSourceInput.value;this.viewSyncer.sync(`${e}`,async()=>{if(this.filterSource!==t){this.props.getProperty(ot.filterSource).set(this,t);for(let e=0;e<this.logos.length;e++)for(let t=0;t<this.chains.length;t++){const n=this.chains[t];this.logos[e][n].setOptions({[tt.n5.filterSource]:this.filterSource})}}})}_onRendered=new c.Subject;get onRendered(){return this._onRendered}invalidate(e){const t=`${this.viewerToLog()}.invalidate(${e?` <- ${e} `:""})`;this.viewSyncer.sync(`${t}`,async()=>{this._onRendered.next()})}async awaitRendered(e=5e3){await(0,Xe.PE)(this.onRendered,()=>{},()=>{this.invalidate()},e);const t=this.viewSyncer.resetErrors();if(t.length>0)throw t[0]}}class at{value;parentI;parentJ;constructor(){this.value=0,this.parentI=0,this.parentJ=0}}class lt{seq1;seq2;score;constructor(e,t,n){this.seq1=e,this.seq2=t,this.score=n}}class ct{seq1="";seq2="";gap=1;len1=0;len2=0;step=1;alignGrid=[];scores=[];dpGrid=[];connections={};BLOSUM45=[[5,-2,-1,-2,-1,-1,-1,0,-2,-1,-1,-1,-1,-2,-1,1,0,-2,-2,0,-1,-1,0,-5],[-2,7,0,-1,-3,1,0,-2,0,-3,-2,3,-1,-2,-2,-1,-1,-2,-1,-2,-1,0,-1,-5],[-1,0,6,2,-2,0,0,0,1,-2,-3,0,-2,-2,-2,1,0,-4,-2,-3,4,0,-1,-5],[-2,-1,2,7,-3,0,2,-1,0,-4,-3,0,-3,-4,-1,0,-1,-4,-2,-3,5,1,-1,-5],[-1,-3,-2,-3,12,-3,-3,-3,-3,-3,-2,-3,-2,-2,-4,-1,-1,-5,-3,-1,-2,-3,-2,-5],[-1,1,0,0,-3,6,2,-2,1,-2,-2,1,0,-4,-1,0,-1,-2,-1,-3,0,4,-1,-5],[-1,0,0,2,-3,2,6,-2,0,-3,-2,1,-2,-3,0,0,-1,-3,-2,-3,1,4,-1,-5],[0,-2,0,-1,-3,-2,-2,7,-2,-4,-3,-2,-2,-3,-2,0,-2,-2,-3,-3,-1,-2,-1,-5],[-2,0,1,0,-3,1,0,-2,10,-3,-2,-1,0,-2,-2,-1,-2,-3,2,-3,0,0,-1,-5],[-1,-3,-2,-4,-3,-2,-3,-4,-3,5,2,-3,2,0,-2,-2,-1,-2,0,3,-3,-3,-1,-5],[-1,-2,-3,-3,-2,-2,-2,-3,-2,2,5,-3,2,1,-3,-3,-1,-2,0,1,-3,-2,-1,-5],[-1,3,0,0,-3,1,1,-2,-1,-3,-3,5,-1,-3,-1,-1,-1,-2,-1,-2,0,1,-1,-5],[-1,-1,-2,-3,-2,0,-2,-2,0,2,2,-1,6,0,-2,-2,-1,-2,0,1,-2,-1,-1,-5],[-2,-2,-2,-4,-2,-4,-3,-3,-2,0,1,-3,0,8,-3,-2,-1,1,3,0,-3,-3,-1,-5],[-1,-2,-2,-1,-4,-1,0,-2,-2,-2,-3,-1,-2,-3,9,-1,-1,-3,-3,-3,-2,-1,-1,-5],[1,-1,1,0,-1,0,0,0,-1,-2,-3,-1,-2,-2,-1,4,2,-4,-2,-1,0,0,0,-5],[0,-1,0,-1,-1,-1,-1,-2,-2,-1,-1,-1,-1,-1,-1,2,5,-3,-1,0,0,-1,0,-5],[-2,-2,-4,-4,-5,-2,-3,-2,-3,-2,-2,-2,-2,1,-3,-4,-3,15,3,-3,-4,-2,-2,-5],[-2,-1,-2,-2,-3,-1,-2,-3,2,0,0,-1,0,3,-3,-2,-1,3,8,-1,-2,-2,-1,-5],[0,-2,-3,-3,-1,-3,-3,-3,-3,3,1,-2,1,0,-3,-1,0,-3,-1,5,-3,-3,-1,-5],[-1,-1,4,5,-2,0,1,-1,0,-3,-3,0,-2,-3,-2,0,0,-4,-2,-3,4,2,-1,-5],[-1,0,0,1,-3,4,4,-2,0,-3,-2,1,-1,-3,-1,0,-1,-2,-2,-3,2,4,-1,-5],[0,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,0,-2,-1,-1,-1,-1,-1,-5],[-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,1]];BLOSUM50=[[5,-2,-1,-2,-1,-1,-1,0,-2,-1,-2,-1,-1,-3,-1,1,0,-3,-2,0,-2,-1,-1,-5],[-2,7,-1,-2,-4,1,0,-3,0,-4,-3,3,-2,-3,-3,-1,-1,-3,-1,-3,-1,0,-1,-5],[-1,-1,7,2,-2,0,0,0,1,-3,-4,0,-2,-4,-2,1,0,-4,-2,-3,4,0,-1,-5],[-2,-2,2,8,-4,0,2,-1,-1,-4,-4,-1,-4,-5,-1,0,-1,-5,-3,-4,5,1,-1,-5],[-1,-4,-2,-4,13,-3,-3,-3,-3,-2,-2,-3,-2,-2,-4,-1,-1,-5,-3,-1,-3,-3,-2,-5],[-1,1,0,0,-3,7,2,-2,1,-3,-2,2,0,-4,-1,0,-1,-1,-1,-3,0,4,-1,-5],[-1,0,0,2,-3,2,6,-3,0,-4,-3,1,-2,-3,-1,-1,-1,-3,-2,-3,1,5,-1,-5],[0,-3,0,-1,-3,-2,-3,8,-2,-4,-4,-2,-3,-4,-2,0,-2,-3,-3,-4,-1,-2,-2,-5],[-2,0,1,-1,-3,1,0,-2,10,-4,-3,0,-1,-1,-2,-1,-2,-3,2,-4,0,0,-1,-5],[-1,-4,-3,-4,-2,-3,-4,-4,-4,5,2,-3,2,0,-3,-3,-1,-3,-1,4,-4,-3,-1,-5],[-2,-3,-4,-4,-2,-2,-3,-4,-3,2,5,-3,3,1,-4,-3,-1,-2,-1,1,-4,-3,-1,-5],[-1,3,0,-1,-3,2,1,-2,0,-3,-3,6,-2,-4,-1,0,-1,-3,-2,-3,0,1,-1,-5],[-1,-2,-2,-4,-2,0,-2,-3,-1,2,3,-2,7,0,-3,-2,-1,-1,0,1,-3,-1,-1,-5],[-3,-3,-4,-5,-2,-4,-3,-4,-1,0,1,-4,0,8,-4,-3,-2,1,4,-1,-4,-4,-2,-5],[-1,-3,-2,-1,-4,-1,-1,-2,-2,-3,-4,-1,-3,-4,10,-1,-1,-4,-3,-3,-2,-1,-2,-5],[1,-1,1,0,-1,0,-1,0,-1,-3,-3,0,-2,-3,-1,5,2,-4,-2,-2,0,0,-1,-5],[0,-1,0,-1,-1,-1,-1,-2,-2,-1,-1,-1,-1,-2,-1,2,5,-3,-2,0,0,-1,0,-5],[-3,-3,-4,-5,-5,-1,-3,-3,-3,-3,-2,-3,-1,1,-4,-4,-3,15,2,-3,-5,-2,-3,-5],[-2,-1,-2,-3,-3,-1,-2,-3,2,-1,-1,-2,0,4,-3,-2,-2,2,8,-1,-3,-2,-1,-5],[0,-3,-3,-4,-1,-3,-3,-4,-4,4,1,-3,1,-1,-3,-2,0,-3,-1,5,-4,-3,-1,-5],[-2,-1,4,5,-3,0,1,-1,0,-4,-4,0,-3,-4,-2,0,0,-5,-3,-4,5,2,-1,-5],[-1,0,0,1,-3,4,5,-2,0,-3,-3,1,-1,-4,-1,0,-1,-2,-2,-3,2,5,-1,-5],[-1,-1,-1,-1,-2,-1,-1,-2,-1,-1,-1,-1,-1,-2,-2,-1,0,-3,-1,-1,-1,-1,-1,-5],[-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,1]];BLOSUM62=[[4,-1,-2,-2,0,-1,-1,0,-2,-1,-1,-1,-1,-2,-1,1,0,-3,-2,0,-2,-1,0,-4],[-1,5,0,-2,-3,1,0,-2,0,-3,-2,2,-1,-3,-2,-1,-1,-3,-2,-3,-1,0,-1,-4],[-2,0,6,1,-3,0,0,0,1,-3,-3,0,-2,-3,-2,1,0,-4,-2,-3,3,0,-1,-4],[-2,-2,1,6,-3,0,2,-1,-1,-3,-4,-1,-3,-3,-1,0,-1,-4,-3,-3,4,1,-1,-4],[0,-3,-3,-3,9,-3,-4,-3,-3,-1,-1,-3,-1,-2,-3,-1,-1,-2,-2,-1,-3,-3,-2,-4],[-1,1,0,0,-3,5,2,-2,0,-3,-2,1,0,-3,-1,0,-1,-2,-1,-2,0,3,-1,-4],[-1,0,0,2,-4,2,5,-2,0,-3,-3,1,-2,-3,-1,0,-1,-3,-2,-2,1,4,-1,-4],[0,-2,0,-1,-3,-2,-2,6,-2,-4,-4,-2,-3,-3,-2,0,-2,-2,-3,-3,-1,-2,-1,-4],[-2,0,1,-1,-3,0,0,-2,8,-3,-3,-1,-2,-1,-2,-1,-2,-2,2,-3,0,0,-1,-4],[-1,-3,-3,-3,-1,-3,-3,-4,-3,4,2,-3,1,0,-3,-2,-1,-3,-1,3,-3,-3,-1,-4],[-1,-2,-3,-4,-1,-2,-3,-4,-3,2,4,-2,2,0,-3,-2,-1,-2,-1,1,-4,-3,-1,-4],[-1,2,0,-1,-3,1,1,-2,-1,-3,-2,5,-1,-3,-1,0,-1,-3,-2,-2,0,1,-1,-4],[-1,-1,-2,-3,-1,0,-2,-3,-2,1,2,-1,5,0,-2,-1,-1,-1,-1,1,-3,-1,-1,-4],[-2,-3,-3,-3,-2,-3,-3,-3,-1,0,0,-3,0,6,-4,-2,-2,1,3,-1,-3,-3,-1,-4],[-1,-2,-2,-1,-3,-1,-1,-2,-2,-3,-3,-1,-2,-4,7,-1,-1,-4,-3,-2,-2,-1,-2,-4],[1,-1,1,0,-1,0,0,0,-1,-2,-2,0,-1,-2,-1,4,1,-3,-2,-2,0,0,0,-4],[0,-1,0,-1,-1,-1,-1,-2,-2,-1,-1,-1,-1,-2,-1,1,5,-2,-2,0,-1,-1,0,-4],[-3,-3,-4,-4,-2,-2,-3,-2,-2,-3,-2,-3,-1,1,-4,-3,-2,11,2,-3,-4,-3,-2,-4],[-2,-2,-2,-3,-2,-1,-2,-3,2,-1,-1,-2,-1,3,-3,-2,-2,2,7,-1,-3,-2,-1,-4],[0,-3,-3,-3,-1,-2,-2,-3,-3,3,1,-2,1,-1,-2,-2,0,-3,-1,4,-3,-2,-1,-4],[-2,-1,3,4,-3,0,1,-1,0,-3,-4,0,-3,-3,-2,0,-1,-4,-3,-3,4,1,-1,-4],[-1,0,0,1,-3,3,4,-2,0,-3,-3,1,-1,-3,-1,0,-1,-3,-2,-2,1,4,-1,-4],[0,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-2,0,0,-2,-1,-1,-1,-1,-1,-4],[-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,1]];BLOSUM80=[[7,-3,-3,-3,-1,-2,-2,0,-3,-3,-3,-1,-2,-4,-1,2,0,-5,-4,-1,-3,-2,-1,-8],[-3,9,-1,-3,-6,1,-1,-4,0,-5,-4,3,-3,-5,-3,-2,-2,-5,-4,-4,-2,0,-2,-8],[-3,-1,9,2,-5,0,-1,-1,1,-6,-6,0,-4,-6,-4,1,0,-7,-4,-5,5,-1,-2,-8],[-3,-3,2,10,-7,-1,2,-3,-2,-7,-7,-2,-6,-6,-3,-1,-2,-8,-6,-6,6,1,-3,-8],[-1,-6,-5,-7,13,-5,-7,-6,-7,-2,-3,-6,-3,-4,-6,-2,-2,-5,-5,-2,-6,-7,-4,-8],[-2,1,0,-1,-5,9,3,-4,1,-5,-4,2,-1,-5,-3,-1,-1,-4,-3,-4,-1,5,-2,-8],[-2,-1,-1,2,-7,3,8,-4,0,-6,-6,1,-4,-6,-2,-1,-2,-6,-5,-4,1,6,-2,-8],[0,-4,-1,-3,-6,-4,-4,9,-4,-7,-7,-3,-5,-6,-5,-1,-3,-6,-6,-6,-2,-4,-3,-8],[-3,0,1,-2,-7,1,0,-4,12,-6,-5,-1,-4,-2,-4,-2,-3,-4,3,-5,-1,0,-2,-8],[-3,-5,-6,-7,-2,-5,-6,-7,-6,7,2,-5,2,-1,-5,-4,-2,-5,-3,4,-6,-6,-2,-8],[-3,-4,-6,-7,-3,-4,-6,-7,-5,2,6,-4,3,0,-5,-4,-3,-4,-2,1,-7,-5,-2,-8],[-1,3,0,-2,-6,2,1,-3,-1,-5,-4,8,-3,-5,-2,-1,-1,-6,-4,-4,-1,1,-2,-8],[-2,-3,-4,-6,-3,-1,-4,-5,-4,2,3,-3,9,0,-4,-3,-1,-3,-3,1,-5,-3,-2,-8],[-4,-5,-6,-6,-4,-5,-6,-6,-2,-1,0,-5,0,10,-6,-4,-4,0,4,-2,-6,-6,-3,-8],[-1,-3,-4,-3,-6,-3,-2,-5,-4,-5,-5,-2,-4,-6,12,-2,-3,-7,-6,-4,-4,-2,-3,-8],[2,-2,1,-1,-2,-1,-1,-1,-2,-4,-4,-1,-3,-4,-2,7,2,-6,-3,-3,0,-1,-1,-8],[0,-2,0,-2,-2,-1,-2,-3,-3,-2,-3,-1,-1,-4,-3,2,8,-5,-3,0,-1,-2,-1,-8],[-5,-5,-7,-8,-5,-4,-6,-6,-4,-5,-4,-6,-3,0,-7,-6,-5,16,3,-5,-8,-5,-5,-8],[-4,-4,-4,-6,-5,-3,-5,-6,3,-3,-2,-4,-3,4,-6,-3,-3,3,11,-3,-5,-4,-3,-8],[-1,-4,-5,-6,-2,-4,-4,-6,-5,4,1,-4,1,-2,-4,-3,0,-5,-3,7,-6,-4,-2,-8],[-3,-2,5,6,-6,-1,1,-2,-1,-6,-7,-1,-5,-6,-4,0,-1,-8,-5,-6,6,0,-3,-8],[-2,0,-1,1,-7,5,6,-4,0,-6,-5,1,-3,-6,-2,-1,-2,-5,-4,-4,0,6,-1,-8],[-1,-2,-2,-3,-4,-2,-2,-3,-2,-2,-2,-2,-2,-3,-3,-1,-1,-5,-3,-2,-3,-1,-2,-8],[-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,1]];BLOSUM90=[[5,-2,-2,-3,-1,-1,-1,0,-2,-2,-2,-1,-2,-3,-1,1,0,-4,-3,-1,-2,-1,-1,-6],[-2,6,-1,-3,-5,1,-1,-3,0,-4,-3,2,-2,-4,-3,-1,-2,-4,-3,-3,-2,0,-2,-6],[-2,-1,7,1,-4,0,-1,-1,0,-4,-4,0,-3,-4,-3,0,0,-5,-3,-4,4,-1,-2,-6],[-3,-3,1,7,-5,-1,1,-2,-2,-5,-5,-1,-4,-5,-3,-1,-2,-6,-4,-5,4,0,-2,-6],[-1,-5,-4,-5,9,-4,-6,-4,-5,-2,-2,-4,-2,-3,-4,-2,-2,-4,-4,-2,-4,-5,-3,-6],[-1,1,0,-1,-4,7,2,-3,1,-4,-3,1,0,-4,-2,-1,-1,-3,-3,-3,-1,4,-1,-6],[-1,-1,-1,1,-6,2,6,-3,-1,-4,-4,0,-3,-5,-2,-1,-1,-5,-4,-3,0,4,-2,-6],[0,-3,-1,-2,-4,-3,-3,6,-3,-5,-5,-2,-4,-5,-3,-1,-3,-4,-5,-5,-2,-3,-2,-6],[-2,0,0,-2,-5,1,-1,-3,8,-4,-4,-1,-3,-2,-3,-2,-2,-3,1,-4,-1,0,-2,-6],[-2,-4,-4,-5,-2,-4,-4,-5,-4,5,1,-4,1,-1,-4,-3,-1,-4,-2,3,-5,-4,-2,-6],[-2,-3,-4,-5,-2,-3,-4,-5,-4,1,5,-3,2,0,-4,-3,-2,-3,-2,0,-5,-4,-2,-6],[-1,2,0,-1,-4,1,0,-2,-1,-4,-3,6,-2,-4,-2,-1,-1,-5,-3,-3,-1,1,-1,-6],[-2,-2,-3,-4,-2,0,-3,-4,-3,1,2,-2,7,-1,-3,-2,-1,-2,-2,0,-4,-2,-1,-6],[-3,-4,-4,-5,-3,-4,-5,-5,-2,-1,0,-4,-1,7,-4,-3,-3,0,3,-2,-4,-4,-2,-6],[-1,-3,-3,-3,-4,-2,-2,-3,-3,-4,-4,-2,-3,-4,8,-2,-2,-5,-4,-3,-3,-2,-2,-6],[1,-1,0,-1,-2,-1,-1,-1,-2,-3,-3,-1,-2,-3,-2,5,1,-4,-3,-2,0,-1,-1,-6],[0,-2,0,-2,-2,-1,-1,-3,-2,-1,-2,-1,-1,-3,-2,1,6,-4,-2,-1,-1,-1,-1,-6],[-4,-4,-5,-6,-4,-3,-5,-4,-3,-4,-3,-5,-2,0,-5,-4,-4,11,2,-3,-6,-4,-3,-6],[-3,-3,-3,-4,-4,-3,-4,-5,1,-2,-2,-3,-2,3,-4,-3,-2,2,8,-3,-4,-3,-2,-6],[-1,-3,-4,-5,-2,-3,-3,-5,-4,3,0,-3,0,-2,-3,-2,-1,-3,-3,5,-4,-3,-2,-6],[-2,-2,4,4,-4,-1,0,-2,-1,-5,-5,-1,-4,-4,-3,0,-1,-6,-4,-4,4,0,-2,-6],[-1,0,-1,0,-5,4,4,-3,0,-4,-4,1,-2,-4,-2,-1,-1,-4,-3,-3,0,4,-1,-6],[-1,-2,-2,-2,-3,-1,-2,-2,-2,-2,-2,-1,-1,-2,-2,-1,-1,-3,-2,-2,-2,-1,-2,-6],[-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,1]];NUCLEOTIDES=[[1,-1,-1,-1],[-1,1,-1,-1],[-1,-1,1,-1],[-1,-1,-1,1]];PAM30=[[6,-7,-4,-3,-6,-4,-2,-2,-7,-5,-6,-7,-5,-8,-2,0,-1,-13,-8,-2,-3,-3,-3,-17],[-7,8,-6,-10,-8,-2,-9,-9,-2,-5,-8,0,-4,-9,-4,-3,-6,-2,-10,-8,-7,-4,-6,-17],[-4,-6,8,2,-11,-3,-2,-3,0,-5,-7,-1,-9,-9,-6,0,-2,-8,-4,-8,6,-3,-3,-17],[-3,-10,2,8,-14,-2,2,-3,-4,-7,-12,-4,-11,-15,-8,-4,-5,-15,-11,-8,6,1,-5,-17],[-6,-8,-11,-14,10,-14,-14,-9,-7,-6,-15,-14,-13,-13,-8,-3,-8,-15,-4,-6,-12,-14,-9,-17],[-4,-2,-3,-2,-14,8,1,-7,1,-8,-5,-3,-4,-13,-3,-5,-5,-13,-12,-7,-3,6,-5,-17],[-2,-9,-2,2,-14,1,8,-4,-5,-5,-9,-4,-7,-14,-5,-4,-6,-17,-8,-6,1,6,-5,-17],[-2,-9,-3,-3,-9,-7,-4,6,-9,-11,-10,-7,-8,-9,-6,-2,-6,-15,-14,-5,-3,-5,-5,-17],[-7,-2,0,-4,-7,1,-5,-9,9,-9,-6,-6,-10,-6,-4,-6,-7,-7,-3,-6,-1,-1,-5,-17],[-5,-5,-5,-7,-6,-8,-5,-11,-9,8,-1,-6,-1,-2,-8,-7,-2,-14,-6,2,-6,-6,-5,-17],[-6,-8,-7,-12,-15,-5,-9,-10,-6,-1,7,-8,1,-3,-7,-8,-7,-6,-7,-2,-9,-7,-6,-17],[-7,0,-1,-4,-14,-3,-4,-7,-6,-6,-8,7,-2,-14,-6,-4,-3,-12,-9,-9,-2,-4,-5,-17],[-5,-4,-9,-11,-13,-4,-7,-8,-10,-1,1,-2,11,-4,-8,-5,-4,-13,-11,-1,-10,-5,-5,-17],[-8,-9,-9,-15,-13,-13,-14,-9,-6,-2,-3,-14,-4,9,-10,-6,-9,-4,2,-8,-10,-13,-8,-17],[-2,-4,-6,-8,-8,-3,-5,-6,-4,-8,-7,-6,-8,-10,8,-2,-4,-14,-13,-6,-7,-4,-5,-17],[0,-3,0,-4,-3,-5,-4,-2,-6,-7,-8,-4,-5,-6,-2,6,0,-5,-7,-6,-1,-5,-3,-17],[-1,-6,-2,-5,-8,-5,-6,-6,-7,-2,-7,-3,-4,-9,-4,0,7,-13,-6,-3,-3,-6,-4,-17],[-13,-2,-8,-15,-15,-13,-17,-15,-7,-14,-6,-12,-13,-4,-14,-5,-13,13,-5,-15,-10,-14,-11,-17],[-8,-10,-4,-11,-4,-12,-8,-14,-3,-6,-7,-9,-11,2,-13,-7,-6,-5,10,-7,-6,-9,-7,-17],[-2,-8,-8,-8,-6,-7,-6,-5,-6,2,-2,-9,-1,-8,-6,-6,-3,-15,-7,7,-8,-6,-5,-17],[-3,-7,6,6,-12,-3,1,-3,-1,-6,-9,-2,-10,-10,-7,-1,-3,-10,-6,-8,6,0,-5,-17],[-3,-4,-3,1,-14,6,6,-5,-1,-6,-7,-4,-5,-13,-4,-5,-6,-14,-9,-6,0,6,-5,-17],[-3,-6,-3,-5,-9,-5,-5,-5,-5,-5,-6,-5,-5,-8,-5,-3,-4,-11,-7,-5,-5,-5,-5,-17],[-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,1]];PAM70=[[5,-4,-2,-1,-4,-2,-1,0,-4,-2,-4,-4,-3,-6,0,1,1,-9,-5,-1,-1,-1,-2,-11],[-4,8,-3,-6,-5,0,-5,-6,0,-3,-6,2,-2,-7,-2,-1,-4,0,-7,-5,-4,-2,-3,-11],[-2,-3,6,3,-7,-1,0,-1,1,-3,-5,0,-5,-6,-3,1,0,-6,-3,-5,5,-1,-2,-11],[-1,-6,3,6,-9,0,3,-1,-1,-5,-8,-2,-7,-10,-4,-1,-2,-10,-7,-5,5,2,-3,-11],[-4,-5,-7,-9,9,-9,-9,-6,-5,-4,-10,-9,-9,-8,-5,-1,-5,-11,-2,-4,-8,-9,-6,-11],[-2,0,-1,0,-9,7,2,-4,2,-5,-3,-1,-2,-9,-1,-3,-3,-8,-8,-4,-1,5,-2,-11],[-1,-5,0,3,-9,2,6,-2,-2,-4,-6,-2,-4,-9,-3,-2,-3,-11,-6,-4,2,5,-3,-11],[0,-6,-1,-1,-6,-4,-2,6,-6,-6,-7,-5,-6,-7,-3,0,-3,-10,-9,-3,-1,-3,-3,-11],[-4,0,1,-1,-5,2,-2,-6,8,-6,-4,-3,-6,-4,-2,-3,-4,-5,-1,-4,0,1,-3,-11],[-2,-3,-3,-5,-4,-5,-4,-6,-6,7,1,-4,1,0,-5,-4,-1,-9,-4,3,-4,-4,-3,-11],[-4,-6,-5,-8,-10,-3,-6,-7,-4,1,6,-5,2,-1,-5,-6,-4,-4,-4,0,-6,-4,-4,-11],[-4,2,0,-2,-9,-1,-2,-5,-3,-4,-5,6,0,-9,-4,-2,-1,-7,-7,-6,-1,-2,-3,-11],[-3,-2,-5,-7,-9,-2,-4,-6,-6,1,2,0,10,-2,-5,-3,-2,-8,-7,0,-6,-3,-3,-11],[-6,-7,-6,-10,-8,-9,-9,-7,-4,0,-1,-9,-2,8,-7,-4,-6,-2,4,-5,-7,-9,-5,-11],[0,-2,-3,-4,-5,-1,-3,-3,-2,-5,-5,-4,-5,-7,7,0,-2,-9,-9,-3,-4,-2,-3,-11],[1,-1,1,-1,-1,-3,-2,0,-3,-4,-6,-2,-3,-4,0,5,2,-3,-5,-3,0,-2,-1,-11],[1,-4,0,-2,-5,-3,-3,-3,-4,-1,-4,-1,-2,-6,-2,2,6,-8,-4,-1,-1,-3,-2,-11],[-9,0,-6,-10,-11,-8,-11,-10,-5,-9,-4,-7,-8,-2,-9,-3,-8,13,-3,-10,-7,-10,-7,-11],[-5,-7,-3,-7,-2,-8,-6,-9,-1,-4,-4,-7,-7,4,-9,-5,-4,-3,9,-5,-4,-7,-5,-11],[-1,-5,-5,-5,-4,-4,-4,-3,-4,3,0,-6,0,-5,-3,-3,-1,-10,-5,6,-5,-4,-2,-11],[-1,-4,5,5,-8,-1,2,-1,0,-4,-6,-1,-6,-7,-4,0,-1,-7,-4,-5,5,1,-2,-11],[-1,-2,-1,2,-9,5,5,-3,1,-4,-4,-2,-3,-9,-2,-2,-3,-10,-7,-4,1,5,-3,-11],[-2,-3,-2,-3,-6,-2,-3,-3,-3,-3,-4,-3,-3,-5,-3,-1,-2,-7,-5,-2,-2,-3,-3,-11],[-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,1]];PAM250=[[2,-2,0,0,-2,0,0,1,-1,-1,-2,-1,-1,-3,1,1,1,-6,-3,0,0,0,0,-8],[-2,6,0,-1,-4,1,-1,-3,2,-2,-3,3,0,-4,0,0,-1,2,-4,-2,-1,0,-1,-8],[0,0,2,2,-4,1,1,0,2,-2,-3,1,-2,-3,0,1,0,-4,-2,-2,2,1,0,-8],[0,-1,2,4,-5,2,3,1,1,-2,-4,0,-3,-6,-1,0,0,-7,-4,-2,3,3,-1,-8],[-2,-4,-4,-5,12,-5,-5,-3,-3,-2,-6,-5,-5,-4,-3,0,-2,-8,0,-2,-4,-5,-3,-8],[0,1,1,2,-5,4,2,-1,3,-2,-2,1,-1,-5,0,-1,-1,-5,-4,-2,1,3,-1,-8],[0,-1,1,3,-5,2,4,0,1,-2,-3,0,-2,-5,-1,0,0,-7,-4,-2,3,3,-1,-8],[1,-3,0,1,-3,-1,0,5,-2,-3,-4,-2,-3,-5,0,1,0,-7,-5,-1,0,0,-1,-8],[-1,2,2,1,-3,3,1,-2,6,-2,-2,0,-2,-2,0,-1,-1,-3,0,-2,1,2,-1,-8],[-1,-2,-2,-2,-2,-2,-2,-3,-2,5,2,-2,2,1,-2,-1,0,-5,-1,4,-2,-2,-1,-8],[-2,-3,-3,-4,-6,-2,-3,-4,-2,2,6,-3,4,2,-3,-3,-2,-2,-1,2,-3,-3,-1,-8],[-1,3,1,0,-5,1,0,-2,0,-2,-3,5,0,-5,-1,0,0,-3,-4,-2,1,0,-1,-8],[-1,0,-2,-3,-5,-1,-2,-3,-2,2,4,0,6,0,-2,-2,-1,-4,-2,2,-2,-2,-1,-8],[-3,-4,-3,-6,-4,-5,-5,-5,-2,1,2,-5,0,9,-5,-3,-3,0,7,-1,-4,-5,-2,-8],[1,0,0,-1,-3,0,-1,0,0,-2,-3,-1,-2,-5,6,1,0,-6,-5,-1,-1,0,-1,-8],[1,0,1,0,0,-1,0,1,-1,-1,-3,0,-2,-3,1,2,1,-2,-3,-1,0,0,0,-8],[1,-1,0,0,-2,-1,0,0,-1,0,-2,0,-1,-3,0,1,3,-5,-3,0,0,-1,0,-8],[-6,2,-4,-7,-8,-5,-7,-7,-3,-5,-2,-3,-4,0,-6,-2,-5,17,0,-6,-5,-6,-4,-8],[-3,-4,-2,-4,0,-4,-4,-5,0,-1,-1,-4,-2,7,-5,-3,-3,0,10,-2,-3,-4,-2,-8],[0,-2,-2,-2,-2,-2,-2,-1,-2,4,2,-2,2,-1,-1,-1,0,-6,-2,4,-2,-2,-1,-8],[0,-1,2,3,-4,1,3,0,1,-2,-3,1,-2,-4,-1,0,0,-5,-3,-2,3,2,-1,-8],[0,0,1,3,-5,3,3,0,2,-2,-3,0,-2,-5,0,0,-1,-6,-4,-2,2,3,-1,-8],[0,-1,0,-1,-3,-1,-1,-1,-1,-1,-1,-1,-1,-2,-1,0,0,-4,-2,-1,-1,-1,-1,-8],[-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,1]];SCHNEIDER=[[11.6,-2.7,9.7,-1.7,-2.7,-6.4,-3.9,-5.6,5.1,-5,3.6,-4.2,-6.3,-13,-7.1,-11.5,.4,-6,-1.9,-5.3,-8.5,-11.2,-8.9,-10.8,2.1,0,1.4,.2,-10.2,-13.5,-13,-12.5,-2.6,-8.5,-5,-8.1,-6.3,-9.9,-7.5,-9,-7.1,-10.2,-8.2,-9.2,-8.2,-12.5,-11.1,-11.4,-50,-14.8,-50,-13.8,-7.3,-10.1,-8.4,-9.1,-50,-13,-13.5,-12.4,-10.7,-18.1,-11.8,-17.2],[-2.7,13,-3.3,10.9,-3.5,-.4,-3.3,-1.8,-5.4,4.6,-5.5,3,-10.2,-7.9,-9.9,-9.6,-5,.5,-5.5,-1,-10.3,-8.1,-9.4,-9.6,-8.1,-5,-7.3,-6.3,-13.4,-11.3,-14.4,-12.9,-6.3,.8,-6.4,-1.1,-7.4,-5,-6.2,-6.5,-5.6,-1.6,-4.7,-3,-10.8,-8.7,-11.9,-10,-50,-6.2,-50,-7.5,-6.3,-4.3,-6.2,-5.4,-50,-7,-16.3,-8.2,-13.2,-12.3,-13.1,-13.3],[9.7,-3.3,11.6,-2.8,-4.5,-6.7,-3.1,-6.9,3.3,-5.5,4.8,-5.1,-8.9,-13.2,-5.7,-12.6,-1.5,-6.1,-.6,-6.1,-10,-11.8,-8.6,-11.9,1.2,.5,2.2,.1,-11.8,-14,-11.9,-13.4,-4.9,-9.1,-3.4,-8.9,-8,-10,-7.2,-10,-9.1,-10.2,-7.1,-9.9,-10.1,-13,-10.6,-12.7,-50,-14.9,-50,-14.4,-8.9,-10.8,-8.9,-10.4,-50,-13.1,-11.8,-13,-12.4,-19.4,-11.5,-17.8],[-1.7,10.9,-2.8,12.9,-2.7,-2.2,-2.8,.2,-4.8,2.9,-5.2,5.2,-9.1,-9.5,-9,-7,-4,-1,-5,1,-9,-8.8,-8.9,-7.7,-7,-6.8,-7.1,-4.3,-12.4,-12.9,-13.9,-10,-4.9,-.7,-5.6,1.4,-6,-6.5,-6.2,-4.8,-5.1,-3.2,-5,-1.2,-9.8,-9.9,-11.3,-8.2,-50,-7.6,-50,-5.1,-5.5,-5.8,-5.9,-4.2,-50,-8.3,-15.5,-5.9,-11.6,-14.2,-12,-11.6],[-2.7,-3.5,-4.5,-2.7,11.7,9,10.6,9.6,-3.2,-.7,-5.1,-.4,.7,-4.6,-.4,-3.6,-4.8,-8.9,-6.5,-7.8,-1.4,-4.1,-2.9,-3.3,-8,-9.1,-8,-8.2,-6,-9.3,-7.7,-8.5,-6.4,-10.1,-7.5,-8.6,2.8,-.7,.9,.1,-5.9,-7.3,-6.5,-6.5,-.4,-3.9,-2.6,-3.1,-50,-14.6,-50,-12.6,2.9,.1,1.8,1,-50,-9.2,-13.6,-7.7,-4.8,-12.2,-6.2,-11],[-6.4,-.4,-6.7,-2.2,9,12.3,9.8,9.6,-7.1,2.4,-7.2,.3,-2.9,-1.2,-3,-3.3,-7.6,-6.7,-8.1,-7.9,-4.9,-1.9,-4.5,-3.8,-9.5,-7.8,-9.3,-8.9,-9.4,-7.1,-9,-9,-9.4,-7.5,-9.3,-9.2,-.7,2.6,.2,-.1,-8,-4.6,-7.7,-6.1,-3.6,-1,-4.1,-3.1,-50,-11.6,-50,-11.6,.2,2.3,.4,.5,-50,-6.5,-15.3,-7.8,-8.4,-9.5,-8.3,-11.1],[-3.9,-3.3,-3.1,-2.8,10.6,9.8,12.2,9.8,-4.9,.1,-3.6,-.2,-1.7,-4.1,.9,-3.5,-5.9,-8.9,-5.6,-8.5,-3.9,-3.9,-2.2,-4.5,-7.3,-7.5,-6.4,-8.5,-7.1,-8.2,-6.7,-7.8,-7.9,-9.1,-7.1,-9.4,.9,-.2,2.5,-.3,-6.9,-6.5,-5.5,-6.8,-1.7,-3.4,-1.7,-2.8,-50,-13,-50,-11.5,1.5,.7,2.7,.6,-50,-8.9,-12.1,-7.4,-6.1,-11.5,-5.4,-10.4],[-5.6,-1.8,-6.9,.2,9.6,9.6,9.8,11.6,-6.6,.9,-7.2,2.5,-2.3,-3.4,-2.3,-.6,-6.5,-8.2,-8,-6.3,-3.7,-3.5,-3.9,-1.6,-9.9,-8.9,-9.6,-7,-8.6,-8.9,-8.8,-6.8,-8.6,-8.2,-8.8,-6.8,.3,.1,.2,2.4,-7.4,-6.2,-6.9,-4.4,-2.9,-2.9,-3.5,-.9,-50,-12.2,-50,-10.1,1.2,.6,1.2,2.4,-50,-7.6,-16.1,-5.8,-7.2,-10.8,-7.4,-9],[5.1,-5.4,3.3,-4.8,-3.2,-7.1,-4.9,-6.6,13.3,-2.8,11.2,-1.9,-5.7,-12.5,-7.2,-11.6,-.7,-4.8,-3.1,-4.3,-10,-11.6,-8.8,-11.7,10.5,7.7,9.1,8.5,-9.8,-12.7,-11.7,-11.8,-6.3,-11.4,-8.8,-11,-7.5,-10.3,-8.3,-9.9,-1.9,-6.7,-4.1,-6.4,-7.9,-12.5,-11.4,-11.7,-50,-14,-50,-13.2,-8.5,-10.4,-9.1,-9.6,-50,-9.8,-7.7,-8.8,-10.3,-17.9,-11.8,-16],[-5,4.6,-5.5,2.9,-.7,2.4,.1,.9,-2.8,12.8,-2.6,11,-8.4,-6.3,-8.3,-7.7,-6.1,-2.9,-6.5,-4.2,-8.5,-5.9,-7.5,-7.7,-5.5,-2.4,-5.5,-4.1,-12.9,-10.3,-12.7,-11.3,-7.4,-3.1,-7.4,-4.9,-4.4,-1.8,-3.5,-3.5,-1.6,3,-.8,.9,-8.4,-6.3,-9.6,-7.3,-50,-9,-50,-9.7,-2.3,-.2,-1.2,-1.5,-50,-.7,-13.3,-2,-11.8,-11.9,-12.3,-12.7],[3.6,-5.5,4.8,-5.2,-5.1,-7.2,-3.6,-7.2,11.2,-2.6,13.4,-2.1,-7.7,-12.5,-5.3,-11.9,-2.2,-4.4,-1.9,-4.8,-10.2,-11.5,-8.1,-12,9.3,8.2,10,8,-10.8,-11.9,-10.7,-12.4,-8.2,-11.8,-6.9,-11.5,-8.4,-9.9,-7.1,-10.6,-4.7,-6.8,-1.2,-7,-9.8,-11.6,-9.6,-12.1,-50,-14.1,-50,-12.7,-10,-10.8,-8.8,-10.5,-50,-9.2,-4.2,-9.3,-11,-18.2,-11.1,-16.1],[-4.2,3,-5.1,5.2,-.4,.3,-.2,2.5,-1.9,11,-2.1,13.2,-7.6,-8.5,-8,-5.3,-5.6,-4.5,-6.8,-2.4,-7.8,-7.9,-7.9,-6.2,-5.7,-5.1,-5.4,-2.1,-12.4,-12.3,-13.1,-10.1,-6.6,-4.4,-6.9,-2.6,-3.6,-3.8,-3.7,-2,-1.4,.8,-.9,3,-8.2,-8.1,-9.2,-5.8,-50,-10.1,-50,-7.4,-1.7,-2,-1.5,-.5,-50,-2.1,-12.6,-.4,-11.6,-13.9,-11.4,-11.1],[-6.3,-10.2,-8.9,-9.1,.7,-2.9,-1.7,-2.3,-5.7,-8.4,-7.7,-7.6,13.2,9.6,3.5,9.7,-8.7,-12.4,-10.7,-10.7,-7.8,-10.2,-8.8,-9.6,-9.5,-11.9,-10.9,-10.5,2.3,-.4,-.2,-.3,-9.7,-15.5,-11.4,-13.7,-3,-6.4,-4.1,-5.4,-9.6,-11.9,-10.5,-11.8,6.2,3.3,3.7,3.6,-50,-13.6,-50,-11.9,-5.6,-8.8,-7.2,-8.9,-50,-12.4,-14.1,-11.6,2.8,-6.4,.5,-5.2],[-13,-7.9,-13.2,-9.5,-4.6,-1.2,-4.1,-3.4,-12.5,-6.3,-12.5,-8.5,9.6,12.7,.2,10.5,-12.4,-11.6,-13.2,-12,-12.4,-10.1,-11.6,-12,-15.1,-13.1,-14.3,-13.4,-1.4,1.4,-1.6,-.5,-14.9,-14.3,-15.2,-16.8,-7.7,-4.7,-6.3,-6.6,-14.6,-10.8,-12.8,-13,2.3,6,2.5,3.6,-50,-11.2,-50,-11.9,-10.5,-9.2,-10.5,-10.5,-50,-10.3,-16.2,-11.3,-1.7,-3.7,-2.5,-5.4],[-7.1,-9.9,-5.7,-9,-.4,-3,.9,-2.3,-7.2,-8.3,-5.3,-8,3.5,.2,14.3,1,-7.3,-11.2,-6.9,-9.7,-8.5,-10.2,-7.7,-9.8,-10,-10.4,-8.4,-10.2,1,-.6,1.7,-.5,-11.1,-14.8,-9.7,-14.5,-3.7,-5.8,-3.1,-5.6,-10.4,-11.5,-8.2,-11.1,.6,-1.6,1.6,-1.1,-50,-12.4,-50,-11.5,-5.5,-8,-4.9,-7.2,-50,-12.4,-10.3,-11.6,.7,-6.8,2.4,-6],[-11.5,-9.6,-12.6,-7,-3.6,-3.3,-3.5,-.6,-11.6,-7.7,-11.9,-5.3,9.7,10.5,1,12.6,-12,-12.2,-12.5,-9.7,-11.1,-11.2,-11.9,-9.4,-12.9,-14.3,-14,-11.9,-1,-.4,-1.6,1.2,-13.9,-15.4,-13.7,-12.6,-6.2,-6.7,-6.3,-4.4,-13,-12.2,-13,-10.4,2.9,3.8,2.5,5.8,-50,-12.5,-50,-10.2,-9.6,-9.7,-9.6,-8.3,-50,-11.6,-15.4,-9.4,-1.1,-5.4,-1.6,-3.3],[.4,-5,-1.5,-4,-4.8,-7.6,-5.9,-6.5,-.7,-6.1,-2.2,-5.6,-8.7,-12.4,-7.3,-12,12.8,2.3,10.2,3,0,-3.4,-.7,-3.2,2.5,-.8,.9,.2,-3,-7.2,-5.7,-6.1,-.2,-6.6,-1.8,-6,-5.3,-8.2,-5.7,-7.6,-6.7,-9.6,-7.5,-9.3,-7.1,-10.5,-9.6,-9.4,-50,-8.1,-50,-7.2,-4.3,-6.8,-5.7,-6.3,-50,-9.5,-9.6,-8.9,-6.2,-12.8,-6.8,-11.8],[-6,.5,-6.1,-1,-8.9,-6.7,-8.9,-8.2,-4.8,-2.9,-4.4,-4.5,-12.4,-11.6,-11.2,-12.2,2.3,14.6,1.9,12.9,-5.5,-2.6,-4.1,-4.7,-1.2,3,-1.1,1.6,-8,-4.7,-8.7,-6,-8.2,-4.7,-7.8,-6.7,-10,-8.3,-8.9,-9.9,-10.8,-7.1,-10,-9.2,-11.6,-10.1,-12.3,-11.9,-50,2.2,-50,.9,-7.9,-5.9,-7.4,-6.9,-50,-4.6,-11.6,-5.6,-9.7,-5.9,-9.9,-7.3],[-1.9,-5.5,-.6,-5,-6.5,-8.1,-5.6,-8,-3.1,-6.5,-1.9,-6.8,-10.7,-13.2,-6.9,-12.5,10.2,1.9,11.9,2.1,-2.3,-4.1,-.5,-4.6,-.1,-.9,2.4,-.8,-5.1,-6.9,-4.8,-6.7,-2.3,-7.1,-.8,-7.2,-7.2,-8,-5.6,-8.5,-9.4,-9.7,-7.2,-9.8,-9.2,-11.1,-9.5,-10.7,-50,-8.7,-50,-8.6,-6.1,-7.5,-5.5,-7.7,-50,-10.4,-7.7,-10,-7.3,-13.6,-6.4,-13.3],[-5.3,-1,-6.1,1,-7.8,-7.9,-8.5,-6.3,-4.3,-4.2,-4.8,-2.4,-10.7,-12,-9.7,-9.7,3,12.9,2.1,14.7,-4.9,-3.8,-4,-2.4,-1,.8,-1.3,3.4,-7.6,-5.7,-8.1,-3.5,-6.8,-5.8,-7.2,-4.2,-8.9,-10.2,-8.4,-8.2,-9.9,-8.4,-9.7,-6.4,-11.1,-11.1,-11.8,-10,-50,.4,-50,2.6,-7.2,-7,-7.4,-5.1,-50,-5.7,-9.8,-3.2,-8.4,-7.4,-8.9,-5.9],[-8.5,-10.3,-10,-9,-1.4,-4.9,-3.9,-3.7,-10,-8.5,-10.2,-7.8,-7.8,-12.4,-8.5,-11.1,0,-5.5,-2.3,-4.9,12.6,10,11.1,10.5,-6,-8.3,-6.9,-7.5,-2.2,-7.4,-5.3,-5.9,-8.9,-12.5,-9.4,-11.6,-.7,-3.9,-2.3,-3,-9.1,-9.8,-9.2,-9.5,-5.6,-9,-8,-8.5,-50,-15.3,-50,-14.1,2.3,-1.4,.3,-.5,-50,-13.6,-14.3,-11.5,-5.3,-13.7,-6.1,-12.7],[-11.2,-8.1,-11.8,-8.8,-4.1,-1.9,-3.9,-3.5,-11.6,-5.9,-11.5,-7.9,-10.2,-10.1,-10.2,-11.2,-3.4,-2.6,-4.1,-3.8,10,13.1,10.7,10.6,-8.1,-5.2,-8,-6.7,-6.1,-3.7,-7.5,-5.6,-11.1,-10.3,-10.6,-11.9,-3.2,-1,-2.2,-2.8,-10.5,-8.1,-9.4,-9.5,-8.3,-6.9,-9.4,-8.8,-50,-11.3,-50,-12.8,-.6,2.2,-.3,.1,-50,-10.1,-17.5,-11.1,-8.6,-9.9,-8.6,-11.9],[-8.9,-9.4,-8.6,-8.9,-2.9,-4.5,-2.2,-3.9,-8.8,-7.5,-8.1,-7.9,-8.8,-11.6,-7.7,-11.9,-.7,-4.1,-.5,-4,11.1,10.7,13.2,10.4,-5.7,-5.8,-3.5,-6.1,-3.6,-6.5,-3.3,-5.5,-9.4,-11,-8.7,-11.2,-1.8,-2.7,.7,-3,-9.1,-8.2,-7.3,-9.4,-7.2,-8.2,-7.2,-8.2,-50,-13.2,-50,-13.3,.5,-.9,1.8,-.6,-50,-11.4,-11.1,-10.5,-6.1,-12.9,-5,-11.9],[-10.8,-9.6,-11.9,-7.7,-3.3,-3.8,-4.5,-1.6,-11.7,-7.7,-12,-6.2,-9.6,-12,-9.8,-9.4,-3.2,-4.7,-4.6,-2.4,10.5,10.6,10.4,12.6,-8.2,-7.9,-9,-4.7,-6.1,-6,-7.5,-2.9,-10.9,-12.2,-11.2,-10.9,-2.4,-2.9,-2.7,-.9,-10.4,-9.7,-10.2,-8,-8.4,-9.1,-9.3,-6.5,-50,-13.3,-50,-11,-0,-.4,-.4,2.3,-50,-10.9,-17.2,-8.3,-8.3,-12.7,-7.8,-9.3],[2.1,-8.1,1.2,-7,-8,-9.5,-7.3,-9.9,10.5,-5.5,9.3,-5.7,-9.5,-15.1,-10,-12.9,2.5,-1.2,-.1,-1,-6,-8.1,-5.7,-8.2,13.8,11.3,11.8,12.1,-6,-9.1,-9,-9.5,-8.9,-13.4,-10,-13.1,-9.9,-11.7,-9.8,-12.8,-5.9,-9.4,-6.5,-8.1,-10.7,-14,-13.3,-13.9,-50,-11.9,-50,-9.7,-8.9,-10.8,-9,-11.1,-50,-6.5,-5.3,-6.3,-10.5,-16.2,-10.4,-15.2],[0,-5,.5,-6.8,-9.1,-7.8,-7.5,-8.9,7.7,-2.4,8.2,-5.1,-11.9,-13.1,-10.4,-14.3,-.8,3,-.9,.8,-8.3,-5.2,-5.8,-7.9,11.3,15,11.2,12.8,-9.7,-5.3,-9.2,-7.8,-11.7,-10.6,-10.1,-12.2,-11.7,-8.8,-8.9,-11.8,-9.3,-5,-8,-8.2,-13.6,-11.4,-12.8,-13,-50,-7.2,-50,-8.4,-11,-7.7,-8.7,-10.2,-50,-1.5,-7.1,-4.9,-11.2,-11.6,-11.6,-15],[1.4,-7.3,2.2,-7.1,-8,-9.3,-6.4,-9.6,9.1,-5.5,10,-5.4,-10.9,-14.3,-8.4,-14,.9,-1.1,2.4,-1.3,-6.9,-8,-3.5,-9,11.8,11.2,13.4,11.4,-7.3,-8.8,-6.5,-8.5,-10,-12.5,-7.8,-12.5,-9.6,-11,-7.1,-10.7,-7.9,-8,-4.3,-9.4,-11.4,-12.3,-10.9,-12.9,-50,-11.8,-50,-11.2,-9.4,-9.8,-7.3,-10.5,-50,-6.2,-2.2,-6.7,-9.8,-15.2,-8.5,-14.9],[.2,-6.3,.1,-4.3,-8.2,-8.9,-8.5,-7,8.5,-4.1,8,-2.1,-10.5,-13.4,-10.2,-11.9,.2,1.6,-.8,3.4,-7.5,-6.7,-6.1,-4.7,12.1,12.8,11.4,14.7,-8.7,-7.4,-9.4,-5.3,-9.9,-11.8,-10.5,-10.3,-9.9,-10.1,-9.3,-9.3,-8.1,-7.2,-8,-5.2,-12,-12.1,-12.6,-10.9,-50,-7.9,-50,-5.3,-9.3,-8.8,-8.9,-7,-50,-3.6,-7.1,-1.2,-10.2,-12.7,-9.9,-11],[-10.2,-13.4,-11.8,-12.4,-6,-9.4,-7.1,-8.6,-9.8,-12.9,-10.8,-12.4,2.3,-1.4,1,-1,-3,-8,-5.1,-7.6,-2.2,-6.1,-3.6,-6.1,-6,-9.7,-7.3,-8.7,11.2,7.9,8.9,8.1,-12.1,-17.4,-13.2,-16.8,-6.3,-9.5,-7.5,-8.8,-12.7,-15.2,-13.1,-14.2,0,-3.1,-1.8,-3.1,-50,-10.7,-50,-9.3,-4.6,-8.9,-5.9,-8.3,-50,-12.8,-9.6,-10.6,9.5,-3.2,8.2,-2.8],[-13.5,-11.3,-14,-12.9,-9.3,-7.1,-8.2,-8.9,-12.7,-10.3,-11.9,-12.3,-.4,1.4,-.6,-.4,-7.2,-4.7,-6.9,-5.7,-7.4,-3.7,-6.5,-6,-9.1,-5.3,-8.8,-7.4,7.9,11.9,7.8,9.3,-15.2,-15.1,-14.6,-17.2,-9.7,-7.3,-8.2,-9.2,-15,-12.8,-14.1,-14.9,-2.8,.2,-2.9,-2.3,-50,-7.4,-50,-8.7,-9.4,-7.3,-9.4,-9.4,-50,-8,-11.9,-9.7,6.5,.5,6.4,-1.8],[-13,-14.4,-11.9,-13.9,-7.7,-9,-6.7,-8.8,-11.7,-12.7,-10.7,-13.1,-.2,-1.6,1.7,-1.6,-5.7,-8.7,-4.8,-8.1,-5.3,-7.5,-3.3,-7.5,-9,-9.2,-6.5,-9.4,8.9,7.8,10.1,7.8,-14.3,-17.7,-13,-17.8,-8,-9.4,-6.2,-9.2,-15.1,-14.9,-12.2,-14.9,-1.8,-3.2,-.8,-3.2,-50,-10.8,-50,-9.9,-7.3,-9.6,-6.4,-9.4,-50,-12.3,-8.7,-11.3,7.6,-3.3,8.7,-2.9],[-12.5,-12.9,-13.4,-10,-8.5,-9,-7.8,-6.8,-11.8,-11.3,-12.4,-10.1,-.3,-.5,-.5,1.2,-6.1,-6,-6.7,-3.5,-5.9,-5.6,-5.5,-2.9,-9.5,-7.8,-8.5,-5.3,8.1,9.3,7.8,11.8,-14.4,-15.7,-14.5,-14.6,-8.4,-8.7,-7.9,-7.1,-14.3,-13.8,-13.8,-12.3,-2.4,-2.2,-2.9,-.2,-50,-8.9,-50,-7.1,-8.1,-9.1,-8.7,-6.6,-50,-9.7,-11.4,-8,6.8,-1.8,6.9,.4],[-2.6,-6.3,-4.9,-4.9,-6.4,-9.4,-7.9,-8.6,-6.3,-7.4,-8.2,-6.6,-9.7,-14.9,-11.1,-13.9,-.2,-8.2,-2.3,-6.8,-8.9,-11.1,-9.4,-10.9,-8.9,-11.7,-10,-9.9,-12.1,-15.2,-14.3,-14.4,11.1,2.9,9.2,3.5,-3,-7,-4.3,-6.2,-2.2,-6.6,-3.7,-5.7,-6,-10.4,-8.6,-9.5,-50,-15.5,-50,-13.9,-7.8,-10.5,-8.7,-9.6,-50,-16.5,-17.1,-14.8,-12.1,-18.9,-12.4,-17.4],[-8.5,.8,-9.1,-.7,-10.1,-7.5,-9.1,-8.2,-11.4,-3.1,-11.8,-4.4,-15.5,-14.3,-14.8,-15.4,-6.6,-4.7,-7.1,-5.8,-12.5,-10.3,-11,-12.2,-13.4,-10.6,-12.5,-11.8,-17.4,-15.1,-17.7,-15.7,2.9,12.5,3.1,10.3,-7.7,-5.2,-6.2,-7.3,-5.4,-1.7,-5.4,-3.7,-11.6,-9.1,-13,-10.8,-50,-10.3,-50,-11.2,-9.8,-8.3,-9.1,-9.7,-50,-12.7,-20.6,-13.1,-16,-16.6,-17,-18.4],[-5,-6.4,-3.4,-5.6,-7.5,-9.3,-7.1,-8.8,-8.8,-7.4,-6.9,-6.9,-11.4,-15.2,-9.7,-13.7,-1.8,-7.8,-.8,-7.2,-9.4,-10.6,-8.7,-11.2,-10,-10.1,-7.8,-10.5,-13.2,-14.6,-13,-14.5,9.2,3.1,10.8,3,-4.5,-6.7,-2.7,-6.7,-5,-6.8,-2.5,-6.7,-7.5,-10.4,-7.4,-10.2,-50,-15.5,-50,-14.2,-8.9,-10.2,-8.5,-10,-50,-15.6,-15.3,-15.5,-13,-18.8,-12.6,-18.3],[-8.1,-1.1,-8.9,1.4,-8.6,-9.2,-9.4,-6.8,-11,-4.9,-11.5,-2.6,-13.7,-16.8,-14.5,-12.6,-6,-6.7,-7.2,-4.2,-11.6,-11.9,-11.2,-10.9,-13.1,-12.2,-12.5,-10.3,-16.8,-17.2,-17.8,-14.6,3.5,10.3,3,12.4,-6.9,-7.5,-6.8,-4.9,-5.4,-4.2,-5.4,-1.3,-10.8,-11.5,-12.4,-8.2,-50,-12.5,-50,-8.9,-9.2,-10,-9.4,-7.9,-50,-14.3,-19.9,-11.4,-16.2,-19.2,-15.8,-15.9],[-6.3,-7.4,-8,-6,2.8,-.7,.9,.3,-7.5,-4.4,-8.4,-3.6,-3,-7.7,-3.7,-6.2,-5.3,-10,-7.2,-8.9,-.7,-3.2,-1.8,-2.4,-9.9,-11.7,-9.6,-9.9,-6.3,-9.7,-8,-8.4,-3,-7.7,-4.5,-6.9,11.3,8.2,9.4,9.1,-1,-3.3,-1.8,-2.4,1.5,-2.1,-.4,-1.1,-50,-14.5,-50,-12.9,2.8,-0,1.4,.7,-50,-8.7,-14.1,-7.5,-5.2,-12.5,-6.5,-10.7],[-9.9,-5,-10,-6.5,-.7,2.6,-.2,.1,-10.3,-1.8,-9.9,-3.8,-6.4,-4.7,-5.8,-6.7,-8.2,-8.3,-8,-10.2,-3.9,-1,-2.7,-2.9,-11.7,-8.8,-11,-10.1,-9.5,-7.3,-9.4,-8.7,-7,-5.2,-6.7,-7.5,8.2,11.6,8.8,9.1,-3.7,-.9,-3.1,-3,-2,1.2,-2.3,-1.3,-50,-12.1,-50,-12.6,.1,2.5,.7,.6,-50,-6,-14.8,-7.5,-8.6,-9.4,-8.5,-11.2],[-7.5,-6.2,-7.2,-6.2,.9,.2,2.5,.2,-8.3,-3.5,-7.1,-3.7,-4.1,-6.3,-3.1,-6.3,-5.7,-8.9,-5.6,-8.4,-2.3,-2.2,.7,-2.7,-9.8,-8.9,-7.1,-9.3,-7.5,-8.2,-6.2,-7.9,-4.3,-6.2,-2.7,-6.8,9.4,8.8,12.1,8.8,-2.1,-2,.1,-2.4,0,-1.1,1.3,-.8,-50,-11.9,-50,-12.6,1.2,.7,3.5,.8,-50,-7.1,-12.4,-7.1,-7.1,-10.6,-5,-10.6],[-9,-6.5,-10,-4.8,.1,-.1,-.3,2.4,-9.9,-3.5,-10.6,-2,-5.4,-6.6,-5.6,-4.4,-7.6,-9.9,-8.5,-8.2,-3,-2.8,-3,-.9,-12.8,-11.8,-10.7,-9.3,-8.8,-9.2,-9.2,-7.1,-6.2,-7.3,-6.7,-4.9,9.1,9.1,8.8,11.2,-3.1,-3,-3.3,-1,-1.1,-1.4,-2,1.2,-50,-12.8,-50,-10.9,.8,.5,.7,2.3,-50,-7.5,-16.5,-5.9,-7.8,-11.1,-7.8,-9],[-7.1,-5.6,-9.1,-5.1,-5.9,-8,-6.9,-7.4,-1.9,-1.6,-4.7,-1.4,-9.6,-14.6,-10.4,-13,-6.7,-10.8,-9.4,-9.9,-9.1,-10.5,-9.1,-10.4,-5.9,-9.3,-7.9,-8.1,-12.7,-15,-15.1,-14.3,-2.2,-5.4,-5,-5.4,-1,-3.7,-2.1,-3.1,12.8,9.6,11.1,10.1,-4.8,-9.4,-8.1,-8.6,-50,-18.3,-50,-15.4,-5.9,-7.5,-6.6,-7.1,-50,-9.5,-11.7,-8.4,-12.5,-17.3,-13.2,-15.4],[-10.2,-1.6,-10.2,-3.2,-7.3,-4.6,-6.5,-6.2,-6.7,3,-6.8,.8,-11.9,-10.8,-11.5,-12.2,-9.6,-7.1,-9.7,-8.4,-9.8,-8.1,-8.2,-9.7,-9.4,-5,-8,-7.2,-15.2,-12.8,-14.9,-13.8,-6.6,-1.7,-6.8,-4.2,-3.3,-.9,-2,-3,9.6,12.8,9.7,10.5,-8.5,-5.6,-9.3,-7.8,-50,-12.7,-50,-13.8,-6.8,-5.1,-5.3,-6.5,-50,-4.1,-12.8,-5.8,-14.4,-14.1,-13.6,-14.8],[-8.2,-4.7,-7.1,-5,-6.5,-7.7,-5.5,-6.9,-4.1,-.8,-1.2,-.9,-10.5,-12.8,-8.2,-13,-7.5,-10,-7.2,-9.7,-9.2,-9.4,-7.3,-10.2,-6.5,-8,-4.3,-8,-13.1,-14.1,-12.2,-13.8,-3.7,-5.4,-2.5,-5.4,-1.8,-3.1,.1,-3.3,11.1,9.7,12.9,9.8,-5.5,-8.1,-5.4,-7.8,-50,-16.4,-50,-14.8,-5.9,-7.1,-4.7,-7.2,-50,-8.4,-6.4,-8.1,-12.1,-16.2,-10.3,-15.8],[-9.2,-3,-9.9,-1.2,-6.5,-6.1,-6.8,-4.4,-6.4,.9,-7,3,-11.8,-13,-11.1,-10.4,-9.3,-9.2,-9.8,-6.4,-9.5,-9.5,-9.4,-8,-8.1,-8.2,-9.4,-5.2,-14.2,-14.9,-14.9,-12.3,-5.7,-3.7,-6.7,-1.3,-2.4,-3,-2.4,-1,10.1,10.5,9.8,13.1,-7.2,-8,-8.4,-5,-50,-14.7,-50,-11.4,-6.3,-6.7,-5.8,-5,-50,-6.1,-13.4,-3.6,-13,-16,-13.7,-13.3],[-8.2,-10.8,-10.1,-9.8,-.4,-3.6,-1.7,-2.9,-7.9,-8.4,-9.8,-8.2,6.2,2.3,.6,2.9,-7.1,-11.6,-9.2,-11.1,-5.6,-8.3,-7.2,-8.4,-10.7,-13.6,-11.4,-12,0,-2.8,-1.8,-2.4,-6,-11.6,-7.5,-10.8,1.5,-2,0,-1.1,-4.8,-8.5,-5.5,-7.2,11.9,8.6,10,9,-50,-14.2,-50,-12.8,-4.1,-7.4,-5.7,-6.5,-50,-11,-14.3,-9.9,1.4,-7.9,-.7,-6.8],[-12.5,-8.7,-13,-9.9,-3.9,-1,-3.4,-2.9,-12.5,-6.3,-11.6,-8.1,3.3,6,-1.6,3.8,-10.5,-10.1,-11.1,-11.1,-9,-6.9,-8.2,-9.1,-14,-11.4,-12.3,-12.1,-3.1,.2,-3.2,-2.2,-10.4,-9.1,-10.4,-11.5,-2.1,1.2,-1.1,-1.4,-9.4,-5.6,-8.1,-8,8.6,12.4,8.6,9.5,-50,-10.4,-50,-11.6,-7.2,-5.7,-7.5,-7.4,-50,-8.6,-15.7,-9.7,-3,-3.7,-3.2,-5.9],[-11.1,-11.9,-10.6,-11.3,-2.6,-4.1,-1.7,-3.5,-11.4,-9.6,-9.6,-9.2,3.7,2.5,1.6,2.5,-9.6,-12.3,-9.5,-11.8,-8,-9.4,-7.2,-9.3,-13.3,-12.8,-10.9,-12.6,-1.8,-2.9,-.8,-2.9,-8.6,-13,-7.4,-12.4,-.4,-2.3,1.3,-2,-8.1,-9.3,-5.4,-8.4,10,8.6,11.4,8.9,-50,-13.7,-50,-13.2,-6.1,-8.1,-5.5,-7.5,-50,-11.3,-12.7,-10.1,-1.6,-7.8,-.3,-7.2],[-11.4,-10,-12.7,-8.2,-3.1,-3.1,-2.8,-.9,-11.7,-7.3,-12.1,-5.8,3.6,3.6,-1.1,5.8,-9.4,-11.9,-10.7,-10,-8.5,-8.8,-8.2,-6.5,-13.9,-13,-12.9,-10.9,-3.1,-2.3,-3.2,-.2,-9.5,-10.8,-10.2,-8.2,-1.1,-1.3,-.8,1.2,-8.6,-7.8,-7.8,-5,9,9.5,8.9,12,-50,-13,-50,-10.3,-6.2,-7,-7.1,-5.4,-50,-9.3,-14,-8.2,-2.4,-6.3,-2.4,-3.9],[-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,33.3,-50,30.6,-50,-50,-50,-50,-50,29.2,-50,-50,-50,-50,-50,-50,-50],[-14.8,-6.2,-14.9,-7.6,-14.6,-11.6,-13,-12.2,-14,-9,-14.1,-10.1,-13.6,-11.2,-12.4,-12.5,-8.1,2.2,-8.7,.4,-15.3,-11.3,-13.2,-13.3,-11.9,-7.2,-11.8,-7.9,-10.7,-7.4,-10.8,-8.9,-15.5,-10.3,-15.5,-12.5,-14.5,-12.1,-11.9,-12.8,-18.3,-12.7,-16.4,-14.7,-14.2,-10.4,-13.7,-13,-50,15.1,-50,13.3,-9.9,-5.8,-8.9,-7.6,-50,-1.5,-7.8,-3,-8.1,3.6,-9.4,2],[-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,30.6,-50,35.2,-50,-50,-50,-50,-50,28.5,-50,-50,-50,-50,-50,-50,-50],[-13.8,-7.5,-14.4,-5.1,-12.6,-11.6,-11.5,-10.1,-13.2,-9.7,-12.7,-7.4,-11.9,-11.9,-11.5,-10.2,-7.2,.9,-8.6,2.6,-14.1,-12.8,-13.3,-11,-9.7,-8.4,-11.2,-5.3,-9.3,-8.7,-9.9,-7.1,-13.9,-11.2,-14.2,-8.9,-12.9,-12.6,-12.6,-10.9,-15.4,-13.8,-14.8,-11.4,-12.8,-11.6,-13.2,-10.3,-50,13.3,-50,15.2,-8.6,-7,-8.4,-4.8,-50,-3,-7.1,-.1,-7.3,2.3,-8.7,3.9],[-7.3,-6.3,-8.9,-5.5,2.9,.2,1.5,1.2,-8.5,-2.3,-10,-1.7,-5.6,-10.5,-5.5,-9.6,-4.3,-7.9,-6.1,-7.2,2.3,-.6,.5,-0,-8.9,-11,-9.4,-9.3,-4.6,-9.4,-7.3,-8.1,-7.8,-9.8,-8.9,-9.2,2.8,.1,1.2,.8,-5.9,-6.8,-5.9,-6.3,-4.1,-7.2,-6.1,-6.2,-50,-9.9,-50,-8.6,12.5,9.4,11,9.8,-50,-4.8,-8.7,-3.5,-0,-8.6,-2.1,-7],[-10.1,-4.3,-10.8,-5.8,.1,2.3,.7,.6,-10.4,-.2,-10.8,-2,-8.8,-9.2,-8,-9.7,-6.8,-5.9,-7.5,-7,-1.4,2.2,-.9,-.4,-10.8,-7.7,-9.8,-8.8,-8.9,-7.3,-9.6,-9.1,-10.5,-8.3,-10.2,-10,-0,2.5,.7,.5,-7.5,-5.1,-7.1,-6.7,-7.4,-5.7,-8.1,-7,-50,-5.8,-50,-7,9.4,12.7,10.1,10,-50,-1.5,-11.3,-3.3,-5.4,-4.2,-5.6,-6.8],[-8.4,-6.2,-8.9,-5.9,1.8,.4,2.7,1.2,-9.1,-1.2,-8.8,-1.5,-7.2,-10.5,-4.9,-9.6,-5.7,-7.4,-5.5,-7.4,.3,-.3,1.8,-.4,-9,-8.7,-7.3,-8.9,-5.9,-9.4,-6.4,-8.7,-8.7,-9.1,-8.5,-9.4,1.4,.7,3.5,.7,-6.6,-5.3,-4.7,-5.8,-5.7,-7.5,-5.5,-7.1,-50,-8.9,-50,-8.4,11,10.1,13.2,10.2,-50,-4.2,-6.1,-3.6,-3.5,-8.4,-1.2,-6.8],[-9.1,-5.4,-10.4,-4.2,1,.5,.6,2.4,-9.6,-1.5,-10.5,-.5,-8.9,-10.5,-7.2,-8.3,-6.3,-6.9,-7.7,-5.1,-.5,.1,-.6,2.3,-11.1,-10.2,-10.5,-7,-8.3,-9.4,-9.4,-6.6,-9.6,-9.7,-10,-7.9,.7,.6,.8,2.3,-7.1,-6.5,-7.2,-5,-6.5,-7.4,-7.5,-5.4,-50,-7.6,-50,-4.8,9.8,10,10.2,12.1,-50,-3.1,-11.4,-.7,-4.6,-6.6,-4.9,-3.9],[-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,29.2,-50,28.5,-50,-50,-50,-50,-50,33.3,-50,-50,-50,-50,-50,-50,-50],[-13,-7,-13.1,-8.3,-9.2,-6.5,-8.9,-7.6,-9.8,-.7,-9.2,-2.1,-12.4,-10.3,-12.4,-11.6,-9.5,-4.6,-10.4,-5.7,-13.6,-10.1,-11.4,-10.9,-6.5,-1.5,-6.2,-3.6,-12.8,-8,-12.3,-9.7,-16.5,-12.7,-15.6,-14.3,-8.7,-6,-7.1,-7.5,-9.5,-4.1,-8.4,-6.1,-11,-8.6,-11.3,-9.3,-50,-1.5,-50,-3,-4.8,-1.5,-4.2,-3.1,-50,16.4,-5.1,14.2,-10.1,-4.3,-10,-5.4],[-13.5,-16.3,-11.8,-15.5,-13.6,-15.3,-12.1,-16.1,-7.7,-13.3,-4.2,-12.6,-14.1,-16.2,-10.3,-15.4,-9.6,-11.6,-7.7,-9.8,-14.3,-17.5,-11.1,-17.2,-5.3,-7.1,-2.2,-7.1,-9.6,-11.9,-8.7,-11.4,-17.1,-20.6,-15.3,-19.9,-14.1,-14.8,-12.4,-16.5,-11.7,-12.8,-6.4,-13.4,-14.3,-15.7,-12.7,-14,-50,-7.8,-50,-7.1,-8.7,-11.3,-6.1,-11.4,-50,-5.1,18.6,-4.8,-8.6,-8.1,-4.5,-7.3],[-12.4,-8.2,-13,-5.9,-7.7,-7.8,-7.4,-5.8,-8.8,-2,-9.3,-.4,-11.6,-11.3,-11.6,-9.4,-8.9,-5.6,-10,-3.2,-11.5,-11.1,-10.5,-8.3,-6.3,-4.9,-6.7,-1.2,-10.6,-9.7,-11.3,-8,-14.8,-13.1,-15.5,-11.4,-7.5,-7.5,-7.1,-5.9,-8.4,-5.8,-8.1,-3.6,-9.9,-9.7,-10.1,-8.2,-50,-3,-50,-.1,-3.5,-3.3,-3.6,-.7,-50,14.2,-4.8,16.4,-8.9,-5.8,-8.9,-3.4],[-10.7,-13.2,-12.4,-11.6,-4.8,-8.4,-6.1,-7.2,-10.3,-11.8,-11,-11.6,2.8,-1.7,.7,-1.1,-6.2,-9.7,-7.3,-8.4,-5.3,-8.6,-6.1,-8.3,-10.5,-11.2,-9.8,-10.2,9.5,6.5,7.6,6.8,-12.1,-16,-13,-16.2,-5.2,-8.6,-7.1,-7.8,-12.5,-14.4,-12.1,-13,1.4,-3,-1.6,-2.4,-50,-8.1,-50,-7.3,-0,-5.4,-3.5,-4.6,-50,-10.1,-8.6,-8.9,13.2,-.9,9.7,-.3],[-18.1,-12.3,-19.4,-14.2,-12.2,-9.5,-11.5,-10.8,-17.9,-11.9,-18.2,-13.9,-6.4,-3.7,-6.8,-5.4,-12.8,-5.9,-13.6,-7.4,-13.7,-9.9,-12.9,-12.7,-16.2,-11.6,-15.2,-12.7,-3.2,.5,-3.3,-1.8,-18.9,-16.6,-18.8,-19.2,-12.5,-9.4,-10.6,-11.1,-17.3,-14.1,-16.2,-16,-7.9,-3.7,-7.8,-6.3,-50,3.6,-50,2.3,-8.6,-4.2,-8.4,-6.6,-50,-4.3,-8.1,-5.8,-.9,14.2,-1.8,11.6],[-11.8,-13.1,-11.5,-12,-6.2,-8.3,-5.4,-7.4,-11.8,-12.3,-11.1,-11.4,.5,-2.5,2.4,-1.6,-6.8,-9.9,-6.4,-8.9,-6.1,-8.6,-5,-7.8,-10.4,-11.6,-8.5,-9.9,8.2,6.4,8.7,6.9,-12.4,-17,-12.6,-15.8,-6.5,-8.5,-5,-7.8,-13.2,-13.6,-10.3,-13.7,-.7,-3.2,-.3,-2.4,-50,-9.4,-50,-8.7,-2.1,-5.6,-1.2,-4.9,-50,-10,-4.5,-8.9,9.7,-1.8,11.3,-.9],[-17.2,-13.3,-17.8,-11.6,-11,-11.1,-10.4,-9,-16,-12.7,-16.1,-11.1,-5.2,-5.4,-6,-3.3,-11.8,-7.3,-13.3,-5.9,-12.7,-11.9,-11.9,-9.3,-15.2,-15,-14.9,-11,-2.8,-1.8,-2.9,.4,-17.4,-18.4,-18.3,-15.9,-10.7,-11.2,-10.6,-9,-15.4,-14.8,-15.8,-13.3,-6.8,-5.9,-7.2,-3.9,-50,2,-50,3.9,-7,-6.8,-6.8,-3.9,-50,-5.4,-7.3,-3.4,-.3,11.6,-.9,14.1]];TRANS=[[5,0,0,4],[0,5,4,0],[0,4,5,0],[4,0,0,5]];CONBLO={A:0,R:1,N:2,D:3,C:4,Q:5,E:6,G:7,H:8,I:9,L:10,K:11,M:12,F:13,P:14,S:15,T:16,W:17,Y:18,V:19,B:20,Z:21,X:22,"*":23};CONNUCL={A:0,T:1,C:2,G:3};CONSCHN={AAA:0,AAC:1,AAG:2,AAT:3,ACA:4,ACC:5,ACG:6,ACT:7,AGA:8,AGC:9,AGG:10,AGT:11,ATA:12,ATC:13,ATG:14,ATT:15,CAA:16,CAC:17,CAG:18,CAT:19,CCA:20,CCC:21,CCG:22,CCT:23,CGA:24,CGC:25,CGG:26,CGT:27,CTA:28,CTC:29,CTG:30,CTT:31,GAA:32,GAC:33,GAG:34,GAT:35,GCA:36,GCC:37,GCG:38,GCT:39,GGA:40,GGC:41,GGG:42,GGT:43,GTA:44,GTC:45,GTG:46,GTT:47,TAA:48,TAC:49,TAG:50,TAT:51,TCA:52,TCC:53,TCG:54,TCT:55,TGA:56,TGC:57,TGG:58,TGT:59,TTA:60,TTC:61,TTG:62,TTT:63};fillNeedleman(){for(let e=0;e<=this.len1;e++)this.dpGrid[e][0].value=-e*this.gap,this.dpGrid[e][0].parentI=e-1,this.dpGrid[e][0].parentJ=0;for(let e=1;e<=this.len2;e++)this.dpGrid[0][e].value=-e*this.gap,this.dpGrid[0][e].parentI=0,this.dpGrid[0][e].parentJ=e-1}fillOne(e,t){this.dpGrid[e][t].value=Math.max(this.dpGrid[e-1][t-1].value+this.scores[e-1][t-1],Math.max(this.dpGrid[e-1][t].value-this.gap,this.dpGrid[e][t-1].value-this.gap)),this.dpGrid[e][t].value==this.dpGrid[e-1][t-1].value+this.scores[e-1][t-1]?(this.dpGrid[e][t].parentI=e-1,this.dpGrid[e][t].parentJ=t-1):this.dpGrid[e][t].value==this.dpGrid[e-1][t].value-this.gap?(this.dpGrid[e][t].parentI=e-1,this.dpGrid[e][t].parentJ=t):(this.dpGrid[e][t].parentI=e,this.dpGrid[e][t].parentJ=t-1)}gridFromName(e){switch(e){case"BLOSUM45":this.alignGrid=this.BLOSUM45,this.connections=this.CONBLO,this.step=1;break;case"BLOSUM50":this.alignGrid=this.BLOSUM50,this.connections=this.CONBLO,this.step=1;break;case"BLOSUM62":this.alignGrid=this.BLOSUM62,this.connections=this.CONBLO,this.step=1;break;case"BLOSUM80":this.alignGrid=this.BLOSUM80,this.connections=this.CONBLO,this.step=1;break;case"BLOSUM90":this.alignGrid=this.BLOSUM90,this.connections=this.CONBLO,this.step=1;break;case"PAM30":this.alignGrid=this.PAM30,this.connections=this.CONBLO,this.step=1;break;case"PAM70":this.alignGrid=this.PAM70,this.connections=this.CONBLO,this.step=1;break;case"PAM250":this.alignGrid=this.PAM250,this.connections=this.CONBLO,this.step=1;break;case"NUCLEOTIDES":this.alignGrid=this.NUCLEOTIDES,this.connections=this.CONNUCL,this.step=1;break;case"TRANS":this.alignGrid=this.TRANS,this.connections=this.CONNUCL,this.step=1;break;case"SCHNEIDER":this.alignGrid=this.SCHNEIDER,this.connections=this.CONSCHN,this.step=3}this.fillScores()}constructResult(e,t){let n="",i="",o="";const s=this.dpGrid[e][t].value;for(let e=0;e<this.step;e++)o+="|";for(;e>0||t>0;){this.dpGrid[e][t].parentI==e?(n=o+n,i=this.seq2.substr((t-1)*this.step,this.step)+i):this.dpGrid[e][t].parentJ==t?(i=o+i,n=this.seq1.substr((e-1)*this.step,this.step)+n):(n=e-1>=0?this.seq1.substr((e-1)*this.step,this.step)+n:o+n,i=t-1>=0?this.seq2.substr((t-1)*this.step,this.step)+i:o+i);const s=e;e=this.dpGrid[e][t].parentI,t=this.dpGrid[s][t].parentJ}return new lt(n,i,s)}fillScores(){this.scores=[];for(let e=0;e<this.len1;e++){this.scores.push([]);for(let t=0;t<this.len2;t++)this.scores[e].push(this.alignGrid[this.connections[this.seq1.substr(e*this.step,this.step)]][this.connections[this.seq2.substr(t*this.step,this.step)]])}}typeRec(){if(/[ATGC]*/.test(this.seq1)&&/[ATGC]*/.test(this.seq2))return"NUCLEOTIDES";if(/[ARNDCQEGHILKMFPSTWYVBZX*]*/.test(this.seq1)&&/[ARNDCQEGHILKMFPSTWYVBZX*]*/.test(this.seq2))return"BLOSUM62";throw Error("Can't recognize sequence type")}needlemanWunsch(){this.dpGrid=[];for(let e=0;e<this.len1+1;e++){const e=[];for(let t=0;t<this.len2+1;t++)e.push(new at);this.dpGrid.push(e)}this.fillNeedleman();for(let e=1;e<=this.len1;e++)for(let t=1;t<=this.len2;t++)this.fillOne(e,t);return this.constructResult(this.len1,this.len2)}smithWaterman(){this.dpGrid=[];for(let e=0;e<this.len1+1;e++){const e=[];for(let t=0;t<this.len2+1;t++)e.push(new at);this.dpGrid.push(e)}let e=0,t=0,n=0;for(let i=1;i<=this.len1;i++)for(let o=1;o<=this.len2;o++)this.fillOne(i,o),this.dpGrid[i][o].value<=0?(this.dpGrid[i][o].value=0,this.dpGrid[i][o].parentI=0,this.dpGrid[i][o].parentJ=0):0==this.dpGrid[this.dpGrid[i][o].parentI][this.dpGrid[i][o].parentJ].value&&(this.dpGrid[i][o].parentI=0,this.dpGrid[i][o].parentJ=0),this.dpGrid[i][o].value>e&&(e=this.dpGrid[i][o].value,t=i,n=o);return this.constructResult(t,n)}setSequences(e,t){this.seq1=e,this.seq2=t,this.len1=this.seq1.length/this.step,this.len2=this.seq2.length/this.step,this.fillScores()}setGap(e){this.gap=e}setMethod(e=""){"AUTO"==e&&(e=this.typeRec()),this.gridFromName(e)}constructor(e,t,n,i=""){this.setMethod(i),this.setSequences(e,t),this.setGap(n)}}async function ut(e,t,n="Morgan",i=1,o=.6){const s=e.length,a=Uo.seqHelper.getSeqHandler(e),l=Array(s);let c=1;const u=new Map,h=e.categories,d=e.getRawData();for(let t=0;t<s;t++){if(null==h[d[t]]||e.isNone(t)){l[t]=null;continue}l[t]="";const n=a.getSplitted(t);for(let e=0;e<n.length;e++){const i=n.getCanonical(e);u.has(i)||(u.set(i,String.fromCharCode(c)),c++),l[t]+=u.get(i)}}let m={};if(t===ce.Z.MONOMER_CHEMICAL_DISTANCE||t===ce.Z.NEEDLEMANN_WUNSCH){const e=Array.from(u.keys()),s=await async function(e,t="Morgan"){const n=(await(0,ye.pj)()).getMonomerLib(),i=new Array(e.length).fill(0).map(()=>new Array(e.length).fill(0)),o={},s=e.map(e=>n.getMonomer("PEPTIDE",e)?.molfile||n.getMonomer("PEPTIDE",e)?.smiles||""),a=r.Func.find({package:"Chem",name:"getFingerprints"})[0];if(!a)return console.warn('Function "Chem:getFingerprints" is not found in chem package. falling back to Morgan fingerprints'),await be(e);const l=r.Column.fromStrings("smiles",s),c=(r.DataFrame.fromColumns([l]),(await a.apply({col:l,fingerprintType:t}))?.entries);if(!c)return console.warn(`${t} Fingerprints could not be calculated for monomers from chem package.\n falling back to Morgan fingerprints`),await be(e);for(let t=0;t<c.length;++t)if(i[t][t]=1,o[e[t]]=t,c[t])for(let e=t+1;e<c.length;++e)c[e]&&(i[t][e]=i[e][t]=(0,$.$1)(c[t],c[e]));return{scoringMatrix:i,alphabetIndexes:o}}(e,n),a={};Object.entries(s.alphabetIndexes).forEach(([e,t])=>{a[u.get(e)]=t});const c=l.reduce((e,t)=>Math.max(e,t?.length||0),0);m={scoringMatrix:s.scoringMatrix,alphabetIndexes:a,maxLength:c},t===ce.Z.NEEDLEMANN_WUNSCH&&(m.gapOpen=i,m.gapExtend=o)}return{seqList:l,options:m}}var ht=n(4954);function dt(e){const t=s.divH([],{style:{gap:"10px"}}),n=s.divV([s.divText(e.seqCol.name),s.divText(e.activityCol.name)]);return n.style.fontWeight="bold",n.style.display="flex",n.style.justifyContent="space-between",t.append(n),e.points.forEach(n=>{const i=s.divText(e.activityCol.get(n).toFixed(2));i.style.display="flex",i.style.justifyContent="left",i.style.paddingLeft="30px",t.append(s.divV([s.divText(e.seqCol.get(n)),i]))}),t}function mt(e){const t=s.div();t.append(s.divText(e.seqCol.name,{style:{fontWeight:"bold"}}));const n=new Array(2);e.points.forEach((t,i)=>{n[i]=e.activityCol.get(t)});const i={},o=Uo.seqHelper.getSeqHandler(e.seqCol),r=o.defaultBiotype,a=gt(o.getSplitted(e.points[0]),o.getSplitted(e.points[1]),r,i);return t.append(s.div(a,{style:{width:"300px",overflow:"scroll"}})),t.append(ft(i)),t.append(pt("Activity delta",Math.abs(n[0]-n[1]))),t.append(pt("Cliff",e.sali)),t}function pt(e,t){return s.divH([s.divText(`${e}: `,{style:{fontWeight:"bold",paddingRight:"5px"}}),s.divText(t.toFixed(2))],{style:{paddingTop:"10px"}})}function gt(e,t,n,i){const o=document.createElement("canvas"),s=o.getContext("2d");o.height=30;const r=Uo.monomerLib;return Ke(s,0,0,0,30,ee().count(0).take(e.length).map(t=>e.getCanonical(t)).toArray(),ee().count(0).take(t.length).map(e=>t.getCanonical(e)).toArray(),n,r,!0,i),o}function ft(e){const t=s.div();if(Object.keys(e).length>0){const n=s.divV([]);n.append(s.divH([s.divText("Pos",{style:{fontWeight:"bold",width:"30px",borderBottom:"1px solid"}}),s.divText("Difference",{style:{fontWeight:"bold",borderBottom:"1px solid"}})]));for(const t of Object.keys(e))e[t].style.borderBottom="1px solid lightgray",n.append(s.divH([s.divText((parseInt(t)+1).toString(),{style:{width:"30px",borderBottom:"1px solid lightgray"}}),e[t]]));t.append(n)}return t}function yt(e,t){if(!e.col("seq_diff")){const n=r.Column.string("seq_diff",e.rowCount).init(n=>`${e.get(t[0],n)}#${e.get(t[1],n)}`);n.semType="MacromoleculeDifference",n.meta.units=e.col(t[0]).meta.units,n.setTag(ue.gp.separator,e.col(t[0]).getTag(ue.gp.separator)),e.columns.add(n)}const n=e.plot.grid();return n.col(t[0]).visible=!1,n.col(t[1]).visible=!1,n}class bt extends r.JsViewer{constructor(e,t){super(),this.name="",this.semType="",this.initialized=!1,this.gridSelect=!1,this.maxLimit=100,this.recomputeOnCurrentRowChange=!0,this.skipRecomputingProperies=[],this.debounceTimer=null,this.computeRequested=!1,this.renderPromise=Promise.resolve(),this.limit=this.int("limit",10,{min:1,max:this.maxLimit}),this.targetColumnName=this.string("targetColumnName",null,{...t?{semType:t}:{},nullable:!1}),this.name=e,this.semType=t}init(){this.initialized=!0}detach(){this.subs.forEach(e=>e.unsubscribe())}async onTableAttached(){if(this.init(),this.dataFrame){this.subs.push(r.debounce(this.dataFrame.onRowsRemoved,50).subscribe(e=>this.render(!0)));const e="diversity"!==this.name;this.subs.push(r.debounce(this.dataFrame.onCurrentRowChanged,50).subscribe(t=>{this.gridSelect||this.render(e)})),this.subs.push(r.debounce(this.dataFrame.selection.onChanged,50).subscribe(e=>this.render(!1))),this.subs.push(r.debounce(s.onSizeChanged(this.root),50).subscribe(e=>this.render(!1))),this.targetColumnName??(this.targetColumnName=this.dataFrame.columns.bySemType(this.semType).name),this.targetColumn=this.dataFrame.col(this.targetColumnName),this.getProperty("limit").fromOptions({min:1,max:this.maxLimit})}this.render()}onPropertyChanged(e){if(super.onPropertyChanged(e),this.initialized){if("targetColumnName"===e.name){const t=this.dataFrame.col(e.get(this));t.semType===this.semType&&(this.targetColumn=t)}this.debouncedRender()}}debouncedRender(e=!0){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.render(e),this.debounceTimer=null},100)}render(e=!0){this.renderPromise=this.renderPromise.then(async()=>{this.computeRequested=this.computeRequested||e,await this.renderInt(e)})}async renderInt(e){}beforeRender(){return!(!this.initialized||!this.targetColumnName||this.dataFrame&&this.targetColumnName&&this.dataFrame.col(this.targetColumnName).semType!==this.semType&&(o.shell.error(`${this.targetColumnName} is not ${this.semType} type`),1))}}class wt extends bt{distanceMetric;fingerprint;gapOpen;gapExtend;metricsProperties=["distanceMetric","fingerprint","gapOpen","gapExtend"];fingerprintChoices=["Morgan","RDKit","Pattern","AtomPair","MACCS","TopologicalTorsion"];distanceFunctionChoices=[ce.Z.NEEDLEMANN_WUNSCH,ce.Z.HAMMING,ce.Z.LEVENSHTEIN,ce.Z.MONOMER_CHEMICAL_DISTANCE];tags=[r.TAGS.UNITS,ue.gp.aligned,ue.gp.separator,ue.gp.alphabet,"cell.renderer"];preComputeDistanceMatrix=!1;requiresSampling=!1;constructor(e,t){super(e,t),this.distanceMetric=this.string("distanceMetric",ce.Z.HAMMING,{choices:this.distanceFunctionChoices}),this.fingerprint=this.string("fingerprint",this.fingerprintChoices[0],{choices:this.fingerprintChoices}),this.gapOpen=this.float("gapOpen",1),this.gapExtend=this.float("gapExtend",.6)}async onTableAttached(){if(super.onTableAttached(),this.dataFrame){const e=this.dataFrame.rowCount;this.preComputeDistanceMatrix=e<=1e4,this.requiresSampling=e>1e4}}needsGapPenalties(){return this.distanceMetric===ce.Z.NEEDLEMANN_WUNSCH}needsFingerprint(){return this.distanceMetric===ce.Z.MONOMER_CHEMICAL_DISTANCE||this.distanceMetric===ce.Z.NEEDLEMANN_WUNSCH}}const vt={gapPenalty:1,matchScore:1,gapSymbol:pe.b9[pe.Hi.FASTA],localAlignment:!1};class Ct extends wt{seqHelper;cutoff;hotSearch;similarColumnLabel;sketchedMolecule="";curIdx=0;molCol=null;idxs=null;scores=null;gridSelect=!1;targetMoleculeIdx=0;computeCompleted=new c.Subject;distanceMatrixComputed=!1;mmDistanceMatrix;knn;kPrevNeighbors=0;demo;analysisGrid;subInited=!1;lastDistanceMetric="";lastFingerprint="";lastGapOpen=0;lastGapExtend=0;constructor(e,t){super("similarity",r.SEMTYPE.MACROMOLECULE),this.seqHelper=e,this.cutoff=this.float("cutoff",.01,{min:0,max:1}),this.hotSearch=this.bool("hotSearch",!0),this.similarColumnLabel=this.string("similarColumnLabel",null),this.demo=t}init(){this.hotSearch=!0,this.initialized=!0}async renderInt(e){if(this.beforeRender()&&this.targetColumn){this.curIdx=-1==(this.dataFrame?.currentRowIdx??-1)?0:this.dataFrame.currentRowIdx;const t=this.lastDistanceMetric!==this.distanceMetric||this.lastFingerprint!==this.fingerprint||this.lastGapOpen!==this.gapOpen||this.lastGapExtend!==this.gapExtend;if(e&&!this.gridSelect||t){this.targetMoleculeIdx=(this.dataFrame?.currentRowIdx??-1)<0?0:this.dataFrame.currentRowIdx,await this.computeByMM();const e=null!=this.similarColumnLabel?this.similarColumnLabel:`similar (${this.targetColumn})`;this.molCol=r.Column.string(e,this.idxs.length).init(e=>this.targetColumn?.get(this.idxs?.get(e))),this.molCol.semType=r.SEMTYPE.MACROMOLECULE,this.tags.forEach(e=>this.molCol.setTag(e,this.targetColumn.getTag(e)));const t=r.DataFrame.fromColumns([this.idxs,this.molCol,this.scores]);await t.meta.detectSemanticTypes(),await o.data.detectSemanticTypes(t),this.molCol.temp["reference-sequence"]=this.targetColumn.get(this.targetMoleculeIdx),this.molCol.temp[".mm.cellRenderer.maxMonomerLength"]=4;let n=null;t.onCurrentRowChanged.subscribe(e=>{n&&clearTimeout(n),(t?.currentRowIdx??-1)<0||(this.dataFrame&&(this.dataFrame.currentRowIdx=t.col("indexes").get(t.currentRowIdx)),n=setTimeout(()=>{this.createPropertyPanel(t)},300),this.gridSelect=!0)}),this.analysisGrid?(this.analysisGrid.dataFrame=t,this.analysisGrid.invalidate()):(this.analysisGrid=t.plot.grid(),(0,Ne.Ku)(this.root,this.analysisGrid.root)),this.analysisGrid.col("indexes").visible=!1,(0,Ne.Kd)(this.analysisGrid,this.molCol.name,450,30,!0);const i=this.idxs?.getRawData().findIndex(e=>e==this.targetMoleculeIdx);this.analysisGrid.cell("score",i).cell.value=null;const s=o.shell.tv;this.subInited||(s.grid.root.addEventListener("click",e=>{this.gridSelect=!1}),this.subInited=!0),this.computeCompleted.next(!0)}}}async computeByMM(){const e=this.targetColumn.length,t=Math.min(this.limit,e-1);if(!this.knn||this.kPrevNeighbors!==t||this.lastDistanceMetric!==this.distanceMetric||this.lastFingerprint!==this.fingerprint||this.lastGapOpen!==this.gapOpen||this.lastGapExtend!==this.gapExtend){const e=this.distanceMetric,n=await ut(this.targetColumn,e,this.fingerprint,this.gapOpen,this.gapExtend),i=n.seqList,o=n.options;this.lastDistanceMetric=this.distanceMetric,this.lastFingerprint=this.fingerprint,this.lastGapOpen=this.gapOpen,this.lastGapExtend=this.gapExtend,this.kPrevNeighbors=t,this.knn=await(new F).getKNN(i,e,t,o)}const n=new Array(t).fill(0).map((e,t)=>({idx:this.knn.knnIndexes[this.targetMoleculeIdx][t],score:1-this.knn.knnDistances[this.targetMoleculeIdx][t]}));n.sort((e,t)=>t.score-e.score),n.unshift({idx:this.targetMoleculeIdx,score:r.FLOAT_NULL}),this.idxs=r.Column.int("indexes",t+1).init(e=>n[e].idx),this.scores=r.Column.float("score",t+1).init(e=>n[e].score)}createPropertyPanel(e){const t=s.div(),n={},i=this.molCol?.name,r=e.col(i),a=this.seqHelper.getSeqHandler(this.targetColumn),l=this.seqHelper.getSeqHandler(r),c=a.getSplitted(this.targetMoleculeIdx),u=l.getSplitted(e.currentRowIdx),h=function(e,t,n={}){const i={...vt,...n};function o(e,t){return e===t?i.matchScore:-i.matchScore}const s=e.length,r=t.length,a=Array(s+1).fill(0).map(()=>Array(r+1).fill(0));let l=-9999,c=[1,1];for(let n=1;n<s+1;n++)for(let s=1;s<r+1;s++)a[n][s]=Math.max(0,a[n-1][s-1]+o(e.getCanonical(n-1),t.getCanonical(s-1)),a[n-1][s]-i.gapPenalty,a[n][s-1]-i.gapPenalty),a[n][s]>=l&&(l=a[n][s],c=[n,s]);let u=i.localAlignment?c[0]:s,h=i.localAlignment?c[1]:r,d=new Array(0),m=new Array(0);for(;u>0&&h>0;){const n=Math.max(a[u-1][h-1],a[u-1][h],a[u][h-1]);a[u][h]==a[u-1][h-1]+i.matchScore&&n==a[u-1][h-1]?(d.push(e.getCanonical(u-1)),m.push(t.getCanonical(h-1)),u-=1,h-=1):a[u][h]==a[u-1][h]-i.gapPenalty?(m.push(i.gapSymbol),d.push(e.getCanonical(u-1)),u-=1):a[u][h]==a[u][h-1]-i.gapPenalty?(d.push(i.gapSymbol),m.push(t.getCanonical(h-1)),h-=1):(d.push(e.getCanonical(u-1)),m.push(t.getCanonical(h-1)),u-=1,h-=1)}d=[...ee().count(0).take(u).map(t=>e.getCanonical(t)),...d.reverse(),...i.localAlignment?ee().count(c[0]).take(s).map(t=>e.getCanonical(t)):[]],m=[...ee().count(0).take(h).map(e=>t.getCanonical(e)),...m.reverse(),...i.localAlignment?ee().count(c[1]).take(r).map(e=>t.getCanonical(e)):[]];const p=u,g=h;return p>g?m=[...new Array(p-g).fill(i.gapSymbol.valueOf()),...m]:d=[...new Array(g-p).fill(i.gapSymbol.valueOf()),...d],m.length>d.length?d.push(...new Array(m.length-d.length).fill(i.gapSymbol.valueOf())):m.push(...new Array(d.length-m.length).fill(i.gapSymbol.valueOf())),{seq1:d.join(""),seq2:m.join(""),seq1Splitted:new Oe.Mu(d,i.gapSymbol),seq2Splitted:new Oe.Mu(m,i.gapSymbol)}}(c,u),d=gt(h.seq1Splitted,h.seq2Splitted,l.defaultBiotype,n);t.append(s.div(d,{style:{width:"300px",overflow:"scroll"}})),c.length!==u.length&&t.append(s.divV([s.divText("Different sequence length:",{style:{fontWeight:"bold"}}),s.divText(`target: ${c.length} monomers`),s.divText(`selected: ${u.length} monomers`)],{style:{paddingBottom:"10px"}})),t.append(ft(n));const m=s.accordion(),p=s.element("i");p.className="grok-icon svg-icon svg-view-layout",m.addTitle(s.span([p,s.label("Similarity search")])),m.addPane("Differences",()=>t,!0),o.shell.o=m.root}}class At extends wt{seqHelper;diverseColumnLabel;renderMolIds=null;columnNames=[];computeCompleted=new c.Subject;sampledIndices=null;constructor(e){super("diversity",r.SEMTYPE.MACROMOLECULE),this.seqHelper=e,this.diverseColumnLabel=this.string("diverseColumnLabel",null)}async renderInt(e){if(this.beforeRender()&&this.dataFrame&&e&&this.targetColumn){await this.computeByMM();const e=null!=this.diverseColumnLabel?this.diverseColumnLabel:`diverse (${this.targetColumnName})`,t=r.Column.string(e,this.renderMolIds.length).init(e=>this.targetColumn?.get(this.renderMolIds[e]));t.semType=r.SEMTYPE.MACROMOLECULE,this.tags.forEach(e=>t.setTag(e,this.targetColumn.getTag(e)));const n=r.DataFrame.fromColumns([t]);t.temp[".mm.cellRenderer.maxMonomerLength"]=4,n.onCurrentRowChanged.subscribe(e=>{this.dataFrame.currentRowIdx=this.renderMolIds[n.currentRowIdx]});const i=n.plot.grid();(0,Ne.Kd)(i,t.name,450,30),(0,Ne.Ku)(this.root,i.root),this.computeCompleted.next(!0)}}async computeByMM(){const e=this.targetColumn.length;let t;this.requiresSampling&&e>1e4?(t=this.createRandomSample(e,1e4),this.sampledIndices=t):(t=Array.from({length:e},(e,t)=>t),this.sampledIndices=null);const n=this.distanceMetric,i=await ut(this.targetColumn,n,this.fingerprint,this.gapOpen,this.gapExtend),o=i.seqList,s=i.options,r=t.map(e=>o[e]),a=new D(!0,!1),l=await a.calc(r,n,!0,s);a.terminate();const c=t.length,u=(d=c,(e,t)=>d*e+t-Math.floor((e+2)*(e+1)/2)),h=function(e,t){function n(e,t){let n=null,i=null;for(const o of e){const e=t(o);(null==i||e>i)&&(n=o,i=e)}return n}const i=[(s=e-1,Math.floor(function(e){return Math.random()*e}(s)))],o=new Set;var s;for(let t=0;t<e;++t)i.includes(t)||o.add(t);for(;i.length<t;){const e=n(o.values(),e=>Math.min.apply(Math,i.map(function(t,n){return l[u(e,t)]})));null!=e&&(i.push(e),o.delete(e))}return i}(c,Math.min(c,this.limit));var d;this.renderMolIds=h.map(e=>t[e])}createRandomSample(e,t){const n=[];for(let t=0;t<e;t++)this.targetColumn.isNone(t)||n.push(t);if(n.length<=t)return n;for(let e=n.length-1;e>0;e--){const t=Math.floor(Math.random()*(e+1)),i=n[e];n[e]=n[t],n[t]=i}return n.slice(0,t)}}var Tt=n(5433);var Et=n(3736),St=n(4517);class Mt{constructor(e,t=[],n={}){this.onItemChanged=new c.Subject,this.onAddingItemChanged=new c.Subject,this.onItemAdded=new c.Subject,this.onItemRemoved=new c.Subject,this.options={removeButtonTooltip:"Remove item",addButtonTooltip:"Add item",allowAdd:!0,allowRemove:!0},this.addingItemInputs={},this.properties=e,this.options=Object.assign(Object.assign({},this.options),n),this._root=s.divV([],{style:{display:"grid",gridTemplateColumns:`repeat(${this.properties.length}, 1fr)`,alignItems:"center",gap:"12px"},classes:"ui-items-grid"}),this._items=t,this.render()}get root(){return this._root}get items(){return this._items}set items(e){this._items=e,this.render()}addItem(e,t=!0){this._items.push(e),this.render(),t&&this.onItemAdded.next(e)}removeItem(e,t=!0){-1!==this._items.indexOf(e)&&(this._items.splice(this._items.indexOf(e),1),this.render(),t&&this.onItemRemoved.next(e))}removeAtIndex(e,t=!0){if(e<0||e>=this._items.length)return;const n=this._items.splice(e,1);this.render(),t&&this.onItemRemoved.next(n[0])}removeAllItems(){this._items=[],this.render()}render(){var e,t,n,i,o;if(s.empty(this._root),!this.options.horizontalInputNames)for(const n of this.properties){let i=null!==(e=n.caption)&&void 0!==e?e:n.name;(null===(t=this.options.customLabels)||void 0===t?void 0:t[n.name])&&(i=this.options.customLabels[n.name]);const o=s.divText(i);o.style.fontWeight="bold",this._root.appendChild(o)}for(const e of this._items){const t=this.getItemDiv(e);for(const e of t)this._root.appendChild(e)}if(this.options.allowAdd){const e=this.getItemDiv(null!==(o=null===(i=(n=this.options).newItemFunction)||void 0===i?void 0:i.call(n))&&void 0!==o?o:void 0,!0);for(const t of e)this._root.appendChild(t)}}get addingItem(){const e={};return Object.keys(this.addingItemInputs).forEach(t=>{e[t]=this.addingItemInputs[t].value}),e}getItemDiv(e={},t){var n,i;const o=[],a={};let l=null;for(const c of this.properties){void 0===e[c.name]&&(e[c.name]=null);const u=(null===(n=this.options.customInputs)||void 0===n?void 0:n[c.name])?this.options.customInputs[c.name](e):s.input.forProperty(c,e),h=null===(i=this.options.validators)||void 0===i?void 0:i[c.name];h&&u.addValidator(h),o.push(this.options.horizontalInputNames?u.root:this.hideLabel(u.root)),c.propertyType!==r.TYPE.BOOL&&"color"!==c.name.toLowerCase()&&u.input&&(u.input.style.width="100%"),a[c.name]=u,u.onChanged.subscribe(()=>{e[c.name]=u.value,t?this.onAddingItemChanged.next({item:e,fieldName:c.name}):this.onItemChanged.next({item:e,fieldName:c.name})}),u.root.style.alignItems="center",l=u}let c=null;if(t)this.addingItemInputs=a,c=s.icons.add(()=>{const e=this.options.newItemFunction?this.options.newItemFunction():{};Object.keys(a).forEach(t=>{e[t]=a[t].value}),this._items.push(e),this.onItemAdded.next(e),this.render()},this.options.addButtonTooltip);else{if(!this.options.allowRemove)return o;c=s.icons.delete(()=>{this._items.splice(this._items.indexOf(e),1),this.onItemRemoved.next(e),this.render()},this.options.removeButtonTooltip)}return l&&l.addOptions?l.addOptions(c):null==l||l.root.appendChild(c),c.style.color="#2083d5",o}hideLabel(e){return e.getElementsByTagName("label")[0]&&e.removeChild(e.getElementsByTagName("label")[0]),e}hasErrors(){return this._root.querySelectorAll(".d4-invalid").length>0}}const xt={A:new G.A(new Uint32Array([2,0,0,0,16,0,0,0,134217728,0,0,0,32,0,33554432,0,0,0,0,0,1024,0,0,0,262144,128,0,0,0,0,0,0,0,2,0,0,524288,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1048576,0,536870912,0,0,0,0]),2048),C:new G.A(new Uint32Array([2,0,65536,0,0,0,0,32,0,0,2,0,32,0,0,0,0,0,0,0,1024,0,0,0,262144,128,0,0,0,0,0,0,0,65536,0,0,524288,0,0,0,0,0,0,0,524288,524288,0,0,0,0,0,0,0,0,0,0,0,34603008,0,536870912,64,0,0,0]),2048),D:new G.A(new Uint32Array([2,0,65600,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,1024,0,0,0,262400,128,0,0,0,0,0,0,0,0,0,2097152,524288,0,0,0,1024,0,0,0,524288,0,0,0,0,0,0,0,0,0,512,0,0,34603008,0,536870912,0,0,0,0]),2048),E:new G.A(new Uint32Array([2,0,65536,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,1024,0,0,8,262144,128,0,0,16,134217728,0,0,0,0,0,0,524288,0,0,0,128,0,0,0,524288,0,0,0,268435456,0,0,0,0,0,512,2147483648,0,34603008,0,536870912,0,0,0,0]),2048),F:new G.A(new Uint32Array([2,0,98304,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,1024,0,0,0,262144,128,33554432,0,0,0,0,33554432,0,1024,1,0,524288,32768,32,0,0,0,0,16,524288,0,0,0,0,0,0,0,0,0,71303168,0,0,34603008,131072,536870912,0,0,0,0]),2048),G:new G.A(new Uint32Array([134217728,0,65536,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,1024,0,0,0,0,128,0,0,0,0,2097216,0,0,0,0,0,524288,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,512,0,0,0,0,536870912,0,0,0,0]),2048),H:new G.A(new Uint32Array([2,0,1073840128,0,0,0,0,0,0,0,0,67108864,32,0,0,0,0,0,0,0,1024,0,512,0,262144,192,0,268435456,0,0,8200,0,0,0,67108864,0,524296,0,32,0,0,0,0,16,524288,0,0,2147483648,0,0,8,0,0,0,0,0,0,34603008,131072,536870920,4194304,0,0,0]),2048),I:new G.A(new Uint32Array([2,0,65536,0,0,0,0,0,150994944,64,0,0,32,0,0,0,0,0,0,0,1024,0,8388608,0,327680,128,0,0,0,0,0,0,0,2,0,524288,524288,0,0,0,0,0,0,0,0,0,0,0,256,0,0,0,0,8388608,0,33554432,0,1048576,0,536870912,0,0,0,0]),2048),K:new G.A(new Uint32Array([2,0,65536,0,0,0,0,0,0,0,0,0,268435488,0,0,0,0,0,0,0,1024,0,0,8,262144,128,0,0,0,0,2097152,0,0,67108864,0,0,524288,0,0,0,8,0,0,0,524288,0,0,8192,0,0,0,0,0,0,0,2147483648,0,34668544,0,545259520,0,0,0,0]),2048),L:new G.A(new Uint32Array([2,0,65536,0,0,0,0,0,134217728,0,0,0,32,512,0,0,0,0,0,0,1024,256,0,8388608,262400,128,0,0,0,0,0,0,0,2,0,0,524288,0,0,0,0,0,0,0,524288,0,0,0,0,0,0,0,0,0,0,0,0,42991616,0,536870912,0,0,0,0]),2048),M:new G.A(new Uint32Array([2050,0,65536,1048576,0,0,0,0,0,0,0,0,1056,0,0,0,0,0,0,0,1024,0,0,8,262144,128,0,0,0,0,0,536870912,0,2,0,0,1074266112,0,0,0,0,0,0,0,524288,0,0,0,4194304,0,0,0,0,0,0,2147483648,0,34603008,0,536870912,4194304,0,0,0]),2048),N:new G.A(new Uint32Array([2,0,65536,0,4096,0,0,0,0,0,0,16777216,32,0,0,0,0,0,0,0,1024,0,0,0,262400,128,0,0,0,0,0,0,0,0,0,0,524288,0,0,0,1024,0,0,0,524288,0,0,0,0,0,0,0,0,0,0,0,0,34603008,0,536871936,67108864,0,0,0]),2048),P:new G.A(new Uint32Array([0,0,1024,0,0,0,0,0,0,131072,0,1024,32,0,0,0,0,512,0,0,1024,0,0,64,0,128,0,0,1073741824,0,0,138412032,16,0,67108864,0,0,0,0,0,0,8192,0,0,8388608,0,0,8,0,0,0,0,0,0,256,0,0,0,0,553648128,0,0,0,0]),2048),Q:new G.A(new Uint32Array([2,0,65536,0,4096,0,0,0,0,0,0,0,32,0,0,0,0,2,0,0,1024,0,0,8,262144,128,0,0,16,0,0,0,0,0,0,0,524288,0,0,0,0,0,0,0,524288,0,0,0,268435456,0,0,0,0,0,16777216,2147483648,0,34603008,0,536871936,0,0,0,0]),2048),R:new G.A(new Uint32Array([2,0,65536,0,4096,0,32,0,0,0,0,0,268435488,0,0,0,0,0,0,32768,134218752,0,16,8,262144,128,0,1073741824,0,0,8388608,0,0,0,65536,0,524289,0,0,0,0,0,0,0,524288,2048,0,0,0,0,0,0,0,0,0,2147483648,0,34603008,1048576,545259520,0,0,0,0]),2048),S:new G.A(new Uint32Array([2,0,65536,0,0,0,1073741824,0,0,0,0,0,32,0,0,4,0,0,0,0,1024,0,0,0,262144,128,0,0,0,0,0,0,0,0,0,0,524288,0,0,1048576,0,0,0,0,524288,0,0,0,0,0,0,0,0,0,8388608,0,0,34603008,0,536870912,0,0,0,0]),2048),T:new G.A(new Uint32Array([2,0,0,0,0,0,0,8,134217728,0,0,67108864,32,0,0,0,0,0,0,0,1024,0,8388608,0,262144,128,0,0,0,0,0,0,0,2,0,524288,524288,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,536870912,0,0,0,0,1048576,67108864,536870912,0,0,0,0]),2048),V:new G.A(new Uint32Array([2,0,0,0,0,0,0,0,134217728,0,0,0,32,0,0,0,0,0,0,0,1024,0,8388608,0,262144,128,0,0,0,0,0,1073741824,128,2,0,524288,524288,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8192,0,1048576,0,536870912,0,0,0,0]),2048),W:new G.A(new Uint32Array([2,0,98304,8388608,0,0,0,0,0,0,256,4096,32,0,0,0,0,0,0,0,1024,0,0,0,262144,192,0,0,0,0,0,0,0,0,67108865,0,524288,32768,32,0,0,0,8224,16,524288,0,0,0,0,32,128,0,2097152,0,4194304,8388608,0,34603008,8519680,536870912,131072,262144,0,0]),2048),Y:new G.A(new Uint32Array([2,0,98304,0,0,0,0,0,0,4194304,0,0,32,0,0,0,0,0,0,0,1024,0,0,512,262144,128,33554432,0,0,0,0,33554432,0,0,0,0,524288,0,32,0,0,2,0,16,524288,0,0,0,0,0,4,0,0,0,71303168,262144,0,34603008,131072,536870912,0,0,0,0]),2048)},Pt={RNA:{A:new G.A(new Uint32Array([0,0,0,0,0,0,0,0,0,1024,0,67108864,0,0,0,512,0,0,0,8388608,0,0,512,0,0,64,4,0,0,0,4,0,0,0,67108864,0,524289,0,0,0,0,0,0,16,0,659456,0,256,0,16,0,0,0,268435456,0,0,262144,0,131072,0,0,0,8388608,0]),2048),C:new G.A(new Uint32Array([0,1073741824,0,0,0,0,0,2147483648,4,67108864,0,67108864,0,256,0,0,0,0,0,0,1024,0,128,0,0,64,0,0,0,0,0,0,0,0,67108864,0,524289,0,65536,0,0,0,0,16,0,131072,0,4,0,0,0,0,0,0,4194304,0,0,2147483648,131072,0,4096,0,0,0]),2048),G:new G.A(new Uint32Array([0,0,0,0,1024,0,0,0,0,67109888,16384,67108864,0,0,0,0,0,0,0,33562624,1024,33554432,512,16384,0,64,4,0,0,33554432,0,0,0,0,67108864,0,524289,0,0,0,0,0,0,16,0,135168,0,268435456,0,0,0,0,0,268435456,131072,0,0,2147483648,131072,0,0,0,8388608,0]),2048),T:new G.A(new Uint32Array([8388608,0,0,0,0,0,0,0,0,67108864,0,0,0,4,0,0,0,0,0,0,1024,0,0,16384,0,64,0,0,0,0,0,0,0,2,67108864,0,0,0,0,0,0,0,0,40976,0,0,0,0,0,0,0,0,0,67108864,131072,524288,0,0,8519680,0,1,33554432,1048576,0]),2048),U:new G.A(new Uint32Array([0,0,131072,1073741824,0,0,0,0,0,67108864,0,0,0,0,0,0,0,0,0,0,1024,0,128,0,0,64,0,0,0,0,0,0,0,32768,67108864,0,0,0,0,0,0,0,0,16,0,0,0,4,0,0,2048,0,0,0,4341760,0,0,0,131072,0,0,33554432,1048576,0]),2048)},PEPTIDE:xt};async function Lt(e,t,n=0){if(!Object.keys(Pt).includes(t))return null;const i=await async function(e){const t=r.Func.find({package:"Chem",name:"getMorganFingerprint"})?.[0];if(!t)return null;try{const n=(await t.apply({molString:e}))?.getBuffer().buffer;if(n)return new G.A(new Uint32Array(n),2048)}catch(e){return null}}(e);if(!i)return null;if(!Pt[t])return null;const o=Pt[t];let s=0,a=null;for(const[e,t]of Object.entries(o)){const o=(0,$.$1)(i,t);o>s&&o>=n&&(s=o,a=e)}return a}var It;!function(e){e.TYPE="V2000",e[e.NUM_OF_HEADER_LINES=3]="NUM_OF_HEADER_LINES",e[e.NUM_OF_COUNTS_DIGITS=3]="NUM_OF_COUNTS_DIGITS",e[e.ATOM_TYPE_COL=4]="ATOM_TYPE_COL",e[e.FIRST_BONDED_ATOM_COL=1]="FIRST_BONDED_ATOM_COL",e[e.BOND_TYPE_COL=3]="BOND_TYPE_COL",e[e.RGP_SHIFT=8]="RGP_SHIFT",e[e.MAX_ATOM_COUNT=999]="MAX_ATOM_COUNT",e.RGP_LINE_START="M RGP",e.ATOM_ALIAS_LINE_START="A ",e.END="M END"}(It||(It={}));class _t{constructor(e){this.init(e)}init(e){this.fileContent=e.replace(/\r/g,""),this._atomCount=void 0,this._atomTypes=void 0,this._bondCount=void 0,this._bondTypes=void 0,this.xyzAtomCoordinates=void 0,this._pairsOfBondedAtoms=void 0}get atomCount(){return void 0===this._atomCount&&this.setAtomAndBondCounts(),this._atomCount}get bondCount(){return void 0===this._bondCount&&this.setAtomAndBondCounts(),this._bondCount}get x(){var e;return null!==(e=this.xyzAtomCoordinates)&&void 0!==e||(this.xyzAtomCoordinates=this.parseAtomCoordinates()),this.xyzAtomCoordinates.x}get y(){var e;return null!==(e=this.xyzAtomCoordinates)&&void 0!==e||(this.xyzAtomCoordinates=this.parseAtomCoordinates()),this.xyzAtomCoordinates.y}get z(){var e;return null!==(e=this.xyzAtomCoordinates)&&void 0!==e||(this.xyzAtomCoordinates=this.parseAtomCoordinates()),this.xyzAtomCoordinates.z}get atomTypes(){var e;return null!==(e=this._atomTypes)&&void 0!==e||(this._atomTypes=this.parseAtomTypes()),this._atomTypes}get pairsOfBondedAtoms(){var e;return null!==(e=this._pairsOfBondedAtoms)&&void 0!==e||(this._pairsOfBondedAtoms=this.parseBondedAtomPairs()),this._pairsOfBondedAtoms}get bondTypes(){var e;return null!==(e=this._bondTypes)&&void 0!==e||(this._bondTypes=this.parseBondTypes()),this._bondTypes}setAtomAndBondCounts(){const{atomCount:e,bondCount:t}=this.parseAtomAndBondCounts();this._atomCount=e,this._bondCount=t}getNextColumnIdx(e){for(;!this.isWhitespace(e);)++e;for(;this.isWhitespace(e);)++e;return e}shiftIdxToSpecifiedColumn(e,t){let n=e;const i=this.isWhitespace(n)?t:t-1;for(let e=0;e<i;e++)n=this.getNextColumnIdx(n);return n}parseAtomTypes(){const e=this.atomCount,t=new Array(e);let n=this.getAtomBlockIdx();for(let i=0;i<e;i++)n=this.shiftIdxToAtomType(n),t[i]=this.parseAtomType(n),n=this.getNextLineIdx(n);return t}parseAtomCoordinates(){const e=new Float32Array(this.atomCount),t=new Float32Array(this.atomCount),n=new Float32Array(this.atomCount);let i=this.getAtomBlockIdx();for(let o=0;o<this.atomCount;o++){i=this.shiftIdxToXColumn(i);for(const s of[e,t,n])s[o]=this.parseFloatValue(i),i=this.getNextColumnIdx(i);i=this.getNextLineIdx(i)}return{x:e,y:t,z:n}}parseBondedAtomPairs(){const e=new Array(this.bondCount);let t=this.getBondBlockIdx();for(let n=0;n<this.bondCount;n++){t=this.shiftIdxToBondedAtomsPair(t);const i=new Uint16Array(2);i[0]=this.parseIntValue(t),t=this.getNextColumnIdx(t),i[1]=this.parseIntValue(t),e[n]=i,t=this.getNextLineIdx(t)}return e}parseBondTypes(){const e=this.bondCount,t=new Uint16Array(e);let n=this.getBondBlockIdx();for(let i=0;i<e;i++)n=this.shiftIdxToBondType(n),t[i]=this.parseIntValue(n),n=this.getNextLineIdx(n);return t}isWhitespace(e){const t=this.fileContent[e];return" "===t||"\t"===t}getNextLineIdx(e){return"\n"!==this.fileContent[e]?this.fileContent.indexOf("\n",e)+1:e+1}parseFloatValue(e){return this.parseNumericValue(parseFloat,e)}parseIntValue(e){return this.parseNumericValue(parseInt,e)}parseNumericValue(e,t){let n=t+1;for(;!this.isWhitespace(n);)++n;return e(this.fileContent.substring(t,n))}}class Nt extends _t{constructor(e){super(e),this.init(e)}init(e){super.init(e)}parseAtomType(e){let t=e,n=t;return this.isQuote(t)?(n=this.getNextIdenticalChar(t),t++):n=this.fileContent.indexOf(" ",n),this.fileContent.substring(t,n)}isQuote(e){const t=this.fileContent[e].charCodeAt(0);return 39===t||34===t}getNextIdenticalChar(e){const t=this.fileContent[e];return t?this.fileContent.indexOf(t,e+1):-1}isQuery(){return this.isQueryOrFragment((e,t)=>{return 39===e||34===e||76===e&&!((n=this.fileContent.charCodeAt(t+1))>64&&n<91||n>96&&n<123);var n})}isFragment(){return this.isQueryOrFragment(e=>82===e||42===e)}isQueryOrFragment(e){const t=this.atomCount;let n=this.getAtomBlockIdx();for(let i=0;i<t;i++){if(n=this.shiftIdxToAtomType(n),e(this.fileContent.charCodeAt(n),n))return!0;n=this.getNextLineIdx(n)}return!1}}class Rt extends Nt{constructor(e){super(e)}getAtomLines(){const e=this.getAtomBlockIdx(),t=this.getBondBlockIdx();return this.fileContent.substring(e,t).split("\n").slice(0,this.atomCount)}getBondLines(){const e=this.getBondBlockIdx();return this.fileContent.substring(e).split("\n").slice(0,this.bondCount)}getRGroupIdToAtomicIdxMap(){const e=new Map,t=this.fileContent.split("\n");t.filter(e=>e.startsWith(It.RGP_LINE_START)).forEach(t=>{const n=this.getAtomIdxToRgpIdxList(t);for(const[t,i]of n){if(e.has(t))throw new Error(`R group ${t} is already in the map`);e.set(t,i)}});const n=t.map((e,t)=>{if(e.startsWith(It.ATOM_ALIAS_LINE_START))return t}).filter(e=>void 0!==e),i=n.map(e=>t[e]),o=n.map(e=>t[e+1]);i.forEach((t,n)=>{const i=parseInt(t.split(/\s+/)[1])-1,s=parseInt(o[n].substring(1));if(e.has(s))throw new Error(`R group ${s} is already in the map`);e.set(s,i)});const s=this.getRGroupAtomicIndices().filter(t=>!Array.from(e.values()).includes(t));if(0!==s.length)throw new Error(`Unaccounted R group indices: ${s}`);return e}getAtomIdxToRgpIdxList(e){const t=e.split(/\s+/).filter(e=>e).slice(3).map(e=>parseInt(e)),n=new Array(t.length/2);for(let e=0;e<t.length;e+=2)n[e/2]=[t[e+1],t[e]-1];return n}getRGroupAtomicIndices(){return this.atomTypes.map((e,t)=>{if(e.includes("R#"))return t}).filter(e=>void 0!==e)}static isValidMolfile(e){return-1!==e.indexOf(It.TYPE)&&-1!==e.indexOf(It.END)}shiftIdxToAtomType(e){return this.shiftIdxToSpecifiedColumn(e,It.ATOM_TYPE_COL)}getCountsLineIdx(){let e=0;for(let t=0;t<It.NUM_OF_HEADER_LINES;++t)e=this.getNextLineIdx(e);return e}getAtomBlockIdx(){let e=this.getCountsLineIdx();return e=this.getNextLineIdx(e),e}shiftIdxToXColumn(e){return this.getNextColumnIdx(e)}shiftIdxToBondedAtomsPair(e){return this.shiftIdxToSpecifiedColumn(e,It.FIRST_BONDED_ATOM_COL)}shiftIdxToBondType(e){return this.shiftIdxToSpecifiedColumn(e,It.BOND_TYPE_COL)}getBondBlockIdx(){let e=this.getAtomBlockIdx();for(let t=0;t<this.atomCount;t++)e=this.getNextLineIdx(e);return e}parseAtomAndBondCounts(){let e=this.getCountsLineIdx(),t=e+It.NUM_OF_COUNTS_DIGITS;const n=parseInt(this.fileContent.substring(e,t));return e=t,t+=It.NUM_OF_COUNTS_DIGITS,{atomCount:n,bondCount:parseInt(this.fileContent.substring(e,t))}}}class $t extends Nt{constructor(e){super(e),this.init(e)}getAtomLines(){const e=this.getAtomBlockIdx(),t=this.getBondBlockIdx();return this.fileContent.substring(e,t).split("\n").slice(0,this.atomCount)}getBondLines(){const e=this.getBondBlockIdx();return this.fileContent.substring(e).split("\n").slice(0,this.bondCount)}getRGroupIdToAtomicIdxMap(){const e=new Map;return this.getAtomLines().forEach((t,n)=>{const i=t.match(/RGROUPS=\(([\d\s]+)\)/);if(i){const t=i[1].split(/\s+/).map(e=>parseInt(e));if(t.length>2)throw new Error(`R group data ${t} has more than 2 elements`);const o=t[1];if(e.has(o))throw new Error(`R group ${o} is already in the map`);e.set(o,n)}}),e}shiftIdxToAtomType(e){return this.shiftIdxToSpecifiedColumn(e,4)}getCountsLineIdx(){return this.fileContent.indexOf("M V30 COUNTS ")}getAtomBlockIdx(){let e=this.fileContent.indexOf("M V30 BEGIN ATOM");return e=this.getNextLineIdx(e),e}shiftIdxToXColumn(e){let t=this.shiftIdxToAtomType(e);return this.isQuote(t)?(t=this.getNextIdenticalChar(t),t=this.getNextColumnIdx(t),t):this.shiftIdxToSpecifiedColumn(e,5)}shiftIdxToBondedAtomsPair(e){return this.shiftIdxToSpecifiedColumn(e,5)}shiftIdxToBondType(e){return this.shiftIdxToSpecifiedColumn(e,4)}getBondBlockIdx(){return this.getNextLineIdx(this.fileContent.indexOf("M V30 BEGIN BOND"))}static isValidMolfile(e){return-1!==e.indexOf("V3000")&&-1!==e.indexOf("M END")}parseAtomAndBondCounts(){let e=this.fileContent.indexOf("M V30 COUNTS ")+14,t=this.fileContent.indexOf(" ",e+1);const n=parseInt(this.fileContent.substring(e,t));return e=t+1,t=this.fileContent.indexOf(" ",e+1),{atomCount:n,bondCount:parseInt(this.fileContent.substring(e,t))}}}class Ot{constructor(){}static getInstance(e){if(Ot.isMolfileV2K(e))return new Rt(e);if(Ot.isMolfileV3K(e))return new $t(e);throw new Error("Malformed molfile")}static isMolfileV2K(e){return Rt.isValidMolfile(e)}static isMolfileV3K(e){return $t.isValidMolfile(e)}}var Ht=n(6197),Dt=n(9124),Ft=n(3527);class kt{biotype;id;n;m;type;mt;smiles;get issmiles(){return!!this.smiles}at={R1:"H",R2:"H",R3:"H",R4:"H",R5:"H",R6:"H",R7:"H",R8:"H",R9:"H"};get rs(){return Object.keys(this.at).length}constructor(e,t,n="missing",i=void 0,o=void 0,s=void 0,r){if(this.biotype=e,this.id=t,this.n=n,this.m=i,this.type=o,this.mt=s,this.smiles=r,!this.id)throw new Error("Invalid arg undefined [id].")}static objCounter=-1;objId=++kt.objCounter;className="WebEditorMonomerDummy";toLog(){return`Helm: ${this.className}<${this.objId}>`}}class Gt extends kt{backgroundcolor="#808080";linecolor="#000000";textcolor="#000000";constructor(e,t,n,i,o){super(e,t,i,void 0,void 0,void 0,n),this.at={},o.forEach(e=>{this.at[e]="H"})}}class Bt extends kt{backgroundcolor="#FFFFFF";linecolor="#808080";textcolor="#808080";constructor(e){super(e,"*","gap")}}class Vt extends kt{backgroundcolor="#808080";linecolor="#000000";textcolor="#000000";constructor(e,t){super(e,t,"ambiguous")}}class Ut extends kt{backgroundcolor="#FF4444";linecolor="#800000";textcolor="#FFFFFF";constructor(e,t,n){super(e,t,"missing"),n&&(this.backgroundcolor="#C0C0C0",this.linecolor="#404040",this.textcolor="#404040")}}class qt extends kt{backgroundcolor="#FFFF44";linecolor="#800000";textcolor="#000000";constructor(e,t){super(e,t,"broken")}}class Wt{id;m;n;na;type;mt;at;smiles;get rs(){return Object.keys(this.at).length}get issmiles(){return!!this.smiles}linecolor;backgroundcolor;textcolor;constructor(e,t,n,i,o,s,r,a){this.id=e,this.m=t,this.n=n,this.na=i,this.type=o,this.mt=s,this.at=r,this.smiles=a}static fromMonomer(e,t,n){let i={};const o=t.symbol,s=t.smiles;if(t.rgroups.length>0)t.rgroups.forEach(e=>{i[e.label]=e.capGroupName});else{if(!s){if(t.lib)return new qt(e,o);throw new Error("Unexpected missing monomer without .lib")}i=n.getRS(s)}const r=new Wt(t.symbol,t.molfile,t.name,t.naturalAnalog,t.polymerType,t.monomerType,i),a=n.getMonomerColors(e,t.symbol);return a&&(r.textcolor=a?.textcolor,r.linecolor=a?.linecolor,r.backgroundcolor=a?.backgroundcolor),r}}const Yt={[Fe.o.BASE]:{A:"#20E040",G:"#040404",T:"#FF8080",C:"#2060FF",U:"#FF8080"},[Fe.o.NUCLEOTIDE]:{A:"#20E040",G:"#040404",T:"#FF8080",C:"#2060FF",U:"#FF8080"},[Fe.o.LINKER]:{P:"#9aa5e1",p:"#9aa5e1"},[Fe.o.SUGAR]:{R:"#7a85c1",r:"#7a85c1"},[Fe.o.AA]:{A:"rgb(44,160,44)",R:"rgb(23,190,207)",N:"rgb(235,137,70)",D:"rgb(31,119,180)",C:"rgb(188,189,34)",E:"rgb(31, 120, 150)",Q:"rgb(205, 111, 71)",G:"rgb(214,39,40)",H:"rgb(158,218,229)",I:"rgb(23,103,57)",L:"rgb(30,110,96)",K:"rgb(108, 218, 229)",M:"rgb(60,131,95)",F:"rgb(24,110,79)",P:"rgb(255,152,150)",S:"rgb(255,187,120)",T:"rgb(245,167,100)",W:"rgb(182, 223, 138)",Y:"rgb(152,223,138)",V:"rgb(74,160,74)"},[Fe.o.CHEM]:{R:"#eeeeee"},[Fe.o.BLOB]:{B:"#999999",G:"#e2e2e2"}},jt=/.*\|\$.*R.*\$\|/,Kt=/\[R(\d+)\]/,zt=/\[R(\d+)\]/g,Zt=/\[\*:(\d+)\]/g;function Xt(e,t){const n=Array.from(e.matchAll(zt)).map(e=>e[1]),i={name:"Explicit SMILES Monomer",smiles:e,polymerType:t??"CHEM",molfile:"",rgroups:n.map(e=>({label:`R${e}`,capGroupName:"H",capGroupSmiles:`[*:${e}][H]`,alternateId:`R${e}-H`})),author:"Datagrok auto-generated",id:0,createDate:null,monomerType:"Backbone"};try{let t=e;i.rgroups.forEach(e=>{const n=e.label.substring(1);t=t.replace(`[R${n}]`,`[*:${n}]`)});const n=Dn(o.chem.convert(t,o.chem.Notation.Smiles,o.chem.Notation.MolBlock));i.molfile=n,i.smiles=t}catch(t){Uo.logger.error(`getMonomerFromRSmiles: cannot convert SMILES to Molfile: ${e}\n${t}`)}return i}const Qt=/[\w()]+/,Jt=RegExp(String.raw`\(${Qt}(,${Qt})+\)`),en=e=>{const t=s.canvas(250,250);return o.chem.canvasMol(0,0,250,250,t,e),t},tn=new Ft.Mi([255,255,255]),nn=new Ft.Mi([0,0,0]),on=.7*(0,q.wQ)(tn);class sn{_monomers;source;_isEmpty;get isEmpty(){return this._isEmpty}_onChanged=new c.Subject;get onChanged(){return this._onChanged}constructor(e,t){this._monomers=e,this.source=t,this._isEmpty=!this._monomers||0===Object.keys(this._monomers).length||Object.entries(this._monomers).every(([e,t])=>0===Object.keys(t).length);for(const[e,t]of Object.entries(this._monomers))for(const[e,n]of Object.entries(t))n.lib=this}getMonomerSymbolsByType(e){const t=Object.keys(this._monomers[e]??{});return this._smilesMonomerCache[e]&&t.push(...Object.keys(this._smilesMonomerCache[e])),t}_smilesMonomerCache={};addMissingMonomer(e,t){let n=this._monomers[e];n||(n=this._monomers[e]={});let i=t;t==pe._S||t===pe.b9[pe.Hi.HELM]?i="Gap":("PEPTIDE"===e&&"X"===t||"RNA"===e&&"N"===t)&&(i="Any");const o=function(e,t){try{if(jt.test(e)){const n=e.split("|$"),i=n[0].trim(),o=n[1],s=Array.from(o.matchAll(/R(\d+)/g)),r=Array.from(i.matchAll(/(\*)/g));if(s.length!==r.length)return null;let a=i.replaceAll(/\[\*\]/g,"*");const l=s.map(e=>e[1]);for(let e=0;e<l.length;e++){const t=l[e];a=a.replace("*",`[R${t}]`)}return Xt(a,t)}let n=e;const i=Array.from(e.matchAll(Zt));for(const e of i){const t=e[0],i=e[1];n=n.replace(t,`[R${i}]`)}if(Kt.test(n))return Xt(n,t)}catch(t){Uo.logger.error(`smiles2Monomer: cannot parse SMILES: ${e}\n${t}`)}return null}(t,e);if(o){this._smilesMonomerCache[e]=this._smilesMonomerCache[e]??{};const i=this._smilesMonomerCache[e],s=Object.keys(i).length+1;i[t]=`#${e[0]}${s}`;const r={...o,symbol:i[t]},a=new Gt((0,Oe.MD)(e),r.symbol,t,`SMILES Monomer ${r.symbol}`,r.rgroups.map(e=>e.label));return r.wem=a,n[r.symbol]=r,r}return n[t]={symbol:t,name:i,molfile:"",author:"MISSING",id:-1,rgroups:ee().count(1).take(9).map(e=>({capGroupSmiles:"",alternateId:"",capGroupName:"",label:`R${e.toString()}`})).toArray(),smiles:"",polymerType:e,monomerType:void 0,createDate:null}}getMonomer(e,t){let n=t;"RNA"==e&&"R"==n&&(n="r"),"RNA"==e&&"P"==n&&(n="p");let i=null;if(e){this._smilesMonomerCache[e]?.[n]&&(n=this._smilesMonomerCache[e][n]);const t=this._monomers[e];if(i=t?.[n]??null,!i)return this.getMonomer(null,n)}else for(const[e,t]of Object.entries(this._monomers))if(i=t[n],i)break;return i}getWebEditorMonomer(e,t){const[n,i]=(0,Dt.fA)(e,t),o=(0,Ht.Y)(n);let s=this.getMonomer(o,i);if(s&&n==Fe.o.SUGAR&&(s.rgroups?.length??0)<3)return null;s||(s=this.addMissingMonomer(o,i));let r=s.wem??null;return r||(i===pe._S||"*"==i?r=s.wem=new Bt(n):n===Fe.o.NUCLEOTIDE&&"N"===i||n===Fe.o.AA&&"X"===i||(Fe.o.CHEM,0)||Jt.test(i)?r=s.wem=new Vt(n,i):s.lib||(r=s.wem=new Ut(n,i,this.isEmpty)),r||(r=s.wem=Wt.fromMonomer(n,s,this))),r}getTooltip(e,t){const n=(0,Ht.Y)(e),i=s.div([],{classes:"ui-form ui-tooltip"}),o=this.getWebEditorMonomer(e,t),r=this.getMonomer(n,t);if(r){const e=r.symbol,[t,n,a]=(r.name,o?[o.textcolor,o.backgroundcolor,o.linecolor]:["#202020","#A0A0A0","#202020"]);let l;if(i.append(s.divH([s.div([e],{style:{textWrap:"nowrap",marginLeft:"4px",marginRight:"4px",color:t,backgroundColor:n,borderColor:a,borderWidth:"1px",borderStyle:"solid",borderRadius:"2px",padding:"3px",minWidth:"24px",textAlign:"center"}}),s.div([r.name],{style:{padding:"4px"}})],{style:{display:"flex",flexDirection:"row",justifyContent:"left"}})),l=r.molfile?en(r.molfile):r.smiles?s.divV([en(r.smiles),s.divText("from smiles",{style:{fontSize:"smaller"}})]):s.divText("No structure",{style:{margin:"6px"}}),i.append(s.div(l,{style:{display:"flex",flexDirection:"row",justifyContent:"center",margin:"6px"}})),r.symbol!=pe._S){let e=r.lib?.source;e?(e.endsWith(".json")&&(e=e.substring(0,e.length-5)),e=e.replace(/_/g," ").replace(/-/g," ").replace(/([a-z])([a-z])([A-Z])/g,"$1$2 $3"),r.polymerType&&i.append(s.divText(r.polymerType,{style:{fontStyle:"italic"}})),i.append(s.divText(e))):i.append(s.divText("Missed in libraries"))}}else i.append(s.divV([s.divText(`Monomer '${t}' of type '${n}' not found.`),s.divText("Open the Context Panel, then expand Manage Libraries")]));return i}getMonomerTextColor(e,t){const n=this.getMonomerColors(e,t),i=e=>{const t=/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/.exec(e);if(t)return[parseInt(t[1]),parseInt(t[2]),parseInt(t[3])];const n=r.Color.fromHtml(e);return[r.Color.r(n),r.Color.g(n),r.Color.b(n)]},o=i(n.textcolor),s=new Ft.Mi([...o.map(e=>e+1)]),a=(0,q.KE)(s,tn)/((0,q.wQ)(s)*(0,q.wQ)(tn)),l=i(n.backgroundcolor),c=new Ft.Mi([...l.map(e=>e+.01)]);let u;u=(0,q.KE)(c,tn)/((0,q.wQ)(c)*(0,q.wQ)(tn))<a?l:o;let h=new Ft.Mi(u);const d=(0,q.wQ)(h);return d>on&&(h=(0,q.dC)(nn,h,on/d)),`rgb(${h[0]}, ${h[1]}, ${h[2]})`}getMonomerColors(e,t){const n="default";let i=n;const o=(0,Ht.Y)(e),s=this.getMonomer(o,t);let a;if(s){if(s.meta&&s.meta.colors){if("string"==typeof s.meta.colors)try{s.meta.colors=JSON.parse(s.meta.colors)}catch(e){Uo.logger.error(`Bio: MonomerLib.getMonomerColors() failed to parse monomer.meta.colors: ${e}`)}const e=s.meta.colors;e&&"string"!=typeof e&&!(n in e)&&(i="default"),e&&"string"!=typeof e&&i in e&&(a=e[i])}if(!a){const t=Yt[e],n=t?.[s.symbol];n&&(a={textColor:r.Color.toHtml(r.Color.getContrastColor(r.Color.fromHtml(n))),lineColor:"#202020",backgroundColor:n})}const t=s.naturalAnalog;if(!a&&t&&t!==s.symbol)return this.getMonomerColors(e,t)}return a||(a={textColor:"#202020",lineColor:"#202020",backgroundColor:"#A0A0A0"}),{textcolor:a.text??a.textColor,linecolor:a.line??a.lineColor,backgroundcolor:a.background??a.backgroundColor}}getRS(e){const t=e.match(/(?<=\[)[^\][]*(?=])/gm),n={};let i,o="";if(t)for(let e=0;e<t.length;e++)if(null!=t[e]&&/\d/.test(t[e])){i=t[e][t[e].length-1],t[e]=t[e].replace(/[0-9]/g,"");for(let n=0;n<t[e].length;n++)":"!=t[e][n]&&(o+=t[e][n]);n["R"+i]=o,o=""}return n}}var rn=n(5488),an={};an.styleTagTransform=C(),an.setAttributes=y(),an.insert=g().bind(null,"head"),an.domAPI=m(),an.insertStyleElement=w(),h()(rn.A,an),rn.A&&rn.A.locals&&rn.A.locals;class ln extends sn{error;_duplicateMonomers={};get duplicateMonomers(){return this._duplicateMonomers}_duplicatesHandled=!0;get duplicatesHandled(){return this._duplicatesHandled}duplicatesNotified=!1;constructor(e,t,n=void 0){super(e,t),this.error=n}toJSON(){const e=[];for(const t of Object.values(this._monomers))for(const n of Object.values(t))e.push({...n,lib:void 0,wem:void 0});return e}_monomerSets=null;getMonomerSet(e){const t=(0,Ht.Y)(e);if(this._monomerSets||(this._monomerSets={}),!(e in this._monomerSets))for(const[e,n]of Object.entries(this._monomers[t]));return this._monomerSets[e]}getPolymerTypes(){return Object.keys(this._monomers)}getMonomerMolsByPolymerType(e){const t={};return Object.keys(this._monomers[e]??{}).forEach(n=>{t[n]=this._monomers[e][n].molfile}),t}getMonomerSymbolsByRGroup(e,t,n){let i=this.getMonomerSymbolsByType(t).map(e=>this.getMonomer(t,e));return i=i.filter(e=>null!==e),0===i.length?[]:(i=i.filter(t=>{if(!t?.rgroups)return!1;let n=t?.rgroups.length>=e;var i;return i=Ot.getInstance(t.molfile).atomTypes,i.map((e,t)=>"R#"===e?t:-1).filter(e=>-1!==e),n&&=!0,n}),i.map(e=>e?.symbol))}_updateLibInt(e){const t=e.getPolymerTypes(),n=this.getPolymerTypes();t.forEach(t=>{n.includes(t)||(this._monomers[t]={}),e.getMonomerSymbolsByType(t).forEach(n=>{this._monomers[t][n]&&(this._duplicateMonomers[t]??={},this._duplicateMonomers[t][n]??=[this._monomers[t][n]],this._duplicateMonomers[t][n].push(e.getMonomer(t,n))),this._monomers[t][n]=e.getMonomer(t,n)})}),this._isEmpty=this.isEmpty&&e.isEmpty}async updateLibs(e,t=!1){t&&(this._monomers={},this._isEmpty=!0),this._duplicateMonomers={};for(const t of e)t.error||this._updateLibInt(t);if(Object.entries(this.duplicateMonomers).length>0){const e=await(0,Le.u)();this.assignDuplicatePreferences(e)}else this._duplicatesHandled=!0;this._onChanged.next()}assignDuplicatePreferences(e){let t=!0;for(const n in this.duplicateMonomers)for(const i in this.duplicateMonomers[n])if(e.duplicateMonomerPreferences?.[n]?.[i]){const o=e.duplicateMonomerPreferences[n][i],s=this.duplicateMonomers[n][i].find(e=>e.lib?.source===o);s?this._monomers[n][i]=s:t=!1}else t=!1;return this._duplicatesHandled=t,t}clear(){this._monomers={},this._onChanged.next()}getSummaryObj(){const e={},t=this.getPolymerTypes();for(const n of t)e[n]=this.getMonomerSymbolsByType(n).length;return e}getSummaryDf(){const e=this.getPolymerTypes(),t=new Array(e.length);for(const[n,i]of ee().enumerate(e))t[i]=this.getMonomerSymbolsByType(n).length;return r.DataFrame.fromColumns([r.Column.fromStrings("polymerType",e),r.Column.fromList(r.COLUMN_TYPE.INT,"count",t)])}getSummary(){const e=this.getPolymerTypes();return 0==e.length?"empty":e.map(e=>`${e} ${this.getMonomerSymbolsByType(e).length}`).join("\n")}static overrideCounter=0;override(e,t){return new cn(e,`override: ${++ln.overrideCounter}, ${t}`,this)}}class cn extends sn{data;base;constructor(e,t,n){super(e,t),this.data=e,this.base=n}get onChanged(){return this.base.onChanged}getMonomerSymbolsByType(e){const t=this.base.getMonomerSymbolsByType(e);for(const n of Object.keys(this.data[e]??{}))t.includes(n)||t.push(n);return t}addMissingMonomer(e,t){return this.base.addMissingMonomer(e,t)}getMonomer(e,t){const n=this.data[e]?.[t];return n??this.base.getMonomer(e,t)}}var un=n(8604),hn=n(7433),dn=n.n(hn),mn=n(1913),pn=n.n(mn);class gn{helmMonomerSchema;validateMonomerSchema;constructor(e){this.helmMonomerSchema=e;const t=new(dn())({allErrors:!0,strictTuples:!1,allowUnionTypes:!0});pn()(t),this.validateMonomerSchema=t.compile(this.helmMonomerSchema)}validateFile(e,t){const n=this.parseJson(e,t);return null!=n&&(Array.isArray(n)?this.validateJsonContent(n,t):(console.warn(`Bio: Monomer Library File Validator file '${t}': Invalid JSON format: The file must contain an array of monomers.`),!1))}parseJson(e,t){try{return JSON.parse(e)}catch(e){return console.error(`Bio: Monomer Library File Validator file '${t}': Invalid JSON format:`,e),null}}validateJsonContent(e,t){let n=!0;const i=new Set;for(const o of e){const e=o.symbol??o.id??o.name??"#N/A";if(n=this.validateMonomerSchema(o),!n){console.warn(`Bio: Monomer Library File Validator file ${t}, monomer '${e}' violating JSON schema:`,o,"\nError reason: ",JSON.stringify(this.validateMonomerSchema.errors??{}),`\nThere may be other errors in ${t} since the validation is stopped after the first error.`," Please, verify that the monomer library file satisfies the JSON schema");break}const s=`${o.polymerType??""}-${e}`;i.has(s)&&console.warn(`Bio: Monomer Library File Validator file ${t}, monomer '${e}' is duplicated.`,"Please, verify that the monomer library file does not contain duplicated monomer symbols."),i.add(s)}return n}}class fn{fileValidator;libHelper;logger;get LIB_PATH(){return"System:AppData/Bio/monomer-libraries/"}get SETS_PATH(){return"System:AppData/Bio/monomer-sets/"}static HELM_JSON_SCHEMA_PATH="System:AppData/Bio/tests/libraries/HELMmonomerSchema.json";static _instance=null;filesPromise=Promise.resolve();name=ye.ic;_onChanged=new c.Subject;get onChanged(){return this._onChanged}constructor(e,t,n){this.fileValidator=e,this.libHelper=t,this.logger=n}static async getInstance(e,t){if(null==this._instance){const n=await o.dapi.files.readAsText(fn.HELM_JSON_SCHEMA_PATH),i=JSON.parse(n),s=new gn(i);fn._instance=new fn(s,e,t),fn._instance.refreshLists()}return fn._instance}toLog(){return"MonomerLibFileManager"}async validateAgainstHELM(e,t){if(!this.isValidHELMLibrary(e,t))throw new Error(`File ${t} does not satisfy HELM standard`)}isValidHELMLibrary(e,t){return this.fileValidator.validateFile(e,t)}async refreshLists(){await Promise.all([this.updateValidLibList(),this.updateValidSetList()])}async addOrUpdateLibraryString(e,t){e=e.endsWith(".json")?e:`${e}.json`;try{await this.validateAgainstHELM(t,e),await o.dapi.files.writeAsText(this.LIB_PATH+`${e}`,t),await this.updateValidLibList(),await o.dapi.files.exists(this.LIB_PATH+`${e}`)?o.shell.info(`Added ${e} HELM library`):o.shell.error(`Failed to add ${e} library`)}catch(t){this.logger.error(t),o.shell.error(`Failed to add ${e} library`)}}async addOrUpdateLibrary(e,t){const n=JSON.stringify([...t.map(e=>({...e,wem:void 0,lib:void 0}))],null,2);await this.addOrUpdateLibraryString(e,n)}get loadPromise(){return this.filesPromise}async listLibraries(){return this.validLibList}async listSets(){return this.validSetList}async loadLibraries(e,t=!1){let n=[];e=e.map(e=>e.endsWith(".json")?e:`${e}.json`);const i=t?e:e.map(e=>this.LIB_PATH+e),s=[];for(let e=0;e<i.length;e++){const t={};try{const s=await o.dapi.files.readAsText(i[e]);n=JSON.parse(s),n.forEach(e=>{const n=e.polymerType,i=e.symbol;t[n]||(t[n]={}),t[n][i]=e})}catch(t){this.logger.error(`Failed to load monomer library file: ${i[e]}`),this.logger.error(t);continue}finally{s.push(t)}}return s}async loadSets(e){const t=[],n=this.libHelper.getMonomerLib();for(const i of e){const e=i.endsWith(".json")?i:`${i}.json`,s=this.SETS_PATH+e;try{const e=await o.dapi.files.readAsText(s),i=JSON.parse(e),r=i.description,a=Object.entries(i.placeholders).map(([e,t])=>{const i=e,o=t.polymerType,s=t.monomerType,r=t.set;return new ye.lH(n,i,o,s,r)});t.push(new ye.YS(r,a))}catch(e){this.logger.error(`Failed to load monomer set file: ${s}`),this.logger.error(e);continue}}return t}async deleteLibrary(e){const t=e.endsWith(".json")?e:`${e}.json`;await o.dapi.files.delete(this.LIB_PATH+t),await this.updateValidLibList()}async deleteSet(e){const t=e.endsWith(".json")?e:`${e}.json`;await o.dapi.files.delete(this.SETS_PATH+t),await this.updateValidSetList()}async addOrUpdateSetString(e,t){const n=e.endsWith(".json")?e:`${e}.json`;await o.dapi.files.writeAsText(this.SETS_PATH+n,t),await this.updateValidSetList()}async addOrUpdateSet(e,t){const n=JSON.stringify(t,null,2);await this.addOrUpdateSetString(e,n)}async deleteMonomersFromLibrary(e,t){const n=e.endsWith(".json")?e:`${e}.json`,i=this.LIB_PATH+n,s=await o.dapi.files.readAsText(i);let r=JSON.parse(s);r=r.filter(e=>!t.some(t=>e.polymerType===t.polymerType&&e.symbol===t.symbol));const a=JSON.stringify(r,null,2);await o.dapi.files.writeAsText(i,a),await this.updateValidLibList()}validLibList=[];libListHasChanged(e){const t=this.validLibList;return e.length!==t.length||e.some((e,n)=>e!==t[n])}validSetList=[];setListHasChanged(e){const t=this.validSetList;return e.length!==t.length||e.some((e,n)=>e!==t[n])}async getLibraryAsString(e){const t=e.endsWith(".json")?e:`${e}.json`;return o.dapi.files.readAsText(this.LIB_PATH+t)}async getSingleLibrary(e){return(await this.loadLibraries([e]))?.[0]}async getSingleLibraryWithFullPath(e){return(await this.loadLibraries([e],!0))?.[0]}async updateOrAddMonomersInLibrary(e,t){const n=e.endsWith(".json")?e:`${e}.json`,i=this.LIB_PATH+n,s=await o.dapi.files.readAsText(i),r=JSON.parse(s);for(const e of t){const t=r.findIndex(t=>t.polymerType===e.polymerType&&t.symbol===e.symbol);-1!==t?r[t]={...e,lib:void 0,wem:void 0}:r.push({...e,lib:void 0,wem:void 0})}const a=JSON.stringify(r,null,2);await o.dapi.files.writeAsText(i,a),await this.updateValidLibList()}async updateValidLibList(){const e=`${this.toLog()}.updateValidLibList()`;return this.logger.debug(`${e}, start`),this.filesPromise=this.filesPromise.then(async()=>{this.logger.debug(`${e}, IN`);const t=[],n=await this.getLibFileListAtLocation();if(!this.libListHasChanged(n))return void this.logger.debug(`${e}, end, not changed`);for(const e of n){if(!e.endsWith(".json")){t.push(e);continue}const n=await o.dapi.files.readAsText(this.LIB_PATH+`${e}`);this.isValidHELMLibrary(n,e)||t.push(e)}const i=n.filter(e=>!t.includes(e));if(this.libListHasChanged(i)&&(this.validLibList=i,await this.libHelper.loadMonomerLib(!0)),i.some(e=>!e.endsWith(".json"))&&this.logger.warning(`Wrong validation: ${i}`),t.length>0){const e=`Invalid monomer library files in ${this.LIB_PATH}, consider fixing or removing them: ${t.join(", ")}`;this.logger.warning(e)}this.logger.debug(`${e}, OUT`),this._onChanged.next()}),this.logger.debug(`${e}, end`),this.filesPromise}async updateValidSetList(){const e=`${this.toLog()}.updateValidSetList()`;return this.logger.debug(`${e}, start`),this.filesPromise=this.filesPromise.then(async()=>{this.logger.debug(`${e}, IN`);const t=[],n=await this.getSetFileListAtLocation();if(!this.setListHasChanged(n))return void this.logger.debug(`${e}, end, not changed`);for(const e of n)e.endsWith(".json")||t.push(e);const i=n.filter(e=>!t.includes(e));this.setListHasChanged(i)&&(this.validSetList=i,this.libHelper.loadMonomerSets(!0)),this.logger.debug(`${e}, OUT`),this._onChanged.next()}),this.logger.debug(`${e}, end`),this.filesPromise}async getLibFileListAtLocation(){const e=`${this.toLog()}.getLibFileListAtLocation()`;this.logger.debug(`${e}, start`);const t=await o.dapi.files.list(this.LIB_PATH).then(e=>e.filter(e=>e.isFile).map(e=>e.fullPath)),n=[];return n.push(...t),n.map(e=>e.substring(this.LIB_PATH.length))}async getSetFileListAtLocation(){const e=`${this.toLog()}.getSetFileListAtLocation()`;this.logger.debug(`${e}, start`);const t=await o.dapi.files.list(this.SETS_PATH).then(e=>e.map(e=>e.fullPath)),n=[];return n.push(...t),n.map(e=>e.substring(this.SETS_PATH.length))}}const yn="System:AppData/Bio/monomer-collections/";class bn{logger;_monomerLib=new ln({},"MAIN");_monomerSets=new ye.YS("MAIN",[]);_initialLoadCompleted=!1;get initialLoadCompleted(){return this._initialLoadCompleted}_providersDataChanged=new c.Subject;get providersDataChanged(){return this._providersDataChanged}_fileUploadRequested=new c.Subject;get fileUploadRequested(){return this._fileUploadRequested}requestFileUpload(){this._fileUploadRequested.next()}_selectionChanged=new c.Subject;get librarySelectionChanged(){return this._selectionChanged}notifyLibrarySelectionChanged(){this._selectionChanged.next()}async getAvaliableLibraryNames(e=!1){const t=await this.getProviders(),n=[];for(const i of t){e&&await i.refreshLists();const t=await i.listLibraries();n.push(...t)}return n}async refreshValidLibraryLists(){const e=await this.getProviders();await Promise.all(e.map(async e=>e.refreshLists()))}async getAvailableLibrariesPerProvider(){const e=await this.getProviders(),t=new Map;for(const n of e){const e=await n.listLibraries();t.set(n.name,e)}return t}async awaitLoaded(e=1/0){return e=e===1/0?6e4:e,await Promise.race([(async()=>{const e=await this.getProviders();return await Promise.all(e.map(async e=>e.loadPromise)),await this.loadLibrariesPromise,!0})(),(async()=>(await r.delay(e),!1))()]).then(t=>{if(!t)throw new Error(`Loading monomer libraries timeout ${e} ms.`)})}_monomerLibProviders=null;async getProviders(){if(null==this._monomerLibProviders){const e=r.Func.find({meta:{role:"monomer-lib-provider"}});this._monomerLibProviders=await Promise.all(e.map(async e=>await e.apply({}))),this._monomerLibProviders.push(await fn.getInstance(this,Uo.logger)),r.debounce((0,c.merge)(...this._monomerLibProviders.map(e=>e.onChanged)),200).subscribe(()=>{this._providersDataChanged.next()})}return this._monomerLibProviders}constructor(e){this.logger=e}static objCounter=-1;objId=(()=>{if(++bn.objCounter>0)throw new Error("MonomerLibManager MUST be a singleton.");return bn.objCounter})();toLog(){return`MonomerLibManager<${this.objId}>`}getMonomerLib(){return this._monomerLib}getBioLib(){return this.getMonomerLib()}getMonomerSets(){return this._monomerSets}get duplicateMonomers(){return this._monomerLib.duplicateMonomers}get duplicatesHandled(){return this._monomerLib.duplicatesHandled}assignDuplicatePreferances(e){this._monomerLib.assignDuplicatePreferences(e)}loadLibrariesPromise=Promise.resolve();async loadMonomerLib(e=!1){const t=`${this.toLog()}.loadMonomerLib()`;return this.logger.debug(`${t}, start`),this.loadLibrariesPromise=this.loadLibrariesPromise.then(async()=>{this.logger.debug(`${t}, IN`);const n=r.TaskBarProgressIndicator.create("Loading monomers ...");try{const t=await(0,Le.u)(),i=await this.getProviders(),s=await Promise.all(i.map(async e=>e.listLibraries()));s.forEach((e,n)=>{s[n]=e.filter(e=>{const n=!t.exclude.includes(e),i=0===(t.explicit?.length??0)||t.explicit.includes(e);return n&&i})});let r=0;const a=[];for(let e=0;e<i.length;e++){const t=i[e],l=s[e];try{const e=await t.loadLibraries(l);for(let t=0;t<e.length;t++)a.push(new ln(e[t],l[t]))}catch(e){o.shell.warning(`Loading monomer libraries from provider '${t.name}' failed: `),this.logger.error(`Loading monomer libraries from provider '${t.name}' failed: ${e instanceof Error?e.message:e.toString()}`)}n.update(Math.round(100*++r/i.length),`Loading monomers ${r}/${i.length}`)}this._monomerLib.updateLibs(a,e),this._initialLoadCompleted=!0}catch(e){const t=`Loading monomer libraries error: ${e instanceof Error?e.message:e.toString()}`;o.shell.warning(t);const n=e instanceof Error?e.stack:void 0;this.logger.error(t,void 0,n)}finally{n.close(),this.logger.debug(`${t}, OUT`)}}),this.logger.debug(`${t}, end`),this.loadLibrariesPromise}async loadLibraries(e){return this.loadMonomerLib(e)}loadSetsPromise=Promise.resolve();async loadMonomerSets(e=!1){const t=`${this.toLog()}.loadMonomerSets()`;return this.logger.debug(`${t}, start`),this.loadSetsPromise=this.loadSetsPromise.then(async()=>{this.logger.debug(`${t}, IN`);const e=r.TaskBarProgressIndicator.create("Loading monomer sets ...");try{const t=await this.getProviders(),n=await Promise.all(t.map(async e=>e.listSets())),i=[];let s=0;for(let r=0;r<t.length;r++){const a=t[r],l=n[r];try{const e=await a.loadSets(l);for(let t=0;t<e.length;t++)i.push(e[t])}catch(e){o.shell.warning(`Loading monomer sets from provider '${a.name}' failed: `),this.logger.error(`Loading monomer sets from provider '${a.name}' failed: ${e instanceof Error?e.message:e.toString()}`)}e.update(Math.round(100*++s/t.length),`Loading monomer sets ${s}/${t.length}`)}this._monomerSets.updateSets(i)}catch(e){const t=`Loading monomer sets error: ${e instanceof Error?e.message:e.toString()}`;o.shell.warning(t);const n=e instanceof Error?e.stack:void 0;this.logger.error(t,void 0,n)}finally{e.close(),this.logger.debug(`${t}, OUT`)}}),this.logger.debug(`${t}, end`),this.loadSetsPromise}async loadMonomerLibForTests(){await(0,Le.E)(un.G),await this.awaitLoaded(1e4),await this.loadMonomerLib(!0)}async readSingleLibrary(e,t){const n=(await this.getProviders()).find(t=>t.name===e);if(!n)return this.logger.error(`Provider '${e}' not found.`),null;try{const i=await n.loadLibraries([t]);return 0===i.length?(this.logger.error(`Library '${t}' not found in provider '${e}'.`),null):new ln(i[0],t)}catch(e){return this.logger.error(`Loading monomer library '${t}' from provider '${n.name}' failed: ${e instanceof Error?e.message:e.toString()}`),null}}async readLibraryFromFilePath(e){const t=(await this.getProviders()).find(e=>e.name===ye.ic);if(!t)throw new Error(`Provider '${ye.ic}' not found.`);const n=await t.getSingleLibraryWithFullPath(e);if(!n)throw new Error(`Library at path '${e}' not found.`);return new ln(n,e)}async readSingleLibraryByName(e){const t=await this.getProviders(),n=await(0,ye.pY)(t,e);return n?this.readSingleLibrary(n.name,e):(this.logger.error(`No provider found for library '${e}'.`),null)}async readSingleSet(e,t){const n=(await this.getProviders()).find(t=>t.name===e);if(!n)return this.logger.error(`Provider '${e}' not found.`),null;try{const i=await n.loadSets([t]);return 0===i.length?(this.logger.error(`Set '${t}' not found in provider '${e}'.`),null):i[0]}catch(e){return this.logger.error(`Loading monomer set '${t}' from provider '${n.name}' failed: ${e instanceof Error?e.message:e.toString()}`),null}}async listMonomerCollections(){return(await o.dapi.files.list(yn)).filter(e=>"json"===e.extension||e.name.endsWith(".json")).map(e=>e.name)}async deleteMonomerCollection(e){e.endsWith(".json")||(e+=".json"),await o.dapi.files.exists(yn+e)&&await o.dapi.files.delete(yn+e)}async readMonomerCollection(e){e.endsWith(".json")||(e+=".json");const t=await o.dapi.files.readAsText(yn+e);return JSON.parse(t)}async addOrUpdateMonomerCollection(e,t,n,i){e.endsWith(".json")||(e+=".json");const s=JSON.stringify({description:n,tags:i,monomerSymbols:t,updatedBy:r.User.current().login,updatedOn:(new Date).toISOString()},null,2);await o.dapi.files.writeAsText(yn+e,s)}static async getInstance(){let e=window.$monomerLibHelperPromise;return null==e&&(e=window.$monomerLibHelperPromise=(async()=>new bn(Uo.logger))()),e}}var wn=n(857),vn={};vn.styleTagTransform=C(),vn.setAttributes=y(),vn.insert=g().bind(null,"head"),vn.domAPI=m(),vn.insertStyleElement=w(),h()(wn.A,vn),wn.A&&wn.A.locals&&wn.A.locals;const Cn=[{alternateId:"R1-H",capGroupName:"H",capGroupSmiles:"[*:1][H]",label:"R1"},{alternateId:"R2-OH",capGroupName:"OH",capGroupSmiles:"O[*:2]",label:"R2"},{alternateId:"R3-H",capGroupName:"H",capGroupSmiles:"[*:3][H]",label:"R3"},{alternateId:"R4-H",capGroupName:"H",capGroupSmiles:"[*:4][H]",label:"R4"},{alternateId:"R5-H",capGroupName:"H",capGroupSmiles:"[*:5][H]",label:"R5"},{alternateId:"R6-H",capGroupName:"H",capGroupSmiles:"[*:6][H]",label:"R6"}];function An(e,t,n){let i=t[e]??n[e];if(i&&i.length>0)return i;const s=Fn(e,Cn);if(s!==e){const e=o.chem.convert(s,r.chem.Notation.Unknown,r.chem.Notation.Smiles);if(i=t[e]??n[e],i&&i.length>0)return i}return[]}function Tn(e){const t=new Set;return e.filter(e=>!t.has(e.symbol)&&(t.add(e.symbol),!0))}function En(e,t){const n=new Set;for(const i of e){const e=t[i.symbol];if(e&&e.length>0)for(const t of e){const e=t?.lib?.source;e&&n.add(e)}else i.source&&n.add(i.source)}return Array.from(n).join(", ")}var Sn;!function(e){e.MONOMER="Monomer",e.SYMBOL="Symbol",e.NAME="Name",e.R_GROUPS="~R-Groups",e.MONOMER_TYPE="Monomer Type",e.POLYMER_TYPE="Polymer Type",e.NATURAL_ANALOG="Natural Analog",e.AUTHOR="Author",e.CREATE_DATE="Create Date",e.ID="ID",e.META="Meta",e.SOURCE="Source"}(Sn||(Sn={}));const Mn={[Sn.MONOMER]:r.COLUMN_TYPE.STRING,[Sn.SYMBOL]:r.COLUMN_TYPE.STRING,[Sn.NAME]:r.COLUMN_TYPE.STRING,[Sn.R_GROUPS]:r.COLUMN_TYPE.STRING,[Sn.MONOMER_TYPE]:r.COLUMN_TYPE.STRING,[Sn.POLYMER_TYPE]:r.COLUMN_TYPE.STRING,[Sn.NATURAL_ANALOG]:r.COLUMN_TYPE.STRING,[Sn.AUTHOR]:r.COLUMN_TYPE.STRING,[Sn.CREATE_DATE]:r.COLUMN_TYPE.DATE_TIME,[Sn.ID]:r.COLUMN_TYPE.INT,[Sn.META]:r.COLUMN_TYPE.STRING,[Sn.SOURCE]:r.COLUMN_TYPE.STRING};async function xn(e){const t=await Pn(e);if(e.length!==t.rowCount)throw new Error(`Monomers length ${e.length} does not match dataframe row count ${t.rowCount}`);return await Promise.all(new Array(e.length).fill(null).map(async(e,n)=>kn(t.rows.get(n))))}async function Pn(e){try{const t=r.DataFrame.create(e.length),n=new Set;for(const t of e)t.rgroups.forEach(e=>{e.label&&n.add(e.label)});const i=Array.from(n);i.sort();for(const[e,n]of Object.entries(Mn))if(t.columns.addNew(e,n),e===Sn.R_GROUPS)for(const e of i)t.columns.addNew(e,r.COLUMN_TYPE.STRING);t.col(Sn.SYMBOL).semType="Monomer",t.col(Sn.SYMBOL).setTag(Re.Mn.applyToBackground,"true"),t.col(Sn.SYMBOL).setTag(pe.qE.polymerTypeColumnName,Sn.POLYMER_TYPE);const o=r.TaskBarProgressIndicator.create("Creating Monomers DataFrame...");for(let n=0;n<e.length;n++){n%20==0&&o.update((n+1)/e.length*100,"Creating Monomers DataFrame...");const s=()=>{let o=Hn(e[n].rgroups,e[n].smiles,e[n].molfile);o=In(o),e[n].rgroups=$n(e[n].rgroups);const s=i.map(t=>{const i=e[n].rgroups.find(e=>e.label===t);return i?Nn(i,"capGroupSmiles"):""});let r=null;if(e[n].createDate)try{r=Date.parse(e[n].createDate)}catch(t){console.error(`Error parsing date ${e[n].createDate}`)}t.rows.setValues(n,[o,e[n].symbol,e[n].name,JSON.stringify(e[n].rgroups??[]),...s,e[n].monomerType,e[n].polymerType,e[n].naturalAnalog,e[n].author,r,e[n].id,JSON.stringify(e[n].meta??{}),e[n].lib?.source??""],!1);try{r&&t.col(Sn.CREATE_DATE)?.set(n,r,!1)}catch(t){console.error(`Error setting date ${e[n].createDate}`,t)}};await new Promise(e=>{const t=()=>{try{s(),e()}catch(t){console.error("Error in doFill",t),e()}};n%20==0?setTimeout(()=>{t()}):t()})}return o.close(),t.col(Sn.MONOMER).semType=r.SEMTYPE.MOLECULE,i.forEach(e=>{t.col(e).semType=r.SEMTYPE.MOLECULE}),t}catch(e){throw o.shell.error("Error creating monomers dataframe"),console.error(e),e}}class Ln{monomerLibManamger;adjustTable(){this.tv?.dataFrame&&(o.data.detectSemanticTypes(this.tv.dataFrame),this.tv.dataFrame.meta.detectSemanticTypes()),setTimeout(()=>{this.tv?.grid&&(this.tv.grid.props.allowEdit=!1,this.tv.grid.col(Sn.NAME).width=100,this.tv.grid.col(Sn.SYMBOL).width=70)},200)}static VIEW_NAME="Manage Monomers";_newMonomer=de.pe;_newMonomerForm;monomerLib;tv=null;libInput;static instance;activeMonomerLib=null;constructor(e){this.monomerLibManamger=e,this.monomerLib=e.getBioLib(),this._newMonomerForm=new On(e,()=>this.activeMonomerLib,async e=>{const t=await this.getMonomersDf(this.libInput.value);this.tv?.dataFrame&&(this.tv.dataFrame=t,this.adjustTable(),null!=e&&setTimeout(()=>{const n=t.col(Sn.SYMBOL).toList().indexOf(e);-1!==n&&(this.tv?.grid.scrollToCell(t.columns.byIndex(0),n),t.currentRow=t.rows.get(n))},500))},()=>this.tv?.dataFrame)}static async getInstance(){if(!this.instance){const e=await bn.getInstance();await e.awaitLoaded(),this.instance=new Ln(e)}return this.instance}static async getNewInstance(){const e=await bn.getInstance();return await e.awaitLoaded(),new Ln(e)}async createNewMonomerLib(e,t,n){this.tv?.grid&&s.setUpdateIndicator(this.tv.grid.root,!0);try{const i=(await this.monomerLibManamger.getProviders()).find(t=>t.name===e);if(!i)throw new Error(`Provider ${e} not found`);const s=n.map(e=>({...e,lib:void 0,wem:void 0}));await i.addOrUpdateLibrary(t,s),await this.monomerLibManamger.loadMonomerLib(!1),o.shell.v=await this.getViewRoot(t)}catch(e){o.shell.error("Error creating library"),console.error(e)}finally{this.tv?.grid&&s.setUpdateIndicator(this.tv.grid.root,!1)}}async createNewMonomersCollectionDialog(e){const t=(await this.monomerLibManamger.listMonomerCollections()).map(e=>e.toLowerCase()),n=s.input.string("Collection Name",{tooltipText:"Name of the monomer collection, should be unique",placeholder:"Enter collection name",nullable:!1}),i=s.input.string("Description",{tooltipText:"Description of the monomer collection",placeholder:"Enter collection description",nullable:!0}),r=s.dialog("Create New Monomer Collection").add(n).add(i).addButton("Add",async()=>{if(!n.value||!n.value.trim())return void o.shell.warning("Collection name cannot be empty");const a=async e=>{await this.monomerLibManamger.addOrUpdateMonomerCollection(n.value,e,i.value??void 0),o.shell.info(`Collection ${n.value} saved successfully`)};if(t.includes(n.value.toLowerCase())||t.includes(n.value.toLowerCase()+".json")){const t=s.dialog("Collection already exists").add(s.divText(`A collection with the name ${n.value} already exists. Do you want to merge or overwrite it?`));t.addButton("Merge",async()=>{const i=await this.monomerLibManamger.readMonomerCollection(n.value),s=Array.from(new Set([...i.monomerSymbols??[],...e]));try{await a(s)}catch(e){o.shell.error("Error merging monomer collection"),console.error(e)}t.close()}),t.addButton("Overwrite",async()=>{try{await a(e)}catch(e){o.shell.error("Error overwriting monomer collection"),console.error(e)}t.close()}),t.show()}else try{await a(e)}catch(e){o.shell.error("Error creating monomer collection"),console.error(e)}r.close()}).show()}async createNewLibDialog(e){const t=await this.monomerLibManamger.getAvaliableLibraryNames(),n=s.input.string("Library Name",{placeholder:"Enter library name",nullable:!1,onValueChanged:()=>{const e=i(n.value);l.getButton("Create")?.classList?.toggle("d4-disabled",!!e)}});function i(e){return e&&e.trim()?t.includes(e)||t.includes(e+".json")?"Library with this name already exists":null:"Library name cannot be empty"}n.addValidator(i);const r=(await this.monomerLibManamger.getProviders()).map(e=>e.name),a=s.input.choice("Storage",{items:r,value:r[0],nullable:!1,tooltipText:"Select storage provider for the new library"});1===r.length&&(a.readOnly=!0);const l=s.dialog("Create New Library").add(a).add(n).addButton("Create",async()=>{const t=i(n.value);if(t)o.shell.warning(t);else if(a.value){try{await this.createNewMonomerLib(a.value,n.value,e??[])}catch(e){o.shell.error("Error creating library"),console.error(e)}l.close()}else o.shell.warning("Please select storage provider")}).show();l.getButton("Create")?.classList?.toggle("d4-disabled",!0)}get newMonomer(){return this._newMonomer}getNewMonomerForm(){return this._newMonomerForm}_contextMenuSub=null;async getMonomersTableView(e,t=!0){const n=await this.getMonomersDf(e);return this.tv=r.TableView.create(n,t),this.adjustTable(),this._contextMenuSub?.unsubscribe(),this._contextMenuSub=o.events.onContextMenu.subscribe(({args:e})=>{if(!e||!e.menu||!e.context||e.context.type!==r.VIEWER.GRID||!e.context.tableView||e.context.tableView.id!==(this.tv.id??"")||!e.item||!e.item.isTableCell||(e.item.tableRowIndex??-1)<0)return;const t=e.item.tableRowIndex,n=e.menu;if(n.item("Edit Monomer",async()=>{await this.editMonomer(this.tv.dataFrame.rows.get(t))}),n.item("Fix all monomers",()=>{this.fixAllMonomers()}),this.tv.dataFrame.selection.trueCount>0){const e=n.group("Selected Monomers");e.item("Remove",async()=>{const e=await Promise.all(Array.from(this.tv.dataFrame.selection.getSelectedIndexes()).map(e=>kn(this.tv.dataFrame.rows.get(e))));this._newMonomerForm.removeMonomers(e,this.libInput.value)}),e.item("Create Library",async()=>{const e=await Promise.all(Array.from(this.tv.dataFrame.selection.getSelectedIndexes()).map(e=>kn(this.tv.dataFrame.rows.get(e))));this.createNewLibDialog(e)}),e.item("Create Collection",async()=>{const e=Array.from(this.tv.dataFrame.selection.getSelectedIndexes()).map(e=>this.tv.dataFrame.col(Sn.SYMBOL).get(e)).filter(e=>!!e&&e.trim().length>0);if(0===e.length)return o.shell.warning("No valid monomer symbols found in selection");this.createNewMonomersCollectionDialog(e)})}else n.item("Remove Monomer",async()=>{const e=await kn(this.tv.dataFrame.rows.get(t));this._newMonomerForm.removeMonomers([e],this.libInput.value)})}),this.tv.grid&&(this.tv.grid.props.allowEdit=!1),this.tv}static closeAllMonomerManagers(){Array.from(o.shell.tableViews??[]).filter(e=>e.name===Ln.VIEW_NAME).forEach(e=>e.close())}findActiveManagerView(){if(!this.tv)return null;const e=Array.from(o.shell.tableViews??[]).find(e=>e.id===this.tv.id);return e?o.shell.v=e:Ln.closeAllMonomerManagers(),e??null}_skipLibInputOnchange=!1;async getViewRoot(e,t=!0){const n=await this.monomerLibManamger.getAvaliableLibraryNames();if(this._newMonomerForm.molSketcher.resize(),t&&(this.tv=this.findActiveManagerView())&&(e??this.libInput.value)){try{this._skipLibInputOnchange=!0,this.libInput&&(this.libInput.items=n),e&&(this.libInput.value=e)}catch(e){o.shell.error("Error updating library list"),console.error(e)}finally{this._skipLibInputOnchange=!1}const t=await this.getMonomersDf(e);return this.tv.dataFrame=t,this.adjustTable(),this.tv}e??=n[0],this.tv=await this.getMonomersTableView(e,t);let i=this.tv.getRibbonPanels();i.forEach((e,t)=>{i[t]=e.filter(e=>0!==e.getElementsByClassName("grok-icon-filter").length)}),i=i.filter(e=>e.length>0);const a=s.icons.add(()=>{this._newMonomerForm.setEmptyMonomer()},"Add New Monomer"),l=s.iconFA("wand-magic",()=>{this.fixAllMonomers()},"Fix all monomers"),c=s.icons.edit(async()=>{(this.tv?.dataFrame?.currentRowIdx??-1)<0||await this.editMonomer(this.tv.dataFrame.rows.get(this.tv.dataFrame.currentRowIdx))},"Edit Monomer"),u=s.icons.delete(async()=>{const e=this.tv?.dataFrame?.currentRowIdx??-1,t=Array.from(this.tv?.dataFrame?.selection?.getSelectedIndexes()??[]);if(e<0&&0===t.length)return;if(t.length>0){const e=await Promise.all(t.map(e=>kn(this.tv.dataFrame.rows.get(e))));return void await this._newMonomerForm.removeMonomers(e,this.libInput.value)}const n=await kn(this.tv.dataFrame.rows.get(e));await this._newMonomerForm.removeMonomers([n],this.libInput.value)},"Delete");s.tooltip.bind(u,()=>(this.tv?.dataFrame?.selection?.trueCount??0)>0?"Delete selected monomers":"Delete monomer");const h=async()=>{const e=this.libInput.value;if(!e)return o.shell.error("No library selected");let t=null;try{const n=await(0,ye.pY)(await this.monomerLibManamger.getProviders(),e);if(!n)throw new Error(`Library ${e} not found in any provider`);t=await n.getLibraryAsString(e)}catch(t){return o.shell.error(`Error reading library ${e}`),console.error(t)}if(!t)return o.shell.error(`Library ${e} is empty`);r.Utils.download(e,t,"text/plain")},d=async()=>{const e=this.libInput.value;if(!e)return o.shell.error("No library selected");const t=this.tv?.dataFrame;if(!t)return o.shell.error("No monomer table loaded");const n=t.col(Sn.MONOMER),i=t.col(Sn.R_GROUPS);if(!n||!i)return o.shell.error("Monomer or R-groups column not found");const s=t.clone(t.filter),a=s.col(Sn.MONOMER),l=s.col(Sn.R_GROUPS),c=s.columns.getUnusedName("Capped Molecule"),u=s.columns.addNewString(c);u.semType=r.SEMTYPE.MOLECULE;for(let e=0;e<s.rowCount;e++){const t=a.get(e);if(!t)continue;let n=[];try{const t=l.get(e);n=t?JSON.parse(t):[]}catch(e){n=[]}try{u.set(e,Fn(t,n),!1)}catch(t){console.error(`Error capping monomer at row ${e}`,t)}}const h=s.columns.names(),d=h.indexOf(Sn.MONOMER);if(d>=0){const e=h.filter(e=>e!==c);e.splice(d+1,0,c),s.columns.setOrder(e)}const m=e.toLowerCase().endsWith(".json")?e.replace(/\.json$/i,".csv"):`${e}.csv`;r.Utils.download(m,s.toCsv(),"text/csv")},m=s.iconFA("arrow-to-bottom",()=>{r.Menu.popup().item("JSON",()=>{h()}).item("CSV",()=>{d()}).show()},"Download Monomer Library");i.push([a,c,l,u,m]),this.tv.setRibbonPanels(i),this.tv.name=Ln.VIEW_NAME,this.libInput=s.input.choice("Monomer Library",{value:e,items:n,nullable:!1,onValueChanged:async()=>{try{if(this._skipLibInputOnchange)return;const e=await this.getMonomersDf(this.libInput.value);this.tv.dataFrame=e,this.adjustTable()}catch(e){console.error(e)}}}),this.libInput.addOptions(s.icons.add(()=>{this.createNewLibDialog()},"Create new monomer library..."));const p=this._newMonomerForm.form;return p.prepend(this.libInput.root),s.tools.waitForElementInDom(this.tv.root).then(()=>{this.tv.dockManager.dock(p,r.DOCK_TYPE.LEFT,null,void 0,.4)}),this.tv}async editMonomer(e){return this._newMonomer=await kn(e),this._newMonomerForm.setMonomer(this._newMonomer),this._newMonomer}async getMonomersDf(e){this.tv?.grid&&s.setUpdateIndicator(this.tv.grid.root,!0);try{let t=null;const n=await this.monomerLibManamger.getProviders();if(0===n.length)throw new Error("No monomer library providers available");if(e){if(t=await(0,ye.pY)(n,e),!t)throw new Error(`Library ${e} not found in any provider`)}else t=n[0],e=(await t.listLibraries())[0];if(this.activeMonomerLib=await this.monomerLibManamger.readSingleLibrary(t.name,e),!this.activeMonomerLib)return o.shell.error(`Library ${e} not found`),r.DataFrame.create();const i=this.activeMonomerLib.getPolymerTypes().flatMap(e=>this.activeMonomerLib.getMonomerSymbolsByType(e).map(t=>this.activeMonomerLib.getMonomer(e,t)));return await Pn(i)}catch(e){throw o.shell.error("Error creating monomers dataframe"),console.error(e),e}finally{this.tv?.grid&&s.setUpdateIndicator(this.tv.grid.root,!1)}}async fixAllMonomers(){s.dialog("Fix All Monomers").add(s.divText("This action will fix all monomers in the library, standardize their smiles, molblocks and r-groups, assign correct natural analogs and save the library.")).add(s.divText("Do you wish to continue?")).onOK(async()=>{const e=this.tv?.dataFrame,t=this.libInput.value;if(e&&t){this.tv?.grid&&s.setUpdateIndicator(this.tv.grid.root,!0);try{const n=await(0,ye.pY)(await this.monomerLibManamger.getProviders(),t);if(!n)throw new Error(`Library ${t} not found in any provider`);const i=(await Promise.all(new Array(e.rowCount).fill(0).map((t,n)=>kn(e.rows.get(n))))).map(e=>({...e,lib:void 0,wem:void 0}));await n.addOrUpdateLibrary(t,i),await this.monomerLibManamger.loadMonomerLib(!0),o.shell.v=await this.getViewRoot(t)}catch(e){o.shell.error("Error saving library"),console.error(e)}finally{this.tv?.grid&&s.setUpdateIndicator(this.tv.grid.root,!1)}}else o.shell.error("No monomer library loaded")}).show()}resetCurrentRowFollowing(){this._newMonomerForm.molChanged=!1}}function In(e){let t=e.replaceAll(/\[R[1-9]\]/g,e=>`[*:${e[2]}]`);return t=t.replaceAll(/\[\d\*\]/g,e=>`[*:${e[1]}]`),t.replaceAll(/\[\d\*\:\d\]/g,e=>`[*:${e[1]}]`)}const _n=["alternateId","capGroupName","capGroupSMILES","label"];function Nn(e,t){const n=Object.keys(e).find(e=>e.toLowerCase()===t.toLowerCase());if(n)return e[n]}function Rn(e,t,n){const i=Object.keys(e).find(e=>e.toLowerCase()===t.toLowerCase());i?e[i]=n:e[t]=n}function $n(e){return e.map(e=>{const t=function(e,t){const n={};return e.forEach(e=>{const i=Object.keys(t).find(t=>t.toLowerCase()===e.toLowerCase());i&&(n[e]=t[i])}),n}(_n,e),n=Nn(t,"capGroupSMILES"),i=Nn(t,"alternateId"),o=Nn(t,"capGroupName"),s=Nn(t,"label")??"R1";if(n&&i&&o||s.length<2)return t;if(i&&-1!==i.indexOf(`${s}-`)){const e=i.replace(`${s}-`,"");o||(t.capGroupName=e),n||(t.capGroupSMILES=`[*:${s.substring(1)}][${e}]`)}else o&&(n||(t.capGroupSMILES=`[*:${s.substring(1)}][${o}]`),i||(t.alternateId=`${s}-${o}`));return t}).sort((e,t)=>e.label?.localeCompare(t.label??"")??0)}class On{monomerLibManager;getMonomerLib;refreshTable;getMonomersDataFrame;molSketcher;monomerTypeInput;polymerTypeInput;monomerSymbolInput;monomerNameInput;monomerIdInput;monomerNaturalAnalogInput;rgroupsGrid;metaGrid;colors;colorsEditor;saveButton;rgroupsGridRoot;_molChanged=!1;get molChanged(){return this._molChanged}set molChanged(e){this._molChanged=e}saveValidationResult=null;triggerMolChange=!0;inputsTabControl;constructor(e,t,n,i){this.monomerLibManager=e,this.getMonomerLib=t,this.refreshTable=n,this.getMonomersDataFrame=i,this.colors={line:"#000000",background:"#000000",text:"#000000"},this.colorsEditor=new Gn(this.colors),this.molSketcher=new r.chem.Sketcher,this.molSketcher.root.classList.add("monomer-manager-sketcher"),this.polymerTypeInput=s.input.choice("Polymer Type",{value:"PEPTIDE",items:["PEPTIDE","RNA","CHEM","BLOB","G"],onValueChanged:()=>this.onMonomerInputChanged(),nullable:!1}),this.monomerTypeInput=s.input.choice("Monomer Type",{value:"Backbone",items:["Backbone","Branch","Terminal"],onValueChanged:()=>this.onMonomerInputChanged(),nullable:!1}),this.monomerSymbolInput=s.input.string("Monomer Symbol",{nullable:!1,onValueChanged:()=>this.onMonomerInputChanged()}),this.monomerNameInput=s.input.string("Monomer Name",{nullable:!1,onValueChanged:()=>this.onMonomerInputChanged()}),this.monomerNameInput.nullable=!1,this.monomerIdInput=s.input.int("Monomer ID",{nullable:!0,value:0,onValueChanged:()=>this.onMonomerInputChanged()}),this.monomerNaturalAnalogInput=s.input.string("Natural Analog",{nullable:!0,onValueChanged:()=>this.onMonomerInputChanged()}),this.saveButton=s.bigButton("Save",async()=>{const e=this.validateInputs();e?o.shell.warning(e):await this.saveMonomer()}),this.molSketcher.subs.push(this.molSketcher.onChanged.subscribe(async()=>{if(this.triggerMolChange){try{this.rgroupsGridRoot.style.display="none";const e=this.inputsTabControl.panes.find(e=>"r-groups"===e.name?.toLowerCase());e&&e.header.style.removeProperty("background-color");let t=this.molSketcher.getSmiles();if(!t)return this.rgroupsGrid.items=[],this.rgroupsGrid.render(),this.saveValidationResult="Monomer molecule is required",void this.invalidateSaveButton();t=Hn([],t);const n=this.findRgroupsInSmiles(t);if(0===n.length)return this.rgroupsGrid.items=[],this.rgroupsGrid.render(),this.saveValidationResult="At least one R-group is required",e&&e.header.style.setProperty("background-color","#ff000030"),void this.invalidateSaveButton();if(new Set(n.map(e=>e[0])).size!==n.length)return this.saveValidationResult="Duplicate R-groups are not allowed",this.rgroupsGridRoot.style.display="flex",e&&e.header.style.setProperty("background-color","#ff000030"),void this.invalidateSaveButton();const i=n.map(e=>Number.parseInt(e[0].match(/[1-9]/g)[0])).map(e=>this.rgroupsGrid.items.find(t=>t.label===`R${e}`)??{capGroupSMILES:`[*:${e}][H]`,alternateId:`R${e}-H`,capGroupName:"H",label:`R${e}`});this.rgroupsGrid.items=i.sort((e,t)=>e.label?.localeCompare(t.label??"")??0),this.rgroupsGrid.render(),this.rgroupsGridRoot.style.display="flex";const o=await Lt(Fn(t,i),this.polymerTypeInput.value??"");o&&(this.monomerNaturalAnalogInput.value=o)}catch(e){console.error(e)}this.onMonomerInputChanged(),this._molChanged=!0}else this.triggerMolChange=!0}));const a=[r.Property.js("capGroupSMILES",r.TYPE.STRING,{caption:"R-group SMILES",nullable:!1}),r.Property.js("alternateId",r.TYPE.STRING,{caption:"Alternate ID",nullable:!1}),r.Property.js("capGroupName",r.TYPE.STRING,{caption:"R-group name",nullable:!1}),r.Property.js("label",r.TYPE.STRING,{fieldName:"R-group Label",nullable:!1,userEditable:!1})];this.rgroupsGrid=new Mt(a,[],{allowAdd:!1,allowRemove:!1,validators:{capGroupSMILES:e=>e?o.chem.checkSmiles(e)?null:"Invalid SMILES":"Cap group smiles is required",alternateId:e=>e?null:"Alternate ID is required",capGroupName:e=>e?null:"Cap group name is required",label:e=>e?null:"R-group label is required"},customLabels:{capGroupSMILES:"R-group SMILES",alternateId:"Alternate ID",capGroupName:"Cap Group Name",label:"Label"}}),this.rgroupsGrid.onItemChanged.subscribe(()=>this.onMonomerInputChanged()),this.rgroupsGridRoot=s.divV([this.rgroupsGrid.root]),this.rgroupsGridRoot.style.display="none";const l=[r.Property.js("Property",r.TYPE.STRING,{caption:"Property",nullable:!0}),r.Property.js("Value",r.TYPE.STRING,{caption:"Value",nullable:!0})];this.metaGrid=new Mt(l,[]),this.onMonomerInputChanged();const c=s.divV([this.polymerTypeInput,this.monomerTypeInput,this.monomerSymbolInput,this.monomerNameInput,this.monomerIdInput,this.monomerNaturalAnalogInput]);this.inputsTabControl=s.tabControl({Monomer:c,"R-groups":this.rgroupsGridRoot,Meta:s.divV([this.metaGrid.root]),Colors:this.colorsEditor.form},!1)}invalidateSaveButton(){this.saveValidationResult?this.saveButton.classList.add("d4-disabled"):this.saveButton.classList.remove("d4-disabled")}onMonomerInputChanged(){setTimeout(()=>{this.saveValidationResult=this.validateInputs(),this.invalidateSaveButton();const e=this.polymerTypeInput.value&&this.polymerTypeInput.value&&!!this.getMonomerLib()?.getMonomer(this.polymerTypeInput.value,this.monomerSymbolInput.value);this.saveButton.textContent=e?"Save Monomer":"Add Monomer"},200)}setEmptyMonomer(){this.triggerMolChange=!1,this.molSketcher.setSmiles(""),this.monomerSymbolInput.value="",this.monomerNameInput.value="",this.monomerIdInput.value=null,this.monomerNaturalAnalogInput.value=null,this.rgroupsGrid.items=[],this.metaGrid.items=[],this.rgroupsGrid.render(),this.metaGrid.render(),this.rgroupsGridRoot.style.display="none",this.onMonomerInputChanged(),this.colorsEditor.colors={line:"#000000",background:"#000000",text:"#000000"}}setMonomer(e){this.triggerMolChange=!1,this.molSketcher.setSmiles(e.smiles),this.polymerTypeInput.value=e.polymerType,this.monomerTypeInput.value=e.monomerType,this.monomerSymbolInput.value=e.symbol,this.monomerNameInput.value=e.name,this.monomerIdInput.value=e.id,this.monomerNaturalAnalogInput.value=e.naturalAnalog??null,this.rgroupsGrid.items=$n(e.rgroups),this.metaGrid.items=Object.entries(e.meta??{}).filter(([e,t])=>"colors"!==e?.toLowerCase()).map(([e,t])=>({Property:e,Value:t})),this.rgroupsGrid.render(),this.metaGrid.render(),this.rgroupsGridRoot.style.display="flex",this.onMonomerInputChanged(),!e.naturalAnalog&&e.polymerType&&Lt(Fn(e.smiles,this.rgroupsGrid.items),e.polymerType).then(e=>{e&&(this.monomerNaturalAnalogInput.value=e)});const t=e.meta?.colors??"";let n={};try{n=t?JSON.parse(t)?.default:{}}catch(e){console.error(e)}this.colorsEditor.colors={line:n.line??"#000000",background:n.background??"#000000",text:n.text??"#000000"}}validateInputs(){const e=this.inputsTabControl.panes.find(e=>"r-groups"===e.name?.toLowerCase());if(e&&e.header.style.removeProperty("background-color"),!this.molSketcher.getSmiles())return"Monomer Molecule field is required";for(const e of[this.polymerTypeInput,this.monomerTypeInput,this.monomerSymbolInput,this.monomerNameInput])if(null==e.value||""===e.value)return`${e.caption} field is required`;let t=null;if(this.rgroupsGrid.items.length<1&&(t="At least one R-group is required"),!t)e:for(const e of this.rgroupsGrid.items)for(const[n,i]of Object.entries(e))if(!i){t=`R-group ${n} field is required for ${e.label}`;break e}return!t&&this.rgroupsGrid.hasErrors()&&(t="R-group fields contain errors"),t?(e&&e.header.style.setProperty("background-color","#ff000030"),t):null}findRgroupsInSmiles(e){return[...Array.from(e.matchAll(/\[[1-9]\*\]/g)),...Array.from(e.matchAll(/\[\*\:[1-9]\]/g))]}get form(){this.inputsTabControl.root.classList.add("monomer-manager-form-tab-control"),this.inputsTabControl.header.style.marginBottom="10px";const e=s.buttonsInput([this.saveButton]);return s.tooltip.bind(e,()=>this.saveValidationResult??"Save monomer to library"),s.divV([this.molSketcher.root,this.inputsTabControl.root,e],{classes:"ui-form",style:{paddingLeft:"10px",overflow:"scroll",maxWidth:"unset"}})}get fieldInputs(){return{molecule:this.molSketcher,polymerType:this.polymerTypeInput,monomerType:this.monomerTypeInput,symbol:this.monomerSymbolInput,name:this.monomerNameInput,id:this.monomerIdInput,naturalAnalog:this.monomerNaturalAnalogInput}}get metaInputs(){return[]}get rgroupInputs(){return[]}getMonomerInfoTable(e){const t=Hn(e.rgroups,e.smiles,e.molfile),n=o.chem.drawMolecule(t,150,150),i=s.tableFromMap({name:e.name,author:e.author,createDate:e.createDate});return s.divH([n,i],{style:{alignItems:"center"}})}async removeMonomers(e,t,n=!0){const i=await(0,ye.pY)(await this.monomerLibManager.getProviders(),t);if(!i)return void o.shell.error(`Library ${t} not found in any provider`);const r=s.divV(e.map(e=>this.getMonomerInfoTable(e)),{style:{maxHeight:"500px",overflow:"scroll"}}),a=e.length>1,l=a?`Are you sure you want to remove monomers ${e.map(e=>e.symbol).join(", ")} from ${t} library?`:`Are you sure you want to remove monomer with symbol ${e[0].symbol} from ${t} library?`,c=s.dialog("Remove Monomer"+(a?"s":"")).add(s.h1(l)).add(r).addButton("Remove",async()=>{await i.deleteMonomersFromLibrary(t,e),await this.monomerLibManager.loadMonomerLib(!0),await this.refreshTable(),n&&o.shell.info(`Monomer${a?"s":""} ${e.map(e=>e.symbol).join(", ")} ${a?"were":"was"} successfully removed from ${t} library`),c.close()}).show()}async addMonomerToLib(e,t){const n=this.getMonomersDataFrame();if(!n)return void o.shell.error("No monomer library loaded");const i=n?.col(Sn.POLYMER_TYPE)?.toList()??[],r=n?.col(Sn.SYMBOL)?.toList()??[],a=n?.col(Sn.MONOMER)?.toList()??[];if(i.length!==r.length||i.length!==a.length)return void o.shell.error("Monomer library data frame is corrupted");const l=i.findIndex((t,n)=>t===e.polymerType&&r[n]===e.symbol),c=a.findIndex(t=>t===e.smiles),u=async()=>{try{const n=await(0,ye.pY)(await this.monomerLibManager.getProviders(),t);if(!n)return void o.shell.error(`Library ${t} not found in any provider`);await n.updateOrAddMonomersInLibrary(t,[{...e,lib:void 0,wem:void 0}]),await this.monomerLibManager.loadMonomerLib(!0),await this.refreshTable(e.symbol),this._molChanged=!1,o.shell.info(`Monomer ${e.symbol} was successfully saved in library ${t}`)}catch(e){o.shell.error("Error saving monomer"),console.error(e)}this.onMonomerInputChanged()};let h=null,d="";if(l>=0)h=this.getMonomerInfoTable(await kn(n.row(l))),d=`Monomer with symbol '${e.symbol}' already exists in library ${t}.\nAre you sure you want to overwrite it?`;else if((c??-1)>=0){const e=await kn(this.getMonomersDataFrame().rows.get(c));h=this.getMonomerInfoTable(e),d=`Monomer with the same structure already exists in library ${t} with different symbol (${e.symbol}).\nAre you sure you want to duplicate it?`}if(h){const e=s.dialog("Save Monomer").add(s.divText(d)).add(h).addButton("Save",()=>{e.close(),u()}).show()}else await u()}async saveMonomer(){let e=this.molSketcher.getSmiles();if(!e||!o.chem.checkSmiles(e))return void o.shell.warning("Invalid SMILES");e=Hn([],e);let t=o.chem.convert(e,r.chem.Notation.Smiles,r.chem.Notation.MolBlock);t=Dn(t);const n={};this.metaGrid.items.filter(e=>!!e.Property&&!!e.Value).forEach(e=>{n[e.Property]=e.Value});const i=this.metaGrid.addingItem;i&&i.Property&&i.Value&&(n[i.Property]=i.Value),"#000000"===this.colorsEditor.colors.line&&"#000000"===this.colorsEditor.colors.background&&"#000000"===this.colorsEditor.colors.text||(n.colors={default:this.colorsEditor.colors});const s={symbol:this.monomerSymbolInput.value,name:this.monomerNameInput.value,molfile:t,smiles:e,polymerType:this.polymerTypeInput.value,monomerType:this.monomerTypeInput.value,naturalAnalog:this.monomerNaturalAnalogInput.value?this.monomerNaturalAnalogInput.value:void 0,id:this.monomerIdInput.value??0,rgroups:this.rgroupsGrid.items,author:r.User.current().friendlyName,createDate:(new Date).toISOString(),meta:n},a=this.getMonomerLib()?.source;a?await this.addMonomerToLib(s,a):o.shell.warning("Monomer library source is not specified")}}function Hn(e,t,n){t&&(t=function(e){return e.replaceAll(/\[Allyl\:\d\]/g,e=>`[*:${e[e.length-2]}]`)}(t));const i=!t||!o.chem.checkSmiles(t);if(i&&!n)throw new Error("Both SMILES and MOL block are empty or malformed");let s=i?o.chem.convert(n,r.chem.Notation.Unknown,r.chem.Notation.Smiles):t;return s=function(e,t){let n=e;return t.forEach(e=>{const t=e.label[1]??"1";n=n.replace(`[${e.capGroupName}:${t}]`,`[*:${t}]`)}),n=n.replaceAll(/\[\d[A-Z]{1,2}\]/g,e=>`[*:${e[1]}]`),n}(s,e),s=In(s),i?s:o.chem.convert(s,r.chem.Notation.Unknown,r.chem.Notation.Smiles)}function Dn(e){const t=e.split("\n"),n=t.findIndex(e=>e.startsWith("M")&&e.includes("ISO"));if(-1!==n){const e=t[n].trim().split(" ").filter(Boolean);if(e.length>=5&&Number.parseInt(e[4])<9){const e=t[n].indexOf("ISO");t[n]=t[n].substring(0,e)+"RGP"+t[n].substring(e+3)}}const i=t.findIndex(e=>e.includes("V2000"));if(-1===i)return console.error("Mol start line not found"),e;const o=Number.parseInt(t[i].trim().split(" ")[0].slice(0,3).trim()),s={};for(let e=i+1;e<i+1+o;e++){const n=t[e].indexOf("R ");if(-1===n)continue;"#"!==t[e][n+1]&&(t[e]=t[e].replace("R ","R#"));const o=t[e].trim().split(" ").map(e=>e.trim()).filter(Boolean);if(s[e-i]=1,o.length<14)continue;const r=Number.parseInt(o[13]);Number.isNaN(r)||(s[e-i]=r)}const r=Object.keys(s);if(-1===t.findIndex(e=>e.startsWith("M")&&e.includes("RGP"))){const e=`M RGP${r.length.toString().padStart(3," ")}${Object.entries(s).map(([e,t])=>`${e.toString().padStart(4," ")}${t.toString().padStart(4," ")}`).join("")}`,n=t.findIndex(e=>e.startsWith("M")&&e.includes("END"));t.splice(n,0,e)}return r.filter(e=>!!Number.parseInt(e)).map(e=>Number.parseInt(e)+i).forEach(e=>{const n=t[e].split(" "),i=n.findIndex(e=>"R#"===e);if(-1!==i){for(let e=i+1;e<n.length;e++)n[e]&&1==n[e].length&&(Number.parseInt(n[e])??0)>0&&(n[e]="0");t[e]=n.join(" ")}}),t.join("\n")}function Fn(e,t){let n=e;return t.forEach((e,t)=>{const i=e.label[1]??`${t+1}`,o=Nn(e,"capGroupName"),s=Nn(e,"capGroupSMILES");n="allyl"===o?.toLowerCase()||"c=c"===s?.replace(`[*:${i}]`,"")?.toLowerCase()||"[c=c]"===s?.replace(`[*:${i}]`,"")?.toLowerCase()?n.replace(`[*:${i}]`,"C=C"):n.replace(`[*:${i}]`,`[${o}]`)}),n}async function kn(e){let t;try{t=JSON.parse(e.get(Sn.META)??"{}");for(const e in t)"object"==typeof t[e]&&(t[e]=JSON.stringify(t[e])),("string"!=typeof t[e]||t[e]!==r.INT_NULL.toString()&&t[e]!==r.FLOAT_NULL.toString())&&("number"!=typeof t[e]||t[e]!==r.INT_NULL&&t[e]!==r.FLOAT_NULL)||(t[e]=null)}catch(e){console.error(e)}const n=e.get(Sn.MONOMER);if(!n)throw new Error("Monomer SMILES is empty");let i="";try{i=o.chem.convert(n,r.chem.Notation.Smiles,r.chem.Notation.MolBlock),i=Dn(i)}catch(e){o.shell.error(`Error converting SMILES to molfile, \n ${n}`),console.error(e)}let s=e.get(Sn.NATURAL_ANALOG);const a=e.get(Sn.POLYMER_TYPE);let l=[];try{l=JSON.parse(e.get(Sn.R_GROUPS)??"[]")}catch(e){l??=[]}!function(e){function t(e,t){return e.replace(/\[([A-Z][a-z]?):(\d+)\]/g,(e,n,i)=>parseInt(i)===t?`${n?.toLowerCase&&"h"===n?.toLowerCase()?"[H]":n}[*:${i}]`:e)}e.forEach((e,n)=>{const i=Nn(e,"capGroupSMILES"),o=e.label[1]??`${n+1}`;if(!i||i.includes(`[*:${o}]`))return;const s=new RegExp(`\\[[A-Za-z]{1,2}:${o}\\]`);i.includes(`[*${o}]`)?Rn(e,"capGroupSMILES",i.replace(`[*${o}]`,`[*:${o}]`)):i.includes(`[R${o}]`)?Rn(e,"capGroupSMILES",i.replace(`[R${o}]`,`[*:${o}]`)):s.test(i)?Rn(e,"capGroupSMILES",t(i,Number.parseInt(o))):`[${i}]`.match(s)?.[0].length===i.length+2&&Rn(e,"capGroupSMILES",t(`[${i}]`,Number.parseInt(o)))}),e.forEach(e=>{const t=Nn(e,"capGroupSMILES"),n=t.match(/\[\*\:?(\d+)\]/);n&&t===n[0]&&Rn(e,"capGroupSMILES",`${Nn(e,"capGroupName")}${t}`)})}(l);try{if(!s&&a){const e=await Lt(Fn(n,l),a);e&&(s=e)}}catch(e){console.error(e)}return{symbol:e.get(Sn.SYMBOL),name:e.get(Sn.NAME),molfile:i,smiles:n,polymerType:a,monomerType:e.get(Sn.MONOMER_TYPE),naturalAnalog:s,id:e.get(Sn.ID),rgroups:l,meta:t,author:e.get(Sn.AUTHOR),createDate:e.get(Sn.CREATE_DATE)}}class Gn{_colors;_colorInputs;constructor(e){this._colors=e,this._colorInputs={line:s.input.color("Line",{value:e.line,onValueChanged:e=>this._colors.line=e}),background:s.input.color("Background",{value:e.background,onValueChanged:e=>this._colors.background=e}),text:s.input.color("Text",{value:e.text,onValueChanged:e=>this._colors.text=e})}}get colors(){return this._colors}set colors(e){const t={line:r.Color.toHtml(r.Color.fromHtml(e.line??"#000000")),background:r.Color.toHtml(r.Color.fromHtml(e.background??"#000000")),text:r.Color.toHtml(r.Color.fromHtml(e.text??"#000000"))};this._colors=t;for(const e in this._colorInputs)this._colorInputs[e].value=t[e]}get colorsMetaFormat(){return{colors:{default:this._colors}}}get form(){return s.form(Object.values(this._colorInputs))}}function Bn(e){const t={Symbol:e.symbol,Name:e.name,"Polymer Type":e.polymerType,"Monomer Type":e.monomerType};if(e.author&&(t.Author=e.author),e.naturalAnalog&&(t["Natural Analog"]=e.naturalAnalog),e.lib?.source){let n=e.lib.source;n.endsWith(".json")&&(n=n.substring(0,n.length-5)),t.Library=n}e.molfile?t.Structure=o.chem.drawMolecule(e.molfile,150,150):e.smiles&&(t.Structure=o.chem.drawMolecule(e.smiles,150,150));const n=e.rgroups;if(n&&n.length>0)for(const e of n)t[e.label??"?"]=e.alternateId??"";return s.tableFromMap(t)}function Vn(e){const t=function(e){try{return Fn(Hn(e.rgroups,e.smiles,e.molfile),e.rgroups)}catch{}return null}(e);if(!t)return s.divText("No molecular structure available");const n=r.SemanticValue.fromValueType(t,r.SEMTYPE.MOLECULE);return s.panels.infoPanel(n).root}var Un=n(3890),qn=n(1687);function Wn(e){return e.split(/,(?![^(]*\))/).map(e=>('"'===(e=e.trim()).slice(0,1)&&'"'===e.slice(-1)&&(e=e.slice(1,-1)),"'"===e.slice(0,1)&&"'"===e.slice(-1)&&(e=e.slice(1,-1)),e.trim())).filter(e=>!!e)}class Yn{constructor(e,t,n,i){this.currentMenu=null,this.menuItems=[],this.highlightedIndex=-1,this.monomerLib=e,this.polymerType=t,this.helmType=(0,Oe.MD)(t),this.allSymbols=e.getMonomerSymbolsByType(t),this.libHelper=i,this.selectedMonomers=n?[...n]:[],this.tagsHost=s.div([],{style:{display:"flex",flexWrap:"wrap",gap:"4px",marginTop:"4px",maxHeight:"150px",overflowY:"auto"}}),this.countLabel=s.divText("",{style:{fontSize:"11px",color:"var(--grey-4)",marginTop:"4px"}});const o=s.input.string("Search",{value:""});this.inputEl=o.input,this.inputEl.setAttribute("autocomplete","off"),this.inputEl.placeholder="Type to search monomers...",this.setupInputListeners();const r=this.createLibrarySection(),a=this.createCollectionSection(),l=s.button("Clear all",()=>{this.selectedMonomers.length=0,this.renderTags()});l.style.fontSize="11px",l.style.marginTop="4px",this.renderTags(),this.root=s.div([o.root,r,a,s.divH([this.countLabel,l],{style:{justifyContent:"space-between",alignItems:"center"}}),this.tagsHost],{style:{minWidth:"300px"}})}getSelectedMonomers(){return[...this.selectedMonomers]}setSelectedMonomers(e){this.selectedMonomers.length=0,this.selectedMonomers.push(...e),this.renderTags()}setPolymerType(e){this.polymerType=e,this.helmType=(0,Oe.MD)(e),this.allSymbols=this.monomerLib.getMonomerSymbolsByType(e)}focus(){this.inputEl.focus()}updateCountLabel(){this.countLabel.textContent=this.selectedMonomers.length>0?`${this.selectedMonomers.length} monomer(s) selected`:""}renderTags(){this.tagsHost.innerHTML="";for(const e of this.selectedMonomers){const t=s.iconFA("times",()=>{const t=this.selectedMonomers.indexOf(e);t>=0&&(this.selectedMonomers.splice(t,1),this.renderTags(),this.updateCountLabel())},"Remove");t.style.marginLeft="4px",t.style.cursor="pointer";const n=s.div([s.span([e]),t],{style:{display:"inline-flex",alignItems:"center",padding:"2px 6px",borderRadius:"4px",backgroundColor:"var(--grey-2)",border:"1px solid var(--grey-3)",fontSize:"12px",cursor:"default"}});n.addEventListener("mouseenter",()=>{const t=this.monomerLib.getTooltip(this.helmType,e);s.tooltip.show(t,n.getBoundingClientRect().left,n.getBoundingClientRect().bottom+16)}),n.addEventListener("mouseleave",()=>{s.tooltip.hide()}),this.tagsHost.appendChild(n)}this.updateCountLabel()}addMonomer(e){this.selectedMonomers.includes(e)||(this.selectedMonomers.push(e),this.renderTags()),this.inputEl.value="",this.hideMenu(),this.inputEl.focus()}addMonomers(e){let t=!1;for(const n of e)this.selectedMonomers.includes(n)||(this.selectedMonomers.push(n),t=!0);t&&this.renderTags()}hideMenu(){this.currentMenu&&(this.currentMenu.hide(),this.currentMenu=null),this.menuItems=[],this.highlightedIndex=-1}getSuggestions(e){const t=e.toLowerCase(),n=[];for(const e of this.allSymbols){if(this.selectedMonomers.includes(e))continue;const i=this.monomerLib.getMonomer(this.polymerType,e),o=e.toLowerCase(),s=i?.name?.toLowerCase()??"";o.startsWith(t)?n.push({symbol:e,monomer:i,rank:0}):o.includes(t)?n.push({symbol:e,monomer:i,rank:1}):s.includes(t)&&n.push({symbol:e,monomer:i,rank:2})}return n.sort((e,t)=>e.rank-t.rank||e.symbol.localeCompare(t.symbol)),n.slice(0,20)}showSuggestions(){this.hideMenu();const e=this.inputEl.value.trim();if(!e)return;const t=this.getSuggestions(e);if(0===t.length)return;this.currentMenu=r.Menu.popup();const n=t.reduce((e,t)=>{const n=t.monomer?.name?`${t.symbol} - ${t.monomer.name}`:t.symbol;return e.length<n.length?n:e},"");this.currentMenu.item(n,()=>{});const i=new MouseEvent("mousemove",{clientX:this.inputEl.getBoundingClientRect().left,clientY:this.inputEl.getBoundingClientRect().bottom});this.currentMenu.show({causedBy:i,y:this.inputEl.offsetHeight+this.inputEl.offsetTop,x:this.inputEl.offsetLeft}),setTimeout(()=>{this.currentMenu?.clear();for(const e of t){const t=e.monomer?.name?`${e.symbol} - ${e.monomer.name}`:e.symbol;this.currentMenu?.item(t,()=>{this.addMonomer(e.symbol)})}const e=document.querySelector(".d4-menu-popup:last-of-type");e&&(this.menuItems=Array.from(e.querySelectorAll(".d4-menu-item"))),this.highlightedIndex=-1},0)}updateHighlight(e){0!==this.menuItems.length&&(this.highlightedIndex>=0&&this.highlightedIndex<this.menuItems.length&&this.menuItems[this.highlightedIndex].classList.remove("d4-menu-item-hover"),this.highlightedIndex=e,this.highlightedIndex>=0&&this.highlightedIndex<this.menuItems.length&&(this.menuItems[this.highlightedIndex].classList.add("d4-menu-item-hover"),this.menuItems[this.highlightedIndex].scrollIntoView({block:"nearest"})))}setupInputListeners(){this.inputEl.addEventListener("input",()=>{this.showSuggestions()}),this.inputEl.addEventListener("paste",e=>{const t=e.clipboardData?.getData("text");if(!t)return;const n=t.split(/[\n\r]+/).map(e=>e.trim()).filter(e=>e.length>0),i=[];for(const e of n){const t=Wn(e);1===t.length&&e.includes(" ")&&!e.includes(",")?i.push(...e.split(/\s+/).map(e=>e.trim()).filter(e=>e.length>0)):i.push(...t)}if(!(i.length<=1)){e.preventDefault();for(const e of i)this.selectedMonomers.includes(e)||this.selectedMonomers.push(e);this.renderTags(),this.inputEl.value="",this.hideMenu(),this.inputEl.focus()}}),this.inputEl.addEventListener("keydown",e=>{if("ArrowDown"===e.key){if(e.preventDefault(),this.menuItems.length>0){const e=(this.highlightedIndex+1)%this.menuItems.length;this.updateHighlight(e)}}else if("ArrowUp"===e.key){if(e.preventDefault(),this.menuItems.length>0){const e=(this.highlightedIndex-1+this.menuItems.length)%this.menuItems.length;this.updateHighlight(e)}}else if("Enter"===e.key)if(e.preventDefault(),e.stopPropagation(),this.highlightedIndex>=0&&this.highlightedIndex<this.menuItems.length)this.menuItems[this.highlightedIndex].click();else{const e=this.inputEl.value.trim();e&&this.addMonomer(e)}else"Escape"===e.key&&this.hideMenu()})}createLibrarySection(){const e=s.div([],{style:{marginTop:"8px"}});if(!this.libHelper)return e;const t=this.libHelper,n=s.input.choice("Add from library",{items:[],nullable:!0}),i=s.divText("",{style:{fontSize:"11px",color:"var(--green-2)",marginLeft:"8px",minHeight:"16px"}});return t.getAvaliableLibraryNames().then(e=>{n.items=e}),n.onChanged.subscribe(async()=>{const e=n.value;if(e){i.textContent="Loading...";try{const n=await t.readSingleLibraryByName(e);if(n){const t=n.getMonomerSymbolsByType(this.polymerType),o=this.selectedMonomers.length;this.addMonomers(t);const s=this.selectedMonomers.length-o;i.textContent=`Added ${s} monomer(s) from "${e}"`}else i.textContent=`Library "${e}" not found`}catch(e){i.textContent="Error loading library"}n.value=null,setTimeout(()=>{i.textContent=""},4e3)}}),e.appendChild(s.divV([n.root,i])),e}createCollectionSection(){const e=s.div([],{style:{marginTop:"4px"}});if(!this.libHelper)return e;const t=this.libHelper,n=s.input.choice("Add from collection",{items:[],nullable:!0}),i=s.divText("",{style:{fontSize:"11px",color:"var(--green-2)",marginLeft:"8px",minHeight:"16px"}});return t.listMonomerCollections().then(e=>{n.items=e}),n.onChanged.subscribe(async()=>{const e=n.value;if(e){i.textContent="Loading...";try{const n=(await t.readMonomerCollection(e)).monomerSymbols??[],o=this.selectedMonomers.length;this.addMonomers(n);const s=this.selectedMonomers.length-o,r=e.replace(/\.json$/,"");i.textContent=`Added ${s} monomer(s) from "${r}"`}catch(e){i.textContent="Error loading collection"}n.value=null,setTimeout(()=>{i.textContent=""},4e3)}}),e.appendChild(s.divV([n.root,i])),e}}class jn extends r.ObjectHandler{get type(){return"MonomerCollection"}get name(){return"Monomer Collection"}isApplicable(e){return Array.isArray(e)?e.length>0&&e.every(e=>this.isSingleCollection(e)):this.isSingleCollection(e)}isSingleCollection(e){return null!=e&&"object"==typeof e&&"name"in e&&"displayName"in e&&"data"in e&&void 0!==e.data?.monomerSymbols}getCaption(e){return Array.isArray(e)?`${e.length} collections`:e.displayName}renderProperties(e,t=null){return Array.isArray(e)?this.renderMultiProperties(e):this.renderSingleProperties(e)}renderSingleProperties(e){const t=s.accordion("Monomer Collection"),n=r.User.current().login,i=e.data.updatedBy===n;return t.addPane("Details",()=>{const t={Name:e.displayName};if(e.data.description&&(t.Description=e.data.description),e.data.tags&&e.data.tags.length>0&&(t.Tags=e.data.tags.join(", ")),t.Monomers=`${e.data.monomerSymbols.length}`,e.data.updatedBy&&(t["Updated by"]=e.data.updatedBy),e.data.updatedOn)try{t["Updated on"]=new Date(e.data.updatedOn).toLocaleString()}catch{}return s.tableFromMap(t)},!0),t.addPane("Monomers",()=>{const t=s.div([],{style:{display:"flex",flexWrap:"wrap",gap:"4px"}}),n=this.getMonomerLib();for(const i of e.data.monomerSymbols){const e=s.div([i],{style:{display:"inline-block",padding:"2px 8px",borderRadius:"4px",background:"var(--grey-1)",border:"1px solid var(--grey-2)",fontSize:"11px",color:"var(--grey-5)",cursor:"pointer"}});e.addEventListener("mouseenter",()=>{if(n){const t=jn.getMonomerTooltipSafe(n,i);if(t){const n=e.getBoundingClientRect();s.tooltip.show(t,n.left,n.bottom+4)}}}),e.addEventListener("mouseleave",()=>s.tooltip.hide()),e.addEventListener("click",()=>{o.shell.o=r.SemanticValue.fromValueType(i,Ve.uF.MONOMER)}),t.appendChild(e)}return t},!0),t.addPane("Actions",()=>{const t=[],n=s.button("Edit",async()=>{i&&await this.editCollection(e)},i?"Edit this collection":"Only the author can edit");i||jn.disableButton(n),t.push(n);const o=s.button("Delete",async()=>{i&&await this.deleteCollection(e)},i?"Delete this collection":"Only the author can delete");return i||jn.disableButton(o),t.push(o),t.push(s.button("Duplicate",async()=>{await this.duplicateCollection(e)},"Create a copy of this collection")),s.divH(t)},!0),t.root}renderMultiProperties(e){const t=s.accordion("Monomer Collections"),n=r.User.current().login,i=e.every(e=>e.data.updatedBy===n);return t.addPane("Selection",()=>{const t=s.list(e.map(e=>e.displayName));return s.divV([s.divText(`${e.length} collections selected`),t])},!0),t.addPane("Actions",()=>{const t=[];t.push(s.button("Merge",async()=>{await this.mergeCollections(e)},"Merge selected collections into one"));const n=s.button("Delete All",async()=>{i&&await this.deleteMultipleCollections(e)},i?"Delete all selected collections":"Only the author can delete (you must be author of all)");return i||jn.disableButton(n),t.push(n),s.divH(t)},!0),t.root}async editCollection(e){const t=Array.from(o.shell.views).find(e=>"Monomer Collections"===e.name);if(t&&t._mcView)t._mcView.editCollectionPublic(e.name,e.data);else{const t=await bn.getInstance();await t.awaitLoaded();const n=t.getMonomerLib();this.showEditDialog(e,t,n)}}showEditDialog(e,t,n){const i=s.input.string("Name",{value:e.displayName,nullable:!1}),r=s.input.string("Description",{value:e.data.description??"",nullable:!0}),a=s.input.string("Tags",{value:(e.data.tags??[]).join(", "),nullable:!0,placeholder:"Comma-separated tags"}),l=s.input.choice("Polymer Type",{items:["PEPTIDE","RNA","CHEM"],value:"PEPTIDE",nullable:!1}),c=new Yn(n,l.value,[...e.data.monomerSymbols??[]],t);l.onChanged.subscribe(()=>c.setPolymerType(l.value)),s.dialog({title:`Edit Collection: ${e.displayName}`}).add(s.divV([i,r,a,l,s.element("hr"),c.root])).onOK(async()=>{const n=i.value?.trim();if(!n)return void o.shell.warning("Collection name is required");const s=c.getSelectedMonomers();if(0===s.length)return void o.shell.warning("Please select at least one monomer");const l=this.parseTags(a.value);try{n!==e.displayName&&await t.deleteMonomerCollection(e.name),await t.addOrUpdateMonomerCollection(n,s,r.value??void 0,l.length>0?l:void 0),o.shell.info(`Collection "${n}" saved successfully`),await this.refreshView()}catch(e){o.shell.error("Error saving collection")}}).show({resizable:!0}).root.style.width="550px",c.focus()}async deleteCollection(e){s.dialog({title:"Delete Collection"}).add(s.divText(`Are you sure you want to delete "${e.displayName}"?`)).onOK(async()=>{try{const t=await bn.getInstance();await t.deleteMonomerCollection(e.name),o.shell.info(`Collection "${e.displayName}" deleted`),await this.refreshView()}catch(e){o.shell.error("Error deleting collection")}}).show()}async duplicateCollection(e){const t=s.input.string("New Name",{value:`${e.displayName} (copy)`,nullable:!1});s.dialog({title:"Duplicate Collection"}).add(t).onOK(async()=>{const n=t.value?.trim();if(n)try{const t=await bn.getInstance();await t.addOrUpdateMonomerCollection(n,[...e.data.monomerSymbols],e.data.description,e.data.tags?[...e.data.tags]:void 0),o.shell.info(`Collection "${n}" created`),await this.refreshView()}catch(e){o.shell.error("Error duplicating collection")}else o.shell.warning("Name is required")}).show()}async mergeCollections(e){const t=s.input.string("Merged Name",{value:"Merged Collection",nullable:!1}),n=s.input.string("Description",{nullable:!0,placeholder:"Optional description"});s.dialog({title:`Merge ${e.length} Collections`}).add(s.divV([s.divText(`Merging: ${e.map(e=>e.displayName).join(", ")}`),t,n])).onOK(async()=>{const i=t.value?.trim();if(i)try{const t=[...new Set(e.flatMap(e=>e.data.monomerSymbols))],s=[...new Set(e.flatMap(e=>e.data.tags??[]))],r=await bn.getInstance();await r.addOrUpdateMonomerCollection(i,t,n.value??void 0,s.length>0?s:void 0),o.shell.info(`Merged collection "${i}" created with ${t.length} monomers`),await this.refreshView()}catch(e){o.shell.error("Error merging collections")}else o.shell.warning("Name is required")}).show()}async deleteMultipleCollections(e){s.dialog({title:"Delete Collections"}).add(s.divText(`Are you sure you want to delete ${e.length} collections?\n${e.map(e=>e.displayName).join(", ")}`)).onOK(async()=>{try{const t=await bn.getInstance();for(const n of e)await t.deleteMonomerCollection(n.name);o.shell.info(`${e.length} collections deleted`),await this.refreshView()}catch(e){o.shell.error("Error deleting collections")}}).show()}async refreshView(){const e=Array.from(o.shell.views).find(e=>"Monomer Collections"===e.name);if(e&&e._mcView){const t=e._mcView;await t.refresh()}}parseTags(e){return e?e.split(",").map(e=>e.trim()).filter(e=>e.length>0):[]}getMonomerLib(){return Uo.monomerLib??null}static getMonomerTooltipSafe(e,t){const n=[Fe.o.AA,Fe.o.NUCLEOTIDE,Fe.o.CHEM,Fe.o.BLOB];for(const i of n)try{if(e.getWebEditorMonomer(i,t))return e.getTooltip(i,t)}catch{}return null}static disableButton(e){e.style.opacity="0.4",e.style.cursor="default"}static buildContextMenu(e,t,n){const i=r.User.current().login,o=t.data.updatedBy===i;e.item("Edit",()=>{o&&n.editCollection(t)},null,{isEnabled:()=>o?null:"Only the author can edit"}),e.item("Delete",()=>{o&&n.deleteCollection(t)},null,{isEnabled:()=>o?null:"Only the author can delete"}),e.item("Duplicate",()=>n.duplicateCollection(t))}static buildMultiContextMenu(e,t,n){const i=r.User.current().login,o=t.every(e=>e.data.updatedBy===i);e.item("Merge",()=>n.mergeCollections(t)),e.item("Delete All",()=>{o&&n.deleteMultipleCollections(t)},null,{isEnabled:()=>o?null:"Only the author can delete (you must be author of all)"})}}var Kn=n(1757),zn=n.n(Kn);class Zn{monomer;root=s.divV([],{classes:"monomer-card-root"});_selected=!1;get selected(){return this._selected}set selected(e){this._selected=e,this.root.style.border=e?"2px solid var(--green-2)":"2px solid var(--grey-2)"}constructor(e){this.monomer=e}render(){s.empty(this.root);const e=this.monomer.smiles&&o.chem.checkSmiles(this.monomer.smiles)?o.chem.drawMolecule(this.monomer.smiles,200,200):o.chem.drawMolecule(this.monomer.molfile??"",200,200);this.root.appendChild(e);const t=s.divH([s.divText("Monomer Name: "),s.divText(this.monomer.name)],{classes:"monomer-card-info-row"});if(this.root.appendChild(t),s.tooltip.bind(t,this.monomer.name),this.monomer.lib?.source){const e=s.divH([s.divText("Source: "),s.divText(this.monomer.lib.source)],{classes:"monomer-card-info-row"});this.root.appendChild(e),s.tooltip.bind(e,this.monomer.lib.source)}const n=s.divH([s.divText("Polymer Type: "),s.divText(this.monomer.polymerType)],{classes:"monomer-card-info-row"});this.root.appendChild(n),s.tooltip.bind(n,this.monomer.polymerType),s.tooltip.bind(this.root,"Select Monomer")}}class Xn{monomerSymbol;monomers;root=s.divH([],{style:{alignItems:"center",width:"100%",overflow:"hidden",visibility:"visible"},classes:"duplicate-monomer-symbol-row"});monomerCards;constructor(e,t,n,i){this.monomerSymbol=e,this.monomers=t,this.monomerCards=t.map(e=>new Zn(e));const o=s.divH([],{style:{overflowX:"auto",width:"100%"}}),r=s.h1(e,{style:{lineHeight:"2em",fontSize:"1.5em",marginRight:"20px",width:"100px",overflow:"hidden",textOverflow:"elipsis"}});s.tooltip.bind(r,e),this.root.appendChild(r),this.root.appendChild(o),this.monomerCards.forEach(e=>{e.root.onclick=()=>{this.monomerCards.forEach(e=>e.selected=!1),e.selected=!0,i(e.monomer)},n&&e.monomer===n&&(e.selected=!0),o.appendChild(e.root)})}render(){this.monomerCards.forEach(e=>e.render())}}class Qn{monomerCardRows=[];saveSettingsPromise=Promise.resolve();searchInput;_root;monomers;settings;filteredMonomerRows=[];static _instance;vv;static async getInstance(){return Qn._instance||(Qn._instance=new Qn,await Qn._instance.refresh(),(await bn.getInstance()).getMonomerLib().onChanged.subscribe(async()=>await Qn._instance.refresh())),Qn._instance.refresh(),Qn._instance}async refresh(){this.settings=await(0,Le.u)();const e=await bn.getInstance();await e.awaitLoaded(),this.monomers=e.duplicateMonomers,this.monomerCardRows=[];for(const t in this.monomers)for(const n in this.monomers[t]){const i=this.settings.duplicateMonomerPreferences?.[t]?.[n]??null,s=i?this.monomers[t][n].find(e=>e.lib?.source===i)??null:null;this.monomerCardRows.push(new Xn(n,this.monomers[t][n],s,async i=>{this.saveSettingsPromise=this.saveSettingsPromise.then(async()=>{i.lib?.source&&(this.settings.duplicateMonomerPreferences=this.settings.duplicateMonomerPreferences??{},this.settings.duplicateMonomerPreferences[t]=this.settings.duplicateMonomerPreferences[t]??{},this.settings.duplicateMonomerPreferences[t][n]=i.lib.source,await(0,Le.E)(this.settings),e.assignDuplicatePreferances(this.settings),o.shell.info(`Monomer '${i.name}' from source '${i.lib.source}' selected for symbol '${n}'.`))})}))}const t=s.divText("Set Default");if(t.addEventListener("click",async()=>{if(0===Object.keys(this.monomers??{}).length)return void o.shell.info("No Duplicate Monomers found");const t=new Set;for(const e in this.monomers)for(const n in this.monomers[e])for(const i of this.monomers[e][n])i.lib?.source&&t.add(i.lib.source);if(0===t.size)return void o.shell.info("No Duplicate Monomers found");const n=Array.from(t),i=s.input.choice("Default Library",{items:n,nullable:!0});s.dialog("Set Default Monomer Source for Duplicates").add(i).onOK(async()=>{if(i.value){for(const e in this.monomers)for(const t in this.monomers[e]){const n=this.monomers[e][t];n?.some(e=>e.lib?.source===i.value)&&(this.settings.duplicateMonomerPreferences=this.settings.duplicateMonomerPreferences??{},this.settings.duplicateMonomerPreferences[e]=this.settings.duplicateMonomerPreferences[e]??{},this.settings.duplicateMonomerPreferences[e][t]=i.value)}await(0,Le.E)(this.settings),e.assignDuplicatePreferances(this.settings),o.shell.info(`Default Monomer Source for Duplicates set to '${i.value}'.`),setTimeout(()=>this.refresh(),100)}else o.shell.info("No library selected")}).show()}),this.filteredMonomerRows=this.monomerCardRows,this.vv)this.vv.setData(this.filteredMonomerRows.length,e=>(this.filteredMonomerRows[e].render(),this.filteredMonomerRows[e].root));else{this.vv=s.virtualView(this.monomerCardRows.length,e=>(this.monomerCardRows[e].render(),this.monomerCardRows[e].root)),this.vv.root.classList.add("duplicate-monomers-virtual-view"),this.searchInput=s.input.string("Search",{placeholder:"Monomer Symbol",value:"",onValueChanged:()=>e(this.searchInput.value)}),this.searchInput.root.style.justifyContent="center",this.searchInput.addOptions(t),this.searchInput.input.style.width="200px",this._root=s.divV([s.h1("Manage Duplicate Monomer Symbols",{style:{textAlign:"center"}}),this.searchInput.root,s.divV([this.vv.root],{style:{overflowY:"auto",height:"100%"}})],{style:{height:"100%"}});const e=e=>{this.filteredMonomerRows=this.monomerCardRows.filter(t=>t.monomerSymbol.toLowerCase().includes(e.toLowerCase())),this.vv.setData(this.filteredMonomerRows.length,e=>(this.filteredMonomerRows[e].render(),this.filteredMonomerRows[e].root))}}}constructor(){}get root(){return this._root}}var Jn=n(3017),ei={};async function ti(){await ri.showDialog()}async function ni(e=!0){return await ai.showView(e)}ei.styleTagTransform=C(),ei.setAttributes=y(),ei.insert=g().bind(null,"head"),ei.domAPI=m(),ei.insertStyleElement=w(),h()(Jn.A,ei),Jn.A&&Jn.A.locals&&Jn.A.locals;class ii{_widget;get widget(){return this._widget}constructor(){}static instancePromise;libHelper;static async getInstance(){return null==ii.instancePromise&&(ii.instancePromise=(async()=>{const e=new ii,t=await(0,ye.pj)();return e.libHelper=t,e._widget=await e.createWidget(),e})()),ii.instancePromise}static async reloadWidget(){const e=await ii.getInstance();e._widget=await e.createWidget()}_fileUploadSubscription=null;async createWidget(){const e=await this.getWidgetContent(),t=await(0,ye.pj)();return this._fileUploadSubscription?.unsubscribe(),this._fileUploadSubscription=t.fileUploadRequested.subscribe(()=>this.promptToAddLibraryFiles()),new r.Widget(e)}async getWidgetContent(){const e=await oi.createControlsForm();return zn()(e).addClass("monomer-lib-controls-form").addClass("d4-dialog-contents"),setTimeout(()=>{e&&zn()(e)&&zn()(e).removeClass("ui-form-condensed")},200),s.divV([e])}async promptToAddLibraryFiles(){r.Utils.openFile({accept:".json",open:async e=>{const t=async t=>{const n=e.name;if((await t.listLibraries()).includes(n)&&!await new Promise(e=>{s.dialog("Confirm Library Update").add(s.divText(`Library '${n}' already exists. Do you want to overwrite it?`)).onOK(()=>e(!0)).onCancel(()=>e(!1)).show()}))return;const i=await e.text(),a=r.TaskBarProgressIndicator.create(`Adding ${n} as a monomer library`);try{await t.addOrUpdateLibraryString(n,i)}catch(e){o.shell.error(`File ${n} is not a valid monomer library, verify it is aligned to HELM JSON schema.`),console.error(e)}finally{a.close()}},n=await this.libHelper.getProviders();if(0===n.length)return void o.shell.error("No monomer library providers available to add the library.");if(1===n.length)return void await t(n[0]);const i=s.dialog("Select storage for new monomer library"),a=s.input.choice("Storage",{items:n.map(e=>e.name),value:n[0].name,nullable:!1,tooltipText:"Storage provider for new monomer library"});i.add(a).onOK(async()=>{const e=n.find(e=>e.name===a.value);await t(e)}).show()}})}}class oi{libHelper;userLibSettings;constructor(e,t){this.libHelper=e,this.userLibSettings=t,this.libHelper.providersDataChanged.subscribe(async()=>{await this.updateControlsForm()})}toLog(){return"LibraryControlsManager<#>"}static async createControlsForm(){Uo.logger.debug("LibraryControlsForm.createControlsForm(), start");const e=await(0,Le.u)(),t=await(0,ye.pj)();return new oi(t,e)._createControlsForm()}async _createControlsForm(){const e=await this.createLibraryControls(),t=s.wideForm(e,void 0);return zn()(t).addClass("monomer-lib-controls-form").addClass("d4-dialog-contents"),t}async updateControlsForm(){const e=await this._createControlsForm();zn()(".monomer-lib-controls-form").replaceWith(e)}async createLibraryControls(){return(await this.libHelper.getAvaliableLibraryNames()).map(e=>this.createLibInput(e))}createLibInput(e){const t=`${this.toLog()}.createLibInput()`;Uo.logger.debug(`${t}, libFileName = '${e}', start`);const n=!this.userLibSettings.exclude.includes(e),i=s.input.bool(e,{value:n,onValueChanged:()=>{si(i.value,e)}});s.tooltip.bind(i.root,`Include monomers from ${e}`);const r=s.iconFA("trash-alt",()=>this.promptForLibraryDeletion(e),"Delete"),a=s.icons.edit(async()=>{o.shell.v=await(await Ln.getInstance()).getViewRoot(e)},"Edit monomer library");return s.tooltip.bind(r,`Delete ${e}`),i.addOptions(a),i.addOptions(r),Uo.logger.debug(`${t}, libFileName = '${e}', end`),i}promptForLibraryDeletion(e){s.dialog("Warning").add(s.divText(`Are you sure you want to delete library "${e}"?`)).onOK(async()=>{try{const t=r.TaskBarProgressIndicator.create(`Deleting ${e} library`);await si(!1,e);const n=await(0,ye.pY)(await this.libHelper.getProviders(),e);if(!n)throw new Error(`Cannot find provider for library ${e}`);await n.deleteLibrary(e),t.close()}catch(t){console.error(t),o.shell.error(`Failed to delete ${e} library`)}}).showModal(!1)}}async function si(e,t){const n=await(0,Le.u)();!function(e,t,n){t?e.exclude=e.exclude.filter(e=>e!==n):e.exclude.includes(n)||e.exclude.push(n)}(n,e,t),await(0,Le.E)(n);const i=await(0,ye.pj)();await i.loadMonomerLib(!0),o.shell.info("Monomer library user settings saved"),i.notifyLibrarySelectionChanged()}class ri{constructor(){}static _instance;dialog;closeDialogSubject$=new c.Subject;static async showDialog(){ri._instance||(ri._instance=new ri,ri._instance.closeDialogSubject$.subscribe(()=>{ri._instance.dialog=void 0})),ri._instance.dialog||(ri._instance.dialog=await ri._instance.getDialog()),ri._instance.dialog.show()}async getDialog(){const e=(await ii.getInstance()).widget,t=await(0,ye.pj)(),n=s.dialog({title:"Manage monomer libraries",helpUrl:"/help/datagrok/solutions/domains/bio/bio.md#manage-monomer-libraries"});zn()(n.root).css("width","350px"),n.clear(),n.addButton("Add",()=>t.requestFileUpload(),void 0,"Upload new HELM monomer library"),n.add(e);const i=n.onClose.subscribe(()=>{this.closeDialogSubject$.next(),i.unsubscribe()});return n}}class ai{constructor(){}static _instance;static viewName="Manage Monomer Libraries";_view;_duplicateManager;libManager;async getView(e=!0){const t=(await ii.getInstance()).widget,n=s.bigButton("Add",()=>this.libManager.requestFileUpload(),"Upload new HELM monomer library"),i=s.bigButton("Merge",()=>{this.mergeSelectedLibs()},"Merge selected libraries into one"),a=s.splitH([s.divV([t.root,s.buttonsInput([n,i])],{classes:"ui-form"}),this._duplicateManager.root],{style:{width:"100%",height:"100%"}},!0);if(this._view)try{this._view.subs.forEach(e=>e.unsubscribe()),this._view.detach(),this._view.close()}catch(e){}return this._view=r.View.fromRoot(a),this._view.name=ai.viewName,e&&o.shell.addView(this._view),s.tools.waitForElementInDom(a).then(()=>{setTimeout(()=>{const e=Array.from(a.children).filter(e=>e.classList.contains("ui-box"));if(2!==e.length)return;const[t,n]=e,i=t.getBoundingClientRect().width+n.getBoundingClientRect().width,o=.3*i;t.style.width=`${o}px`;const s=i-o;n.style.width=`${s}px`},100),this._view.subs.push(o.events.onCurrentViewChanged.subscribe(()=>{try{const e=ai._instance;e&&e._view&&o.shell.v&&"id"in o.shell.v&&o.shell.v.id===e._view.id&&e._duplicateManager?.refresh()}catch(e){console.error(e)}}))}),this._view}static async showView(e=!0){return ai._instance||(ai._instance=new ai),ai._instance._duplicateManager||(ai._instance._duplicateManager=await Qn.getInstance()),ai._instance.libManager||(ai._instance.libManager=await bn.getInstance()),e&&ai._instance._view&&Array.from(o.shell.views).find(e=>e.id&&e.id===ai._instance._view.id)?(o.shell.v=ai._instance._view,await ai._instance._duplicateManager.refresh(),ai._instance._view):(ai.closeExistingViews(),ai._instance.getView(e))}static closeExistingViews(){Array.from(o.shell.views).filter(e=>e.name===ai.viewName).forEach(e=>e.close())}async mergeSelectedLibs(){const e="Library with this name already exists",t=await bn.getInstance();if(await t.awaitLoaded(),!t.duplicatesHandled)return void o.shell.warning("Selected libraries contain repeating symbols with different monomers.\n Please choose the correct monomer for each symbol using duplicate monomomer manager.");const n=t.getBioLib().toJSON(),i=s.dialog("Merge selected libraries"),a=s.input.string("Library Name",{placeholder:"Enter new library name",nullable:!1,onValueChanged:()=>{const t=c(a.value);i.getButton("Download")?.classList?.toggle("d4-disabled",!!t&&t!==e),i.getButton("Save")?.classList?.toggle("d4-disabled",!!t)}}),l=await this.libManager.getAvaliableLibraryNames();function c(t){return t&&t.trim()?l.includes(t)||l.includes(t+".json")?e:null:"Library name cannot be empty"}a.addValidator(c);const u=await this.libManager.getProviders();if(0===u.length)return void o.shell.error("No monomer library providers available to save the merged library.");const h=s.input.choice("Storage",{items:u.map(e=>e.name),value:u[0].name,nullable:!1,tooltipText:"Storage provider for saving new monomer library"});i.add(h).add(a).add(s.divText(`Total monomers: ${n.length}`)).addButton("Download",()=>{r.Utils.download((()=>{let e=a.value.trim();return e||(e="New"),e.toLowerCase().endsWith(".json")||(e+=".json"),e})(),JSON.stringify(n))}).addButton("Save",async()=>{if(!a.value||!a.value.trim()||!h.value)return h.validate(),void a.validate();i.close();const e=a.value,t=JSON.stringify(n);this._view&&s.setUpdateIndicator(this._view.root,!0);try{const n=u.find(e=>e.name===h.value);await n.addOrUpdateLibraryString(e,t);const i=await(0,Le.u)();i.exclude=l,await(0,Le.E)(i),await this.libManager.loadMonomerLib(!0),await ii.reloadWidget()}catch(t){o.shell.error(`Failed to save library ${e}. see console for details.`),console.error(t)}finally{this._view&&s.setUpdateIndicator(this._view.root,!1)}}).show(),i.getButton("Download")?.classList?.add("d4-disabled"),i.getButton("Save")?.classList?.add("d4-disabled")}}var li,ci=function(e,t,n,i){return new(n||(n=Promise))(function(o,s){function r(e){try{l(i.next(e))}catch(e){s(e)}}function a(e){try{l(i.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};class ui{_setBreadcrumbsInViewName(){var e,t;const n=["Home","Demo",...(null!==(e=this._path)&&void 0!==e?e:"").split("/")],i=s.breadcrumbs(n);if(i.onPathClick.subscribe(e=>ci(this,void 0,void 0,function*(){const t=e[e.length-1];if(t===i.path[i.path.length-1])return;const n=o.shell.browsePanel.mainTree.getOrCreateGroup("Apps").getOrCreateGroup("Demo");n.currentItem="Demo"===t?n:n.items.find(e=>e.text===t)})),o.shell.v){if(0!==i.path.length&&"Home"===i.path[0]){const e=s.iconFA("home",()=>{o.shell.v.close(),o.shell.v=r.View.createByType(r.VIEW_TYPE.HOME)});e.classList.add("demo-breadcrumbs-home-element"),i.root.firstElementChild.replaceWith(e)}const e=null===(t=o.shell.v.ribbonMenu.root.parentElement)||void 0===t?void 0:t.getElementsByClassName("d4-ribbon-name")[0];e&&(e.textContent="",e.appendChild(i.root))}}constructor(e,t,n=!1,i){var o,r;this.name="",this.description="",this._isAutomatic=!1,this._autoStartFirstStep=!1,this._currentStep=0,this._isStopped=!1,this._isCancelled=!1,this._isStepProcessed=!1,this._root=s.div([],{id:"demo-script",classes:"tutorials-root tutorials-track demo-app-script"}),this._steps=[],this._mainHeader=s.panel([],"tutorials-main-header"),this._header=s.h2(""),this._headerDiv=s.divH([],"tutorials-root-header"),this._stopStartBtn=s.button(s.iconFA("pause"),()=>ci(this,void 0,void 0,function*(){return yield this._changeStopState()}),"Play / pause"),this._restartBtn=s.button(s.iconFA("redo"),()=>ci(this,void 0,void 0,function*(){return yield this._restartScript()}),"Restart"),this._nextStepBtn=s.button(s.iconFA("play"),()=>ci(this,void 0,void 0,function*(){this._isStepProcessed||(yield this._nextStep())}),"Next step"),this._activity=s.panel([],"tutorials-root-description"),this._progressDiv=s.divV([],"tutorials-root-progress"),this._progress=s.element("progress"),this._progressSteps=s.divText(""),this._closeBtn=s.button(s.iconFA("chevron-left"),()=>this._closeDock(),"Back to demo"),this.DEMO_PATH="apps/Tutorials/Demo",this.name=e,this.description=t,this._isAutomatic=n,this._autoStartFirstStep=null!==(o=null==i?void 0:i.autoStartFirstStep)&&void 0!==o&&o,this._path=null!==(r=null==i?void 0:i.path)&&void 0!==r?r:"",this._progress.max=0,this._progress.value=1,ui.currentObject=this}get steps(){return this._steps}get stepNumber(){return this._steps.length}_addHeader(){this._createHeaderDiv(),this._createProgressDiv(),this._mainHeader.append(this._headerDiv,this._progressDiv)}_createHeaderDiv(){this._header.innerText=this.name,this._headerDiv.append(this._closeBtn),this._headerDiv.append(this._header),this._nextStepBtn.firstChild.className="grok-icon fas fa-play",this._headerDiv.append(this._isAutomatic?this._stopStartBtn:this._nextStepBtn)}_createProgressDiv(){this._progress.max=this.stepNumber,this._progressDiv.append(this._progress),this._progressSteps=s.divText(`Step: ${this._progress.value} of ${this.stepNumber}`),this._progressDiv.append(this._progressSteps)}_addDescription(){var e;this._activity.append(s.div(this.description,"tutorials-root-description"));for(let t=0;t<this.stepNumber;t++){let n=s.iconFA("clock");this._isAutomatic||0===t&&(n=s.iconFA("play",()=>this._nextStep(),"Next step"),n.className="grok-icon fas fa-play");const i=s.div(this._steps[t].name,"grok-tutorial-entry-instruction"),o=s.div(null===(e=this._steps[t].options)||void 0===e?void 0:e.description,"grok-tutorial-step-description hidden"),r=s.divH([n,i],"grok-tutorial-entry");this._activity.append(r,o)}}_initRoot(){o.shell.windows.showContextPanel=!0,o.shell.windows.showHelp=!1,this._node=o.shell.dockManager.dock(this._root,r.DOCK_TYPE.FILL,o.shell.dockManager.findNode(o.shell.browsePanel.root),this.name),this._node.container.containerElement.classList.add("tutorials-demo-script-container"),this._addHeader(),this._root.append(this._mainHeader),this._addDescription(),this._root.append(this._activity)}_setViewParams(){var e;o.shell.v&&(o.shell.v.name=this.name,o.shell.v.path=`${this.DEMO_PATH}/${(null!==(e=this._path)&&void 0!==e?e:"").replaceAll(" ","-")}`,this._setBreadcrumbsInViewName())}_nextStep(){return ci(this,void 0,void 0,function*(){var e,t;this._isStepProcessed=!0,this._isAutomatic||(this._nextStepBtn.classList.add("disabled"),this._nextStepBtn.firstChild.classList.add("fa-disabled"));const n=this._activity.getElementsByClassName("grok-tutorial-entry")[this._currentStep],i=this._activity.getElementsByClassName("grok-icon")[this._currentStep],a=this._activity.getElementsByClassName("grok-tutorial-step-description")[this._currentStep];i.className="grok-icon far fa-spinner-third fa-spin",a.classList.remove("hidden"),a.classList.add("visible");const l=n,c=(null===(e=this._steps[this._currentStep].options)||void 0===e?void 0:e.delay)?null===(t=this._steps[this._currentStep].options)||void 0===t?void 0:t.delay:2e3;try{this._setViewParams(),yield this._steps[this._currentStep].func(),this._setViewParams()}catch(e){console.error(e)}this._scrollTo(this._root,l.offsetTop-this._mainHeader.offsetHeight),this._isAutomatic&&(yield this._countdown(n,i,c),yield r.delay(c));const u=s.iconFA("check");if(i.replaceWith(u),u.className="grok-icon far fa-check",this._progress.value++,this._progressSteps.innerText=`Step: ${this._progress.value} of ${this.stepNumber}`,this._currentStep++,this._isStepProcessed=!1,this._currentStep===this.stepNumber)return this._restartBtn.disabled=!1,void(this._isAutomatic?this._stopStartBtn.replaceWith(this._restartBtn):this._nextStepBtn.replaceWith(this._restartBtn));if(!this._isAutomatic){const e=this._activity.getElementsByClassName("grok-icon")[this._currentStep],t=s.iconFA("play",()=>this._nextStep(),"Next step");t.className="grok-icon fas fa-play",e.replaceWith(t),this._nextStepBtn.classList.remove("disabled"),this._nextStepBtn.firstChild.classList.remove("fa-disabled")}o.shell.v instanceof r.TableView&&(yield o.data.detectSemanticTypes(o.shell.tv.dataFrame))})}_startScript(){return ci(this,void 0,void 0,function*(){for(let e=this._currentStep;e<this.stepNumber&&!this._isStopped&&!this._isCancelled;e++)yield this._nextStep()})}_scrollTo(e,t){e.focus(),e.scrollTop=t}_countdown(e,t,n){return ci(this,void 0,void 0,function*(){const i=s.div([],"demo-script-countdown");t.classList.add("hidden");let o=n/1e3;const r=this._createSVGIndicator(o);i.append(r),e.prepend(i);const a=setInterval(()=>{o--,0===o&&(clearInterval(a),i.remove(),t.classList.remove("hidden"),t.classList.add("visible"))},1e3)})}_createSVGIndicator(e){const t=document.createElementNS("http://www.w3.org/2000/svg","svg"),n=document.createElementNS("http://www.w3.org/2000/svg","circle");return n.setAttributeNS(null,"cx","7"),n.setAttributeNS(null,"cy","7"),n.setAttributeNS(null,"r","6"),n.setAttributeNS(null,"style",`animation: countdown ${e}s linear infinite forwards`),t.append(n),t}_changeStopState(){return ci(this,void 0,void 0,function*(){const e=this._stopStartBtn.getElementsByClassName("grok-icon");e[0].className="grok-icon fas fa-play",this._isStopped=!this._isStopped,this._isStopped||(e[0].className="grok-icon fal fa-pause",this._isStepProcessed||(yield this._startScript()))})}_restartScript(){return ci(this,void 0,void 0,function*(){this._restartBtn.disabled=!0,o.shell.dockManager.close(this._node),this._clearRoot(),this._setInitParams(),yield this.start()})}_clearRoot(){this._root=s.div([],{id:"demo-script",classes:"tutorials-root tutorials-track demo-app-script"}),this._mainHeader=s.panel([],"tutorials-main-header"),this._header=s.h2(""),this._headerDiv=s.divH([],"tutorials-root-header"),this._activity=s.panel([],"tutorials-root-description"),this._progressDiv=s.divV([],"tutorials-root-progress"),this._progress=s.element("progress"),this._progressSteps=s.divText(""),this._progress.max=0,this._progress.value=1}_setInitParams(){this._currentStep=0,this._isStopped=!1,this._isCancelled=!1,this._stopStartBtn.getElementsByClassName("grok-icon")[0].className="grok-icon fal fa-pause",this._nextStepBtn.classList.remove("disabled")}_closeDock(){o.shell.dockManager.close(this._node),this.cancelScript()}cancelScript(){this._isCancelled=!0,ui.currentObject=null}step(e,t,n){return this._steps[this.steps.length]={name:e,func:t,options:n},this}start(){return ci(this,void 0,void 0,function*(){var e;(null===(e=o.shell.v)||void 0===e?void 0:e.name)===this.name&&o.shell.v.close(),this._initRoot(),this._isAutomatic?yield this._startScript():this._autoStartFirstStep&&(yield this._nextStep())})}}ui.currentObject=null,function(e){e.X="Embed_X",e.Y="Embed_Y"}(li||(li={}));var hi=n(5749),di=n(966),mi=n(608),pi=n(1619),gi=n(8152);class fi{urlParams;funcName;options;df;view;constructor(e,t,n={}){this.urlParams=e,this.funcName=t,this.options=n}async init(e){this.df=e,await this.buildView()}async buildView(){const e=ee()(this.urlParams.entries()).map(([e,t])=>`${e}=${encodeURIComponent(t)}`).toArray().join("&");this.view=o.shell.addTableView(this.df),this.view.path=this.view.basePath=`func/${Uo.name}.${this.funcName}?${e}`;const t={...this.options,sequenceColumnName:"sequence"};for(const[e,n]of this.urlParams.entries())switch(e){case tt.n5.fixWidth:case tt.n5.fitArea:t[e]=(e=>["1","on","true"].includes(e.toLowerCase()))(n);break;default:t[e]=n}const n=await this.view.dataFrame.plot.fromType("WebLogo",t);this.view.dockManager.dock(n,r.DOCK_TYPE.DOWN,null,"WebLogo",.35)}}class yi{tableInput;seqColInput;funcParamsDiv;get funcParams(){return{table:this.tableInput.value,sequence:this.seqColInput.value}}get paramsUI(){return this.funcParamsDiv}constructor(){this.tableInput=s.input.table("Table",{value:o.shell.tv.dataFrame,onValueChanged:()=>{this.onTableInputChanged()}});const e=this.tableInput.value.columns.bySemType(r.SEMTYPE.MACROMOLECULE);this.seqColInput=s.input.column("Sequence",{table:this.tableInput.value,value:e,filter:e=>e.semType===r.SEMTYPE.MACROMOLECULE}),this.funcParamsDiv=s.inputs([this.tableInput,this.seqColInput],{style:{minWidth:"320px"}})}onTableInputChanged(){this.seqColInput=s.input.column("Sequence",{table:this.tableInput.value,value:this.tableInput.value.columns.bySemType(r.SEMTYPE.MACROMOLECULE)})}}var bi=n(6869);const wi="-";class vi extends Be{constructor(e,t){super(e,t)}static _canonLoadingKey=pe.sc+".loading";getCanonicalizer(e){const t=e.temp[pe.sc]??null;if(t)return t;if(e.temp[vi._canonLoadingKey])return null;const n=e.getTag(pe.jz);if(!n)return null;const i=n.includes(":")?n.split(":"):[void 0,n],o=r.Func.find({name:i[1],package:i[0]});return 0===o.length||(e.temp[vi._canonLoadingKey]=!0,o[0].apply({}).then(t=>{e.temp[pe.sc]=t,e.temp[vi._canonLoadingKey]=!1,this.gridCol?.grid?.invalidate&&this.gridCol.grid.invalidate()}).catch(()=>{e.temp[vi._canonLoadingKey]=!1})),null}render(e,t,n,i,o,s,r){e.save(),e.beginPath(),e.rect(t,n,i,o),e.clip();try{if(!s.isTableCell)return;const r=s.cell?.column&&s.cell.column?.dart&&"true"===s.cell.column.getTag(Re.Mn.applyToBackground);e.font="12px monospace",e.textBaseline="middle",e.textAlign="left";const a=e.measureText("M"),l=a.actualBoundingBoxAscent+a.actualBoundingBoxDescent+8;let c=s.cell.value;c&&c!==pe._S||(c=wi);const u=c.split(pe.ot).map(e=>e&&e!==pe._S?e.trim():wi),h=u.map(e=>(0,ue.zS)(e,Math.max(2,Math.floor(.15*i/u.length)))),d=h.map(t=>e.measureText(t).width+4),m=d.reduce((e,t)=>e+t,0);let p=t+(i-m)/2+2;const g=this.tableCol.getTag(pe.gp.alphabet),f=g===ue.YI.RNA||g===ue.YI.DNA?bi.o.NUCLEOTIDE:bi.o.AA;for(let a=0;a<h.length;a++){const c=u[a],m=this.getHelmType(s,f);let g=$e.S$,y="rgb(255, 255, 255)";if(this.monomerLib)if(r){const e=this.monomerLib.getMonomerColors(m,c);g=e?.textcolor??g,y=e?.backgroundcolor??y}else g=this.monomerLib.getMonomerTextColor(m,c);if(r)if(e.fillStyle=y,i<30||o<30)e.fillRect(t+a*i/h.length,n,i/h.length,o);else{const t=2;e.roundRect(p-2,n+o/2-l/2,d[a],l,t),e.fill()}e.fillStyle=g,e.fillText(h[a],p,n+o/2,i),p+=d[a]}}finally{e.restore()}}onMouseMove(e,t){const[n,i,o]=(0,De.BG)(e);if(e.grid.dart!=this.gridCol?.grid.dart||n?.dart!=this.gridCol?.dart||!i||!e.isTableCell)return!1;const r=i.getTag(pe.gp.alphabet),a=e.cell.value,l=this.getCanonicalizer(i),c=l&&a?l.canonicalize(a):a,u=e.grid.canvas.getBoundingClientRect(),h=e.bounds.right+u.left-4,d=e.bounds.bottom+u.top-4;if(!a||a==pe._S||a==wi||null!=l&&l.isGap(a))return s.tooltip.show(s.divText("gap"),h,d),!0;if(!this.monomerLib)return s.tooltip.show(s.divText("Monomer library is not available."),h,d),!0;const m=r===ue.YI.RNA||r===ue.YI.DNA?bi.o.NUCLEOTIDE:bi.o.AA,p=c.split(pe.ot).map(t=>{if(!t||t===pe._S||t===wi)return s.divText("gap");const n=this.getHelmType(e,m);return this.monomerLib.getTooltip(n,t)}),g=s.divH(p,{style:{alignItems:"top",flexWrap:"wrap",gap:"4px"}}),f=Array.from(g.querySelectorAll("canvas"));if(f.length>2){const e=Math.floor(550/f.length);f.forEach(t=>{t.style.setProperty("max-width",`${e}px`,"important"),t.style.setProperty("max-height",`${e}px`,"important")})}return s.tooltip.show(g,h,d),!0}getHelmType(e,t){let n=t;const[i,o,s]=(0,De.BG)(e);if((e.tableRowIndex??-1)>-1&&o?.getTag(pe.qE.polymerTypeColumnName)){const t=o.getTag(pe.qE.polymerTypeColumnName),i=o.dataFrame?.col(t);if(i){const t=i.get(e.tableRowIndex);t&&["BLOB","CHEM","G","PEPTIDE","RNA"].includes(t)&&(n=(0,Oe.MD)(t))}}return n}async awaitRendered(e=1e4,t=`${e} timeout`){return Promise.resolve()}static getOrCreate(e){const[t,n,i]=(0,De.BG)(e);let o=i.rendererBack;return o||(o=i.rendererBack=new vi(t,n)),o}}class Ci extends r.GridCellRenderer{get name(){return Ve.uF.MONOMER}get cellType(){return Ve.uF.MONOMER}get defaultHeight(){return 15}get defaultWidth(){return 40}render(e,t,n,i,o,s,r){vi.getOrCreate(s).render(e,t,n,i,o,s,r)}onMouseMove(e,t){vi.getOrCreate(e).onMouseMove(e,t),t.preventDefault()}}class Ai{constructor(e,t,n=""){this.target=e,this.debugEnabled=t,this.prefix=n}error(e,t,n){return this.target.error(this.prefix+e,t,n)}warning(e,t){return this.target.warning(this.prefix+e,t)}info(e,t){return this.target.info(this.prefix+e,t)}debug(e,t){if(this.debugEnabled)return this.target.debug(this.prefix+e,t)}}class Ti extends Map{_onPropertyChanged=new c.Subject;get onPropertyChanged(){return this._onPropertyChanged}get fontSize(){const e=super.get("FontSize");return e&&!isNaN(e)?Number.parseInt(e):12}set fontSize(e){super.set("FontSize",e),this._onPropertyChanged.next("FontSize")}get maxMonomerLength(){const e=super.get("MaxMonomerLength");return"long"===e?null:parseInt(e)}set maxMonomerLength(e){const t=null==e?"long":e.toString();super.set("MaxMonomerLength",t),this._onPropertyChanged.next("MaxMonomerLength")}get tooltipWebLogo(){return super.get("TooltipWebLogo")}set tooltipWebLogo(e){super.set("TooltipWebLogo",e),this._onPropertyChanged.next("TooltipWebLogo")}get defaultSeparator(){return super.get("DefaultSeparator")}set defaultSeparator(e){if(1!==e.length)throw new Error("The separator must be of length one.");super.set("DefaultSeparator",e),this._onPropertyChanged.next("DefaultSeparator")}constructor(e){super(Object.entries(e))}}class Ei extends r.Package{_properties;_seqHelper;get seqHelper(){if(!this._seqHelper)throw new Error("Package Bio .seqHelper is not initialized.");return this._seqHelper}_monomerLib;get monomerLib(){if(!this._monomerLib)throw new Error("Package Bio .monomerLib is not initialized.");return this._monomerLib}_monomerSets;get monomerSets(){if(!this._monomerSets)throw new Error("Package Bio .monomerSets is not initialized.");return this._monomerSets}_rdKitModule;get rdKitModule(){if(!this._rdKitModule)throw new Error("Package Bio .rdKitModule is not initialized.");return this._rdKitModule}get properties(){return this._properties}set properties(e){this._properties=e}_initialized=!1;get initialized(){return this._initialized}constructor(e={debug:!1}){super(),super._logger=new Ai(super.logger,e.debug)}completeInit(e,t,n,i){this._seqHelper=e,this._monomerLib=t,this._monomerSets=n,this._rdKitModule=i,this._initialized=!0}handleErrorUI(e){const[t,n]=(0,we.AP)(e);o.shell.error(t),this.logger.error(t,void 0,n)}}var Si=n(6307),Mi=n(5999),xi={};xi.styleTagTransform=C(),xi.setAttributes=y(),xi.insert=g().bind(null,"head"),xi.domAPI=m(),xi.insertStyleElement=w(),h()(Mi.A,xi),Mi.A&&Mi.A.locals&&Mi.A.locals;class Pi extends r.Widget{seqCol;seqHelper;get type(){return"MacromoleculeColumnWidget"}viewed=!1;wlViewer=null;constructor(e,t){super(s.divV([])),this.seqCol=e,this.seqHelper=t}async init(){const e=this.seqHelper.getSeqHandler(this.seqCol),t=Uo.properties.tooltipWebLogo,n=this.seqCol.getTag(Qe.gp.tooltipWebLogo);!1===t||["false","off","disable","disabled"].includes(n)||(this.wlViewer=await this.seqCol.dataFrame.plot.fromType("WebLogo",{sequenceColumnName:this.seqCol.name,backgroundColor:0,positionHeight:"Entropy",positionWidth:e.getAlphabetIsMultichar()?24:16,fixWidth:!0,fitArea:!1,positionNames:"",endPositionName:"50"}),this.wlViewer.root.style.height="50px",this.root.appendChild(this.wlViewer.root),this.root.style.width="100%")}detach(){this.wlViewer&&(this.wlViewer.detach(),this.wlViewer=null),super.detach()}}var Li=n(4951);function Ii(e,t,n,i){const o=Uo.seqHelper.getSeqHandler(e);let s=null,a=null;for(let e=0;e<o.posList.length;++e)o.posList[e]==t&&(s=e),o.posList[e]==n&&(a=e);if(null==s&&null!==t)throw new Error(`Start position ${t} not found.`);if(null==a&&null!==n)throw new Error(`End position ${n} not found.`);if(o.posList.length<a)throw new Error(`End position ${a} exceeds positions length`);const l=i||`${e.name}: (${t??""}-${n??""})`,c=function(e,t,n,i,o){if(!n||!i||!e.dataFrame)return null;const s=e.getTag(ue.gp.annotations);if(!s)return null;let a;try{a=JSON.parse(s)}catch{return null}const l=a.find(e=>e.category===St.eI.Structure&&e.start===n&&e.end===i);if(!l)return null;const c=(0,Et.VT)(e.name);let u=null;try{u=e.dataFrame.columns.byName(c)}catch{return null}if(!u)return null;const h=(0,Et.wi)(u);if(!h.some(e=>e?.some(e=>e.annotationId===l.id&&null!=e.endPositionIndex)))return null;const d=e.dataFrame,m=r.Column.fromType(r.COLUMN_TYPE.STRING,o,d.rowCount);for(let e=0;e<d.rowCount;e++){const n=h[e],i=n?.find(e=>e.annotationId===l.id&&null!=e.endPositionIndex);if(i){const n=t.getSplitted(e),o=[];for(let e=i.positionIndex;e<=i.endPositionIndex;e++)e<n.length&&o.push(n.getOriginal(e));m.set(e,o.join(t.separator||""))}else m.set(e,"")}return m}(e,o,t,n,l);return c||o.getRegion(s,a,l)}const _i={df:r.DataFrame.fromCsv("seq,value\nATCCGTCGT,0.5\nTGTTCGTCA,0.4\nATGGTCGTA,0.7\nATCCGTGCA,0.1"),colName:"seq",positionNames:["1","1A","1C","2","4","4A","4B","5","6"].join(ue.z1),regions:[{name:"first region",start:"1",end:"2"},{name:"second region",start:"1C",end:"4"},{name:"overlapping second",start:"1C",end:"4A"},{name:"whole sequence",start:"1",end:"6"},{name:"bad start",start:"0",end:"6"},{name:"bad end",start:"1",end:"4C"},{name:"bad start & end",start:"0",end:"4C"}]};class Ni{urlParams;funcName;view;data;constructor(e,t){this.urlParams=e,this.funcName=t}async init(e){this.data=e??_i;const t=this.data.df.getCol(this.data.colName);this.data.positionNames&&t.setTag(ue.gp.positionNames,this.data.positionNames),this.data.regions&&t.setTag(ue.gp.regions,JSON.stringify(this.data.regions)),await this.buildView()}async buildView(){await o.data.detectSemanticTypes(this.data.df),this.view=o.shell.addTableView(this.data.df),this.view.path=this.view.basePath=`func/${Uo.name}.${this.funcName}`;const e=await this.view.dataFrame.plot.fromType("WebLogo",{sequenceColumnName:this.data.colName});this.view.dockManager.dock(e,r.DOCK_TYPE.DOWN,null,"WebLogo",.35)}}class Ri{call;seqHelper;inputs=new class{table;sequence;region;start;end;name};constructor(e,t){this.call=e,this.seqHelper=t;const n=e=>this.call.inputParams[e].property.description;this.inputs.table=s.input.table("Table",{value:this.call.inputParams.table.value??o.shell.tv.dataFrame});const i=this.call.inputParams.sequence.value??this.inputs.table.value.columns.bySemType(r.SEMTYPE.MACROMOLECULE);this.inputs.sequence=s.input.column("Sequence",{table:o.shell.tv.dataFrame,value:i,onValueChanged:this.sequenceInputChanged.bind(this),filter:e=>e.semType===r.SEMTYPE.MACROMOLECULE}),this.inputs.start=s.input.choice("Start",{onValueChanged:this.startInputChanged.bind(this)}),this.inputs.end=s.input.choice("End",{onValueChanged:this.endInputChanged.bind(this)}),this.inputs.region=s.input.choice("Region",{value:null,items:[],onValueChanged:this.regionInputChanged.bind(this)}),this.inputs.name=s.input.string("Column name",{value:this.getDefaultName(),onValueChanged:this.nameInputChanged.bind(this),clearIcon:!0}),this.inputs.name.onInput.subscribe(()=>this.nameInputInput.bind(this));for(const e in this.call.inputParams)s.tooltip.bind(this.inputs[e].captionLabel,n(e));this.sequenceInputChanged()}sequenceInputChanged(){const e=this.inputs.sequence.value;e&&this.seqHelper.getSeqHandler(e),this.updateRegionItems(),this.updateStartEndInputItems(),this.updateRegion(!0),this.updateNameInput()}fixRegion=!1;regionInputChanged(){this.fixRegion=!0;try{const e=this.inputs.region.stringValue,t=e?JSON.parse(e):null;if(null!==t)this.inputs.start.value=t?.start,this.inputs.end.value=t?.end;else{const e=this.seqHelper.getSeqHandler(this.inputs.sequence.value);this.inputs.start.value=e.posList[0],this.inputs.end.value=e.posList[e.posList.length-1]}}finally{this.fixRegion=!1}}startInputChanged(){this.updateRegion(!1),this.updateNameInput()}endInputChanged(){this.updateRegion(!1),this.updateNameInput()}nameInputChanged(){this.defaultNameUpdating||(this.defaultName=!1)}nameInputInput(){this.inputs.name.value||(this.defaultName=!0,this.inputs.name.input.focus())}updateStartEndInputItems(){const e=this.inputs.sequence.value,t=e?this.seqHelper.getSeqHandler(e):null,n=this.inputs.start.input,i=this.inputs.end.input;for(let e=n.options.length-1;e>=0;--e)n.options.remove(e);for(let e=i.options.length-1;e>=0;--e)i.options.remove(e);for(const e of t?.posList??[]){const t=document.createElement("option"),o=document.createElement("option");t.text=o.text=e,t.value=o.value=e,n.options.add(t),i.options.add(o)}n.value=t?.posList[0]??"",i.value=t?.posList[t?.posList.length-1]??""}updateRegionItems(){const e=this.inputs.sequence.value;let t=null;const n=e?e.getTag(ue.gp.annotations):null;if(n)try{const e=JSON.parse(n).filter(e=>"structure"===e.category&&e.start&&e.end);e.length>0&&(t=e.map(e=>({name:e.name,description:e.description??"",start:e.start,end:e.end})))}catch{}if(!t){const n=e?e.getTag(ue.gp.regions):null;t=n?JSON.parse(n):null}const i=this.inputs.region.input;for(let e=i.options.length-1;e>=0;--e)i.options.remove(e);const o=document.createElement("option");if(o.text="",o.value=JSON.stringify(null),i.options.add(o),null!=t){this.inputs.region.root.style.removeProperty("display");for(const e of t){const t=document.createElement("option");t.text=`${e.name}: ${e.start}-${e.end}`,t.value=JSON.stringify(e),i.options.add(t)}}else this.inputs.region.root.style.display="none"}updateRegion(e){const t=this.inputs.start.stringValue??"",n=this.inputs.end.stringValue??"";if(!this.fixRegion){const e=this.inputs.region.input;e.selectedIndex=-1;for(let i=e.options.length-1;i>=0;--i){const o=e.options[i],s=JSON.parse(o.value);s&&t===s.start&&n===s.end&&(e.selectedIndex=i)}}}defaultName=!0;defaultNameUpdating=!1;updateNameInput(){this.defaultNameUpdating=!0;try{this.defaultName&&(this.inputs.name.value=this.getDefaultName())}finally{this.defaultNameUpdating=!1}}getDefaultName(){const e=this.inputs.region.stringValue,t=e?JSON.parse(e):null,n=this.inputs.sequence.value,i=this.inputs.start.stringValue??"",o=this.inputs.end.stringValue??"";return null!=t?`${n.name}(${t.name}): ${t.start}-${t.end}`:`${n?.name}: (${i}-${o})`}getParams(){return{table:this.inputs.table.value,sequence:this.inputs.sequence.value,start:this.getStart(),end:this.getEnd(),name:this.getName()}}getStart(){return this.inputs.start.stringValue}getEnd(){return this.inputs.end.stringValue}getName(){const e=this.inputs.name.stringValue;return""==e?null:e}dialog(){const e=s.inputs(Object.values(this.inputs),{style:{minWidth:"320px"}});s.dialog({title:"Get Region"}).add(e).onOK(()=>{(async()=>{const e=this.getParams();await this.call.func.prepare(e).call(!0)})().catch(e=>{Uo.handleErrorUI(e)})}).show()}widget(){const e=s.inputs(Object.entries(this.inputs).filter(([e,t])=>!["table","sequence"].includes(e)).map(([e,t])=>t)),t=s.button("Get Region",()=>{(async()=>{const e=this.getParams();await this.call.func.prepare(e).call(!0)})().catch(e=>{Uo.handleErrorUI(e)})});return r.Widget.fromRoot(s.divV([e,s.div(t)]))}}var $i=n(8754);async function Oi(e,t,n,i,s){const a=await async function(e,t,n,i,s){const a=ge(t,s),l=s.getSeqHandler(t).getNewColumnFromList("ref",[n]),c=s.getSeqHandler(l).getSplitted(0),u=i===fe.IDENTITY?function(e,t){const n=t.columns.length,i=new Array(n),o=new Array(n),s=new Array(n);for(let r=0;r<n;++r){const n=t.columns.byIndex(r);i[r]=n.getRawData(),o[r]=n.categories.indexOf("");const a=r<e.length?e.getOriginal(r):pe._S;s[r]=n.categories.indexOf(a)}const a=r.Column.float("Identity",t.rowCount),l=a.getRawData();for(let n=0;n<t.rowCount;++n){l[n]=0;for(let t=0;t<e.length;++t)(i[t]?i[t][n]:0)===s[t]&&++l[n];l[n]/=e.length}return a}(c,a):i===fe.SIMILARITY?await async function(e,t,n){const i=t.columns.toList(),s=await async function(e,t,n){e instanceof r.Column&&(e=ge(e,n).columns.toList());const i=(await(0,ye.pj)()).getMonomerLib(),s=new Array(e.length),a=e[0].length,l=new Float32Array(a);for(let n=0;n<e.length;++n){const c=n<t.length?t.getCanonical(n):pe._S,u=i.getMonomer("PEPTIDE",c)?.smiles??"",h=e[n],d=h.getRawData(),m=h.categories,p=m.indexOf("");if(s[n]={categories:m,data:d,emptyIndex:p},void 0===c)continue;const g=r.Column.fromStrings("smiles",m.map(e=>i.getMonomer("PEPTIDE",e)?.smiles??"")),f=(r.DataFrame.fromColumns([g]),await o.chem.getSimilarities(g,u)),y=f?f.getRawData():null;for(let e=0;e<a;++e){const t=d[e];c!==pe._S&&t!==p?l[e]+=y[t]:c===pe._S&&t===p&&(l[e]+=1)}}for(let n=0;n<l.length;++n){let i=l[n]/t.length;for(let o=0;o<e.length;++o){const e=s[o];if(o>=t.length&&e.data[n]!==e.emptyIndex||e.data[n]===e.emptyIndex&&o<t.length){i=r.FLOAT_NULL;break}}l[n]=i}return r.Column.fromFloat32Array("Similarity",l)}(i,e,n);return s}(c,a,s):null;if(null==u)throw new Error(`In bio library: Unknown sequence scoring method: ${i}`);return u.name=e.columns.getUnusedName(u.name),e.columns.add(u),u}(e,t,n,i,s);for(let e=0;e<a.length;e++)t.isNone(e)&&a.set(e,null,!1);return a}var Hi=n(294),Di=n(330);const Fi=OCL;var ki=n(2582);class Gi{monomerSymbol;constructor(e){this.monomerSymbol=e}atoms;bonds;rGroups;get atomCount(){return this.atoms.count}get bondCount(){return this.bonds.count}shiftR1GroupToOrigin(){const e=this.rGroups.getAtomicIdx(1);if(null==e)return;const{x:t,y:n}=this.atoms.atomCoordinates[e];this.atoms.shift({x:-t,y:-n})}alignR2AlongX(){const e=this.rGroups.getAtomicIdx(2);if(null==e)throw new Error(`Cannot find R2 group for monomer ${this.monomerSymbol}`);const t=this.atoms.atomCoordinates[e],n=t.y/t.x,i=Math.atan(n);if(isNaN(i))throw new Error(`Cannot calculate angle for R2 group for monomer ${this.monomerSymbol}`);this.rotateCoordinates(-i)}shiftMonomerToDefaultPosition(){this.shiftR1GroupToOrigin(),null!==this.rGroups.getAtomicIdx(2)&&this.alignR2AlongX()}deleteBondLineWithSpecifiedRGroup(e){this.rGroups.deleteBondLineWithSpecifiedRGroup(e)}shiftCoordinates(e){this.atoms.shift(e)}rotateCoordinates(e){this.atoms.rotate(e)}getBondLines(){return this.bonds.getBondLines()}getAtomLines(){return this.atoms.atomLines}removeRGroups(e){this.rGroups.removeRGroups(e)}replaceRGroupWithAttachmentAtom(e,t){this.rGroups.replaceRGroupWithAttachmentAtom(e,t)}getAttachmentAtomByRGroupId(e){return this.rGroups.getAttachmentAtomIdByRGroupId(e)}shiftBonds(e){this.bonds.shift(e)}capRGroups(e,t){this.rGroups.capRGroups(e,t)}}var Bi=n(6956);class Vi{atoms;bonds;constructor(e,t,n){this.atoms=t,this.bonds=n,this.rGroupIdToAtomicIndexMap=e.getRGroupIdToAtomicIdxMap()}rGroupIdToAtomicIndexMap;rGroupBondPositionMap=new Map;getAtomicIdx(e){const t=this.rGroupIdToAtomicIndexMap.get(e);return null==t?null:t}removeRGroupsFromAtomBlock(e){e.forEach(e=>{if(null==this.rGroupIdToAtomicIndexMap.get(e))throw new Error(`Cannot find atomic index for R group ${e}`)});const t=Array.from(this.rGroupIdToAtomicIndexMap.entries()).filter(([t,n])=>e.includes(t)).map(([e,t])=>t);this.atoms.deleteAtoms(t)}removeRGroups(e){this.removeRGroupsFromAtomBlock(e),e.forEach(e=>{const t=this.replaceRGroupInBondsByDummy(e);this.rGroupBondPositionMap.set(e,t)})}replaceRGroupInBondsByDummy(e){const t=this.rGroupIdToAtomicIndexMap.get(e);if(this.rGroupBondPositionMap.has(e))throw new Error(`R group ${e} is already handled`);const n=this.bonds.getPositionsInBonds(t+1);if(0===n.length)throw new Error(`Cannot find position for R group ${e}`);if(n.length>1)throw new Error(`More than one position for R group ${e}`);const i=n[0];return this.bonds.replacePositionsInBondsByDummy([i]),this.bonds.removeAtomIdFromBonds(t+1),this.removeRGroupFromAtomicIdxMap(e,t),i}removeRGroupFromAtomicIdxMap(e,t){this.rGroupIdToAtomicIndexMap.delete(e);for(const[e,n]of this.rGroupIdToAtomicIndexMap)n>t&&this.rGroupIdToAtomicIndexMap.set(e,n-1)}deleteBondLineWithSpecifiedRGroup(e){const t=this.rGroupBondPositionMap.get(e);if(!t)throw new Error(`Cannot find position for R group ${e}`);const{bondLineIdx:n}=t;this.bonds.deleteBondLines([n]),this.rGroupBondPositionMap.delete(e),this.rGroupIdToAtomicIndexMap.delete(e),this.rGroupBondPositionMap.forEach(e=>{e.bondLineIdx>n&&(e.bondLineIdx-=1)})}replaceRGroupWithAttachmentAtom(e,t){const n=this.rGroupBondPositionMap.get(e);if(!n)throw new Error(`Cannot find position for R group ${e}`);const{bondLineIdx:i,nodeIdx:o}=n;this.bonds.bondedAtoms[i][o]=t}getAttachmentAtomIdByRGroupId(e){const t=this.rGroupBondPositionMap.get(e);if(!t)throw new Error(`Cannot find position for R group ${e}`);const{bondLineIdx:n,nodeIdx:i}=t;return this.bonds.bondedAtoms[n][(i+1)%2]}capRGroups(e,t){this.rGroupIdToAtomicIndexMap.forEach((n,i)=>{const o=e.find(e=>e.rGroupId===i)??e[i-1];o.isSimple?o.element===Bi.m?(this.removeRGroups([i]),this.deleteBondLineWithSpecifiedRGroup(i)):this.atoms.replaceRGroupSymbolByElement(n,o.element):this.capWithComplexGroup(n,o.smiles,t)})}capWithComplexGroup(e,t,n){const i=t.replace(/\[\*:\d+\]/g,"[Xe]"),o=n.get_mol(i);if(!o)throw new Error(`Cannot parse cap group SMILES: ${t}`);let s;try{s=o.get_v3Kmolblock()}finally{o.delete()}const r=Ot.getInstance(s),a=r.getAtomLines(),l=r.pairsOfBondedAtoms,c=r.getBondLines(),u=r.x,h=r.y,d=r.atomTypes;let m=-1;for(let e=0;e<d.length;e++)if("Xe"===d[e]){m=e;break}if(-1===m)throw new Error(`Cannot find placeholder atom in cap group SMILES: ${t}`);let p=-1;for(let e=0;e<l.length;e++){const[t,n]=l[e];if(t===m+1){p=n-1;break}if(n===m+1){p=t-1;break}}if(-1===p)throw new Error(`Cannot find attachment atom in cap group SMILES: ${t}`);const g=this.atoms.atomCoordinates[e],f=g.x-u[p],y=g.y-h[p],b=d[p];this.atoms.replaceRGroupSymbolByElement(e,b);const w=new Map;w.set(p+1,e+1);let v=this.atoms.count+1;for(let e=0;e<a.length;e++){if(e===m||e===p)continue;const t=u[e]+f,n=h[e]+y;this.atoms.appendAtomLine(a[e],t,n),w.set(e+1,v),v++}for(let e=0;e<l.length;e++){const[t,n]=l[e];if(t===m+1||n===m+1)continue;const i=w.get(t),o=w.get(n);this.bonds.appendBondLine(c[e],[i,o])}}}class Ui{coordinates=[];rawAtomLines=[];get count(){return this.coordinates.length}get atomCoordinates(){return this.coordinates}replaceRGroupSymbolByElement(e,t){this.rawAtomLines[e]=this.rawAtomLines[e].replace("R#",t)}appendAtomLine(e,t,n){this.rawAtomLines.push(e),this.coordinates.push({x:t,y:n})}deleteAtoms(e){this.coordinates=this.coordinates.filter((t,n)=>!e.includes(n)),this.rawAtomLines=this.rawAtomLines.filter((t,n)=>!e.includes(n))}shift(e){this.coordinates=this.coordinates.map(t=>{const n=t.x+e.x,i=t.y+e.y;if(isNaN(n)||isNaN(i))throw new Error(`Cannot shift coordinates by ${e.x}, ${e.y}`);return{x:n,y:i}})}rotate(e){this.coordinates=this.coordinates.map(t=>{const n=t.x,i=t.y,o=n*Math.cos(e)-i*Math.sin(e),s=n*Math.sin(e)+i*Math.cos(e);if(isNaN(o)||isNaN(s))throw new Error(`Cannot rotate coordinates by ${e}`);return{x:o,y:s}})}}class qi extends Ui{constructor(e){super(),this.rawAtomLines=e.getAtomLines(),this.coordinates=this.rawAtomLines.map(e=>({x:parseFloat(e.substring(0,10)),y:parseFloat(e.substring(10,20))}))}get atomLines(){return this.rawAtomLines.map((e,t)=>{const n=this.coordinates[t];return`${n.x.toFixed(4).padStart(10," ")}${n.y.toFixed(4).padStart(10," ")}${e.substring(20)}`})}}class Wi{bondedAtomPairs=[];rawBondLines=[];get count(){return this.bondedAtomPairs.length}get bondedAtoms(){return this.bondedAtomPairs}appendBondLine(e,t){this.rawBondLines.push(e),this.bondedAtomPairs.push(t)}deleteBondLines(e){this.rawBondLines=this.rawBondLines.filter((t,n)=>!e.includes(n)),this.bondedAtomPairs=this.bondedAtomPairs.filter((t,n)=>!e.includes(n))}getPositionsInBonds(e){const t=[];return this.bondedAtomPairs.forEach((n,i)=>{n.forEach((n,o)=>{n===e&&t.push({bondLineIdx:i,nodeIdx:o})})}),t}replacePositionsInBondsByDummy(e,t){null==t&&(t=-1),e.forEach(e=>{const{bondLineIdx:n,nodeIdx:i}=e;this.bondedAtomPairs[n][i]=t})}removeAtomIdFromBonds(e){this.bondedAtomPairs=this.bondedAtomPairs.map(t=>t.map(t=>t>e?t-1:t))}shift(e){this.bondedAtomPairs=this.bondedAtomPairs.map(t=>t.map(t=>t+e))}}class Yi extends Wi{constructor(e){super(),this.rawBondLines=e.getBondLines(),this.bondedAtomPairs=this.rawBondLines.map(e=>[parseInt(e.substring(0,3)),parseInt(e.substring(3,6))])}getBondLines(){return this.bondedAtomPairs.map((e,t)=>{if(e.some(e=>-1===e))throw new Error(`Bonded pair ${e} contains -1`);return`${e[0].toString().padStart(3," ")}${e[1].toString().padStart(3," ")}${this.rawBondLines[t].substring(6)}`})}}class ji extends Gi{constructor(e,t){super(t);const n=Ot.getInstance(e);this.atoms=new qi(n),this.bonds=new Yi(n),this.rGroups=new Vi(n,this.atoms,this.bonds),this.shiftMonomerToDefaultPosition()}}class Ki extends Ui{molfileHandler;constructor(e){super(),this.molfileHandler=e,this.rawAtomLines=e.getAtomLines(),this.coordinates=this.getCoordinates()}getCoordinates(){const e=this.molfileHandler.x,t=this.molfileHandler.y;return Array.from(e).map((e,n)=>({x:e,y:t[n]}))}get atomLines(){const e=/^(M V30 [^-]*)(-?\d+\.\d+)( )(-?\d+\.\d+)( -?\d+\.\d+.*)$/,t=/\sRGROUPS=\(\d+(\s+\d+)*\)/;return this.rawAtomLines.map((n,i)=>{const o=this.coordinates[i],s=o.x.toFixed(4)+"00",r=o.y.toFixed(4)+"00";return n.replace(e,(e,t,n,i,o,a)=>t+s+i+r+a).replace(t,"")})}replaceRGroupSymbolByElement(e,t){super.replaceRGroupSymbolByElement(e,t);const n=this.rawAtomLines[e].substring(3).split(" ");n.length>7&&(this.rawAtomLines[e]=`M ${n.slice(0,7).join(" ")}`)}}class zi extends Wi{molfileHandler;constructor(e){super(),this.molfileHandler=e,this.rawBondLines=e.getBondLines(),this.bondedAtomPairs=this.getBondedAtomPairs()}getBondedAtomPairs(){return this.molfileHandler.pairsOfBondedAtoms.map(e=>[e[0],e[1]])}getBondLines(){const e=/^(M\s+V30\s+\d+\s+\d+\s+)(\d+)(\s+)(\d+)(.*)$/;return this.bondedAtomPairs.map((t,n)=>{if(t.some(e=>-1===e))throw new Error(`Bonded pair ${t} contains -1`);return this.rawBondLines[n].replace(e,(e,n,i,o,s,r)=>`${n}${t[0]}${o}${t[1]}${r}`)})}}class Zi extends Gi{constructor(e,t){super(t);const n=Ot.getInstance(e);this.atoms=new Ki(n),this.bonds=new zi(n),this.rGroups=new Vi(n,this.atoms,this.bonds),this.shiftMonomerToDefaultPosition()}}class Xi{static getInstance(e,t){if(Ot.isMolfileV2K(e))return new ji(e,t);if(Ot.isMolfileV3K(e))return new Zi(e,t);throw new Error("Unsupported molfile version")}}class Qi{monomerSymbol;monomerIdx;helm;rdKitModule;monomerLib;molfileWrapper;capGroupInfo=[];static molfileV2KToV3KCache=new Map;constructor(e,t,n,i,o,s){this.monomerSymbol=e,this.monomerIdx=t,this.helm=n,this.rdKitModule=o,this.monomerLib=s;const r=this.getLibraryMonomerObject();let a=r.molfile;Ot.isMolfileV2K(a)&&(a=this.convertMolfileToV3KFormat(a,e,o)),this.molfileWrapper=Xi.getInstance(a,e),this.capGroupInfo=this.getCapGroupInfo(r),this.removeRGroups(n.bondedRGroupsMap[t]),this.capRemainingRGroups(),this.shiftCoordinates(i)}get atomCount(){return this.molfileWrapper.atomCount}get bondCount(){return this.molfileWrapper.bondCount}convertMolfileToV3KFormat(e,t,n){if(Qi.molfileV2KToV3KCache.has(e))return Qi.molfileV2KToV3KCache.get(e);let i=null;try{if(i=n.get_mol(e,JSON.stringify({mergeQueryHs:!0})),i){const t=i.get_v3Kmolblock();return Qi.molfileV2KToV3KCache.set(e,t),t}throw new Error(`Cannot convert ${t} to molV3000`)}finally{i?.delete()}}getLibraryMonomerObject(){const e=this.helm.getPolymerTypeByMonomerIdx(this.monomerIdx),t=this.monomerLib.getMonomer(e,this.monomerSymbol);if(!t)throw new Error(`Monomer ${this.monomerSymbol} is not found in the library`);return t}getCapGroupInfo(e){return e.rgroups.map((e,t)=>{const n=e.capGroupSmiles||e.capGroupSMILES;let i=e.label[1];if(!i||!parseInt(i)||isNaN(parseInt(i))){const e=n?.match(/\[\*:(\d)\]/);e&&e[1]&&(i=e[1])}i&&parseInt(i)&&!isNaN(parseInt(i))||(i=`${t+1}`);const o=n.replace(/(\[|\]|\*|:|\d)/g,"");return{element:o,smiles:n,isSimple:(s=o,/^[A-Z][a-z]?$/.test(s)),rGroupId:parseInt(i)};var s})}shiftCoordinates(e){this.molfileWrapper.shiftCoordinates(e)}getAtomLines(){return this.molfileWrapper.getAtomLines()}getBondLines(){return this.molfileWrapper.getBondLines()}removeRGroups(e){this.molfileWrapper.removeRGroups(e)}capRemainingRGroups(){this.molfileWrapper.capRGroups(this.capGroupInfo,this.rdKitModule)}replaceRGroupWithAttachmentAtom(e,t){this.molfileWrapper.replaceRGroupWithAttachmentAtom(e,t)}getAttachmentAtomByRGroupId(e){return this.molfileWrapper.getAttachmentAtomByRGroupId(e)}deleteBondLineWithSpecifiedRGroup(e){this.molfileWrapper.deleteBondLineWithSpecifiedRGroup(e)}shiftBonds(e){this.molfileWrapper.shiftBonds(e)}}class Ji{rdKitModule;monomerLib;constructor(e,t,n){this.rdKitModule=t,this.monomerLib=n,this.helm=new ki.f(e)}monomerWrappers=[];helm;addMonomer(e,t,n){if(e===pe.b9[ue.Hi.HELM])return;const i=this.monomerWrappers.length,o=new Qi(e,i,this.helm,n,this.rdKitModule,this.monomerLib);this.monomerWrappers.push(o)}getAtomNumberShifts(){const e=[];let t=0;return this.monomerWrappers.forEach(n=>{e.push(t),t+=n.getAtomLines().length}),e}restoreBondsBetweenMonomers(){this.helm.bondData.forEach(e=>{const t=e.map(e=>e.monomerIdx),n=e.map(e=>e.rGroupId),i=t.map(e=>this.monomerWrappers[e]),o=i[1].getAttachmentAtomByRGroupId(n[1]);i[0].replaceRGroupWithAttachmentAtom(n[0],o),i[1].deleteBondLineWithSpecifiedRGroup(n[1])})}compileToMolfile(){const e=[],t=[],n=this.getAtomNumberShifts();this.monomerWrappers.forEach((e,t)=>{e.shiftBonds(n[t])}),this.restoreBondsBetweenMonomers();const i=new Hi.Cg;for(const[n,o]of ee().enumerate(this.monomerWrappers)){const s=e.length,r=t.length;e.push(...n.getAtomLines()),t.push(...n.getBondLines());const a="RNA"==this.helm.getPolymerTypeByMonomerIdx(o)?Fe.o.NUCLEOTIDE:Fe.o.AA;i.set(o,{biotype:a,symbol:n.monomerSymbol,atoms:ee().count(s).take(n.atomCount).toArray(),bonds:ee().count(r).take(n.bondCount).toArray()})}const o=e.length,s=t.length;return{molfile:[this.getV3KHeader(o,s),this.getV3KAtomBlock(e),this.getV3KBondBlock(t),"M V30 END CTAB\nM END"].join("\n"),monomers:i}}getV3KHeader(e,t){return`\n Datagrok\n\n 0 0 0 0 0 0 0 0 0 0999 V3000\nM V30 BEGIN CTAB\nM V30 COUNTS ${e} ${t} 0 0 1`}getV3KAtomBlock(e){const t=/^(M V30 )(\d+)( .*)$/;return["M V30 BEGIN ATOM",...e.map((e,n)=>{const i=n+1;return e.replace(t,(e,t,n,o)=>t+i+o)}),"M V30 END ATOM"].join("\n")}getV3KBondBlock(e){const t=/^(M V30 )(\d+)( .*)$/;return["M V30 BEGIN BOND",...e.map((e,n)=>{const i=n+1;return e.replace(t,(e,t,n,o)=>t+i+o)}),"M V30 END BOND"].join("\n")}}class eo{constructor(e){this.molfileHandler=Ot.getInstance(e)}molfileHandler;get monomerSymbols(){return this.molfileHandler.atomTypes}getMonomerShifts(e){return{x:this.molfileHandler.x[e],y:this.molfileHandler.y[e]}}}class to{helmHelper;rdKitModule;monomerLib;constructor(e,t,n){this.helmHelper=e,this.rdKitModule=t,this.monomerLib=n}convertToSmiles(e){const t=e.dataFrame,n=this.getSmilesList(e),i=`smiles(${e.name})`,o=t?t.columns.getUnusedName(i):i;return r.Column.fromStrings(o,n.map(e=>null==e?"":e))}getSmilesList(e){return this.convertToMolfileV3KColumn(e).toList().map(e=>r.chem.convert(e,r.chem.Notation.MolBlock,r.chem.Notation.Smiles))}molV3KtoMolV3KOCL(e){try{if(!e)return"";return Fi.Molecule.fromMolfile(e).toMolfileV3().replace("STERAC1","STEABS")}catch(e){const[t,n]=(0,we.AP)(e);return Uo.logger.error(t,void 0,n),""}}getMolV3000ViaOCL(e,t){const n=e.map(e=>{if(null==e)return"";const t=e.get_v3Kmolblock();return e.delete(),t}),i=new Array(n.length),o=r.TaskBarProgressIndicator.create("Handling chirality...");for(let e=0;e<n.length;e++){i[e]=this.molV3KtoMolV3KOCL(n[e]);const t=e/n.length*100;o.update(t,`${t?.toFixed(2)}% of molecules completed`)}return o.close(),r.Column.fromStrings(t,i)}convertToRdKitBeautifiedMolfileColumn(e,t,n,i){const o=e.dataFrame,s=this.convertToMolfileV3KColumn(e).toList().map(e=>{if(""===e)return null;const t=n.get_mol(e);return t?(t.set_new_coords(),t.normalize_depiction(1),t.straighten_depiction(!0),t):null}),a=`molfile(${e.name})`,l=o?o.columns.getUnusedName(a):a;return t?this.getMolV3000ViaOCL(s,l):r.Column.fromStrings(l,s.map(e=>{if(null==e)return"";const t=e.get_v3Kmolblock();return e.delete(),t}))}convertToMolfileV3KColumn(e){const t=e.dataFrame,n=this.convertToMolfileV3K(e.toList()).map(e=>e.molfile),i=(0,Di.kA)(t,`molfileV3K(${e.name})`);return r.Column.fromList("string",i,n)}convertToMolfileV3K(e){const t=new Array(e.length);for(let n=0;n<e.length;++n){const i=e[n];if(!i){t[n]=Hi.vF.createEmpty();continue}let o;try{o=this.getPolymerMolfile(i)}catch(e){const[t,n]=(0,we.AP)(e);Uo.logger.error(t,void 0,n),o=Hi.vF.createEmpty()}t[n]=o}return t}getPolymerGraphColumn(e){const t=e.toList(),n=this.helmHelper.getMolfiles(t);return r.Column.fromStrings("mols",n)}getPolymerMolfile(e){const t=this.helmHelper.removeGaps(e),n=t.resHelm,i=new Map;for(const[e,n]of t.monomerMap?.entries()??[])i.set(n,e);const o=this.helmHelper.getMolfiles([n])[0],s=new eo(o),r=new Ji(n,this.rdKitModule,this.monomerLib);s.monomerSymbols.forEach((e,t)=>{const n=s.getMonomerShifts(t);r.addMonomer(e,t,n)});const a=r.compileToMolfile(),l=new Hi.Cg;for(const[e,t]of a.monomers.entries()){const n=i.get(e);l.set(n,t)}return new Hi.vF(a.molfile,l)}}var no=n(2738);class io{seqHelper;_column;_units;_notation;_defaultGapOriginal;_notationProvider=null;_tempReadForNotProvider=!1;get notationProvider(){return this._tempReadForNotProvider||(this._tempReadForNotProvider=!0,this._notationProvider=this._notationProvider??this._column.temp[me.j.notationProvider]??null),this._notationProvider}set notationProvider(e){this._notationProvider=e}_splitter=null;_refinerPromise=Promise.resolve();get refinerPromise(){return this._refinerPromise}runInnerDetector(){if(!this._column.temp.seqHandlerDetectorRun){this._column.temp.seqHandlerDetectorRun=!0;const e=r.Func.find({name:"detectMacromolecule",meta:{role:"semTypeDetector"}})[0];e&&e.applySync({col:this._column})}}constructor(e,t){if(this.seqHelper=t,e.type!==r.TYPE.STRING)throw new Error(`Unexpected column type '${e.type}', must be '${r.TYPE.STRING}'.`);this._column=e;let n=this._column.meta.units;if(!n&&(this.runInnerDetector(),n=this._column.meta.units,!n))throw new Error("Units are not specified in column");if(this._units=n,this._notation=this.getNotation(),[ue.Hi.BILN,ue.Hi.CUSTOM,ue.Hi.SEPARATOR].includes(this._notation)&&!this.column.getTag(ue.gp.separator)&&(this.runInnerDetector(),!this.column.getTag(ue.gp.separator)))throw new Error(`Separator tag '${ue.gp.separator}' is not set for notation '${this._notation}'.`);(this.isCustom()||this.isBiln())&&(this.notationProvider=this.column.temp[me.j.notationProvider]??null);const i=this.isFasta()?pe.b9[ue.Hi.FASTA]:this.isSeparator()?pe.b9[ue.Hi.SEPARATOR]:this.isHelm()?pe.b9[ue.Hi.HELM]:this.isCustom()||this.isBiln()?this.notationProvider?.defaultGapOriginal??pe.b9[ue.Hi.SEPARATOR]:void 0;if(null==i)throw new Error(`Unexpected defaultGapOriginal for notation '${this.notation}'`);if(this._defaultGapOriginal=i,!this.column.tags.has(ue.gp.aligned)||!this.column.tags.has(ue.gp.alphabet)||!this.column.tags.has(ue.gp.alphabetIsMultichar)&&!this.isHelm()&&this.alphabet===ue.YI.UN)if(this.isFasta())this.seqHelper.setUnitsToFastaColumn(this);else if(this.isSeparator()){const t=e.getTag(ue.gp.separator);this.seqHelper.setUnitsToSeparatorColumn(this,t)}else if(this.isHelm())this.seqHelper.setUnitsToHelmColumn(this);else{if(!this.isCustom()&&!this.isBiln())throw new Error(`Unexpected units '${this.column.meta.units}'.`);this.notationProvider?.setUnits(this)}if(!this.column.tags.has(ue.gp.alphabetIsMultichar))if(this.isHelm())this.column.setTag(ue.gp.alphabetIsMultichar,"true");else if(["UN"].includes(this.alphabet))throw new Error(`For column '${this.column.name}' of alphabet '${this.alphabet}' tag '${ue.gp.alphabetIsMultichar}' is mandatory.`);this.columnVersion=this.column.version,!this.isSeparator()||(this.isCustom()||this.isBiln())&&this.notationProvider||e.temp.seqHandlerRefined||(this._refinerPromise=this.refineSeparatorNotation(),e.temp.seqHandlerRefined=!0)}async refineSeparatorNotation(){const e=((e,t,n)=>{const i={};let o=!0,s=null;for(const t of e){const e=t?n(t):[];if(null==s?s=e.length:e.length!==s&&(o=!1),e.length>=3)for(const t of e)t in i||(i[t]=0),i[t]+=1}return{freq:i,sameLength:o}})([...new Set((this.column.length<100?ee().count(0).take(Math.min(100,this.column.length)).map(e=>this.column.get(e)):this.column.categories.slice(0,100)).map(e=>e?e.substring(0,500):"").filter(e=>0!==e.length))],0,e=>e.split(this.separator));let t=!1;const n=r.Func.find({meta:{role:"notationRefiner"}});for(const i of n)try{const n=i.prepare({col:this.column,stats:e,separator:this.separator}),o=(await n.call()).getOutputParamValue();t||=o}catch(e){console.error(e)}t&&(this._tempReadForNotProvider=!1,delete this.column.temp[me.j.seqHandler],this.column.fireValuesChanged())}static setTags(e){const t=e.column.meta.units;if([ue.Hi.FASTA,ue.Hi.SEPARATOR,ue.Hi.BILN].includes(t)){if(!e.column.getTag(ue.gp.alphabet)&&0===Object.keys(e.stats.freq).length)throw new Error("Alphabet is empty and not annotated.");let t=e.column.getTag(ue.gp.aligned);null==t&&(t=e.stats.sameLength||e.column.categories.slice(0,5).filter(e=>!!e).every(e=>e.length>100)?"SEQ.MSA":"SEQ",e.column.setTag(ue.gp.aligned,t));let n=e.column.getTag(ue.gp.alphabet);if(null==n&&(n=(0,Oe.pc)(e.stats.freq,ue.q7),e.column.setTag(ue.gp.alphabet,n)),n===ue.YI.UN){const t=Object.keys(e.stats.freq).length,n=Object.keys(e.stats.freq).some(e=>e.length>1);e.column.setTag(ue.gp.alphabetSize,t.toString()),e.column.setTag(ue.gp.alphabetIsMultichar,n?"true":"false")}}else if(t===ue.Hi.HELM){let t=e.column.getTag(ue.gp.alphabet);if(null==t){const n=ue.q7.map(e=>new no.aD(e.name,e.alphabet,.9));t=(0,Oe.p0)(e.stats.freq,n,e.defaultGapOriginal),e.column.setTag(ue.gp.alphabet,t)}}}get column(){return this._column}get length(){return this._column.length}get units(){return this._units}get notation(){return this._notation}get defaultGapOriginal(){return this._defaultGapOriginal}get separator(){const e=this.column.getTag(ue.gp.separator)??void 0;if(this.notation===ue.Hi.SEPARATOR&&null==e)throw new Error(`Separator is mandatory for column '${this.column.name}' of notation '${this.notation}'.`);return e}get aligned(){const e=this.column.getTag(ue.gp.aligned);if(!e&&(this.isFasta()||this.isSeparator()))throw new Error("Tag aligned not set");return e}get alphabet(){const e=this.column.getTag(ue.gp.alphabet);if(!e&&(this.isFasta()||this.isSeparator()))throw new Error("Tag alphabet not set");return e}get defaultBiotype(){return this.alphabet===ue.YI.RNA||this.alphabet===ue.YI.DNA?Fe.o.NUCLEOTIDE:Fe.o.AA}get helmCompatible(){return this.column.getTag(ue.gp.isHelmCompatible)}getAlphabetSize(){if(this.notation==ue.Hi.HELM||this.alphabet==ue.YI.UN){const e=this.column.getTag(ue.gp.alphabetSize);let t;if(e)t=parseInt(e);else{const e=this.stats;t=Object.keys(e.freq).length}return t}switch(this.alphabet){case ue.YI.PT:return 20;case ue.YI.DNA:case ue.YI.RNA:return 4;case"NT":return console.warn("Unexpected alphabet 'NT'."),4;default:throw new Error(`Unexpected alphabet '${this.alphabet}'.`)}}getAlphabetIsMultichar(){return this.notation===ue.Hi.HELM||this.alphabet===ue.YI.UN&&"true"===this.column.getTag(ue.gp.alphabetIsMultichar)}cached=!0;_splitted=null;columnVersion=null;getSplitted(e,t){if(this.cached&&void 0===t){this.column.version===this.columnVersion&&null!=this._splitted||(this.columnVersion=this.column.version,this._splitted=new Array(this.column.length));let t=this._splitted[e]?this._splitted[e].deref():void 0;if(!t){const n=this.column.get(e);t=this.splitter(n),this._splitted[e]=new WeakRef(t)}return t}{const n=this.column.get(e);return this.getSplitter(t)(n)}}getMonomerAtPosition(e,t,n){if(this.isCanonicalAlphabet&&this.isFasta()&&!this.getAlphabetIsMultichar()){const i=(this.column.get(e)??"")[t];return n?i===pe.b9[ue.Hi.FASTA]?pe._S:i??pe._S:i??""}const i=this.getSplitted(e);return t<0||t>=i.length?this.defaultGapOriginal:n?i.getCanonical(t):i.getOriginal(t)}getMonomersAtPosition(e,t){const n=this.column.length,i=new Array(n).fill(pe._S);if(this.isCanonicalAlphabet&&this.isFasta()&&!this.getAlphabetIsMultichar()){const o=this.column.categories,s=this.column.getRawData();for(let r=0;r<n;r++){const n=o[s[r]]??"";if(e<n.length){const o=n[e];i[r]=t?o===pe.b9[ue.Hi.FASTA]?pe._S:o??pe._S:o??""}}}else for(let o=0;o<n;o++){const n=this.getSplitted(o);e>=0&&e<n.length&&(i[o]=t?n.getCanonical(e):n.getOriginal(e))}return i}getValue(e,t){return this.column.get(e),new me.C(e,this)}getHelm(e){let t;const n=this.column.get(e);return t=this.notation===ue.Hi.HELM?n:this.notation===ue.Hi.CUSTOM||this.notation===ue.Hi.BILN?this.notationProvider.getHelm(n,{}):this.getConverter(ue.Hi.HELM)(n),t}_stats=null;get isCanonicalAlphabet(){const e=this.alphabet;return e===ue.YI.DNA||e===ue.YI.RNA||e===ue.YI.PT}get stats(){if(null==this._stats){const e={};let t=!0,n=null;const i=this.column.length;for(let o=0;o<i;++o){const i=this.getSplitted(o);null==n?n=i.length:i.length!==n&&(t=!1);for(let t=0;t<i.length;++t){const n=i.getCanonical(t);n in e||(e[n]=0),e[n]+=1}}this._stats={freq:e,sameLength:t}}return this._stats}_maxLength=null;get maxLength(){return null==this._maxLength&&(this._maxLength=0===this.column.length?0:ee().count(0).take(this.column.length).map(e=>this.getSplitted(e).length).reduce((e,t)=>e>t?e:t,0)),this._maxLength}_posList=null;get posList(){if(null==this._posList){const e=this.column.getTag(ue.gp.positionNames);this._posList=e?e.split(ue.z1).map(e=>e.trim()):ee().count(1).take(this.maxLength).map(e=>e.toString()).toArray()}return this._posList}isFasta(){return this.notation===ue.Hi.FASTA}isSeparator(){return this.notation===ue.Hi.SEPARATOR||!!this.separator}isFastaOrSeparator(){return this.isFasta()||this.isSeparator()}isHelm(){return this.notation===ue.Hi.HELM}isCustom(){return this.notation===ue.Hi.CUSTOM}isBiln(){return this.notation===ue.Hi.BILN}isRna(){return this.alphabet===ue.YI.RNA}isDna(){return this.alphabet===ue.YI.DNA}isPeptide(){return this.alphabet===ue.YI.PT}isMsa(){return!!this.aligned&&this.aligned.toUpperCase().includes("MSA")}isHelmCompatible(){return"true"===this.helmCompatible}isGap(e){return!e||e===this._defaultGapOriginal}getNotation(){if(this.units.toLowerCase().startsWith(ue.Hi.FASTA))return ue.Hi.FASTA;if(this.units.toLowerCase().startsWith(ue.Hi.SEPARATOR))return ue.Hi.SEPARATOR;if(this.units.toLowerCase().startsWith(ue.Hi.HELM))return ue.Hi.HELM;if(this.units.toLowerCase().startsWith(ue.Hi.CUSTOM))return ue.Hi.CUSTOM;if(this.units.toLowerCase().startsWith(ue.Hi.BILN))return ue.Hi.BILN;throw new Error(`Column '${this.column.name}' has unexpected notation '${this.units}'.`)}getHelmWrappers(){return[this.isDna()||this.isRna()||this.isHelmCompatible()?"RNA1{":"PEPTIDE1{",this.isDna()?"d(":this.isRna()?"r(":"",this.isDna()||this.isRna()?")p":"","}$$$$"]}getNewColumn(e,t,n,i){const o=this.column,s=e.toLowerCase()+"("+o.name+")",a=n??o.dataFrame?.columns.getUnusedName(s)??s,l=r.Column.fromList("string",a,i??new Array(this.column.length).fill(""));if(l.semType=r.SEMTYPE.MACROMOLECULE,l.meta.units=e,e===ue.Hi.SEPARATOR){if(!t)throw new Error(`Notation '${ue.Hi.SEPARATOR}' requires separator value.`);l.setTag(ue.gp.separator,t)}l.setTag(r.TAGS.CELL_RENDERER,e===ue.Hi.HELM?"helm":"sequence");const c=o.getTag(ue.gp.aligned);c&&l.setTag(ue.gp.aligned,c);let u=o.getTag(ue.gp.alphabet);u||this.notation!==ue.Hi.HELM||e===ue.Hi.HELM||(u=ue.YI.UN),null!=u&&l.setTag(ue.gp.alphabet,u);let h=o.getTag(ue.gp.alphabetSize);null!=u&&h&&l.setTag(ue.gp.alphabetSize,h);const d=o.getTag(ue.gp.alphabetIsMultichar);return null!=u&&void 0!==d&&l.setTag(ue.gp.alphabetIsMultichar,d),e==ue.Hi.HELM&&(h=this.getAlphabetSize().toString(),l.setTag(ue.gp.alphabetSize,h)),e===ue.Hi.BILN&&(l.setTag(ue.gp.separator,"-"),l.meta.units=ue.Hi.SEPARATOR),l}getNewColumnFromList(e,t){return this.getNewColumn(this.notation,this.separator,e,t)}static unitsStringIsValid(e){return e=e.toLowerCase(),[ue.Hi.FASTA,ue.Hi.SEPARATOR,ue.Hi.HELM].some(t=>e.startsWith(t.toLowerCase()))}static getNewColumnFromParams(e,t,n){if(!io.unitsStringIsValid(n))throw new Error("Invalid format of 'units' parameter");const i=r.Column.fromList("string",t,new Array(e).fill(""));return i.semType=r.SEMTYPE.MACROMOLECULE,i.meta.units=n,i}get splitter(){return null==this._splitter&&(this._splitter=this.getSplitter()),this._splitter}getSplitter(e){let t=null;if(t=this.notationProvider?this.notationProvider.splitter:null,t)return t;if(this.units.toLowerCase().startsWith(ue.Hi.FASTA))return null===this.column.getTag(ue.gp.alphabet)||this.getAlphabetIsMultichar()?ue.J9:Oe.tm;if(this.units.toLowerCase().startsWith(ue.Hi.SEPARATOR))return(0,ue.dh)(this.separator,e);if(this.units.toLowerCase().startsWith(ue.Hi.HELM))return ue.qp;throw new Error(`Unexpected units ${this.units} .`)}split(e){return this.splitter(e)}getDistanceFunctionName(){if(!this.isFasta())throw new Error("Only FASTA notation is supported");if(this.isMsa())return ce.Z.HAMMING;switch(this.alphabet){case ue.YI.DNA:case ue.YI.RNA:case ue.YI.PT:}return ce.Z.LEVENSHTEIN}getDistanceFunction(){return ce.V[this.getDistanceFunctionName()]()}async checkHelmCompatibility(){if(this.column.tags.has(ue.gp.isHelmCompatible))return"true"===this.column.getTag(ue.gp.isHelmCompatible);const e=(await(0,ye.pj)()).getMonomerLib().getMonomerSymbolsByType("PEPTIDE"),t=new Set(e),n=((0,ue.dh)(this.separator),new Set),i=this.column.length,o=this.column.getRawData();for(let e=0;e<i;++e){const i=o[e];if(!(i in n)){n.add(i);const o=this.getSplitted(e);for(let e=0;e<o.length;++e){const n=o.getCanonical(e);if(!t.has(n))return this.column.setTag(ue.gp.isHelmCompatible,"false"),!1}}}return this.column.setTag(ue.gp.isHelmCompatible,"true"),!0}toFasta(e){return e===ue.Hi.FASTA}toSeparator(e){return e===ue.Hi.SEPARATOR}toHelm(e){return e===ue.Hi.HELM}convertHelmToFastaSeparator(e,t,n,i){i||(i=this.toFasta(t)?pe.b9[ue.Hi.FASTA]:pe.b9[ue.Hi.SEPARATOR]),n||(n=this.toFasta(t)?"":this.separator);const o=e.startsWith("RNA"),s=(0,ue.qp)(e),r=[];for(let e=0;e<s.length;++e){let n=s.getOriginal(e);if(o&&(n=n.replace(de.EK,"$1")),n===pe.b9[ue.Hi.HELM])r.push(i);else if(this.toFasta(t)&&n.length>1){const e="["+n+"]";r.push(e)}else r.push(n)}return r.join(n)}convert(e,t){if(this.isCustom()&&e===ue.Hi.HELM){if(!this.notationProvider||!this.notationProvider.getHelm)throw new Error("Notation provider with getHelm function is required for custom notation conversion.");const n=this.getNewColumn(e,t);return n.init(e=>{const t=this.column.get(e);return this.notationProvider.getHelm(t,{})}),n}{const n=this.getJoiner({notation:e,separator:t}),i=this.getNewColumn(e,t);return i.init(e=>{const t=this.getSplitted(e);return n(t)}),i}}getRegion(e,t,n){const i=this.getNewColumn(this.notation,this.separator);i.name=n;const o=e??0,s=t??this.maxLength-1,r=this.getJoiner(),a=s-o+1,l=pe.b9[this.notation];i.init(e=>{const t=this.getSplitted(e),n=new Array(a);for(let e=0;e<a;++e){const i=o+e;n[e]=i<t.length?t.getOriginal(i):l}return r(new Oe.Mu(n,l))});const c=e=>{const t=e.split(",").map(e=>e.trim()),n=new Array(a);for(let e=0;e<a;++e){const i=o+e;n[e]=i<t.length?t[i]:"?"}return n.join(ue.z1)},u=this.column.getTag(ue.gp.positionNames);u&&i.setTag(ue.gp.positionNames,c(u));const h=this.column.getTag(ue.gp.positionLabels);return h&&i.setTag(ue.gp.positionLabels,c(h)),i}_joiner=void 0;get joiner(){return this._joiner||(this._joiner=this.getJoiner()),this._joiner}getJoiner(e){const t=e?e.notation:this.notation,n=e?e.separator:this.separator;let i;const o=this;switch(t){case ue.Hi.FASTA:i=function(e){return o.joinToFasta(e,o.isHelm())};break;case ue.Hi.SEPARATOR:if(!n)throw new Error(`Separator is mandatory for notation '${t}'.`);i=function(e){return oo(e,n,o.isHelm())};break;case ue.Hi.HELM:{const e=o.alphabet===ue.YI.DNA||o.alphabet===ue.YI.RNA,t=o.getHelmWrappers();i=function(n){return so(n,t,e)};break}case ue.Hi.BILN:i=function(e){return ro(e)};break;default:throw new Error(`Unexpected notation '${t}'.`)}return i}getConverter(e,t=void 0){if(e===ue.Hi.SEPARATOR&&!t)throw new Error(`Target separator is not specified for target units '${ue.Hi.SEPARATOR}'.`);const n=this;if(e===ue.Hi.FASTA)return function(e){return n.convertToFasta(e)};if(e===ue.Hi.HELM)return function(e){return n.convertToHelm(e)};if(e===ue.Hi.SEPARATOR)return function(e){return n.convertToSeparator(e,t)};if(e===ue.Hi.BILN)return function(e){return n.convertToBiln(e)};throw new Error("Unexpected target units '"+e+"'.")}static forColumn(e,t){let n=e.temp[me.j.seqHandler];return n&&n.columnVersion===e.version||(n=e.temp[me.j.seqHandler]=new io(e,t)),n}joinToFasta(e,t){const n=new Array(e.length);for(let i=0;i<e.length;++i){const o=e.getOriginal(i);let s=e.getOriginal(i);t&&(s=s.replace(de.EK,"$1")),o===pe._S?s=pe.b9[ue.Hi.FASTA]:!t||o!==de.q7&&o!==de.WS&&o!==de.rM?o===de.q7?s="":s.length>1&&(s="["+s+"]"):s="",n[i]=s}return n.join("")}convertToFasta(e){const t=this.splitter,n=this.isHelm()?this.splitterAsHelmNucl(e):t(e);return this.joinToFasta(n,this.isHelm())}convertToSeparator(e,t){return oo(this.isHelm()?this.splitterAsHelmNucl(e):this.splitter(e),t,this.isHelm())}convertToHelm(e){if(this.notation==ue.Hi.HELM)return e;if(this.isCustom()&&this.notationProvider?.getHelm)return this.notationProvider.getHelm(e,{});const t=this.getHelmWrappers(),n=this.isDna()||this.isRna();return so(this.splitter(e),t,n)}convertToBiln(e){return this.notation==ue.Hi.BILN?e:ro(this.splitter(e))}splitterAsHelmNucl(e){const t=this.splitter(e),n=new Array(t.length),i=e.startsWith("DNA"),o=e.startsWith("RNA");for(let e=0;e<t.length;++e){let s=t.getOriginal(e);(i||o)&&(s=s.replace(de.EK,"$1"),s!==de.q7&&s!==de.WS&&s!==de.rM||(s=null)),n[e]=s||null}return new Oe.Mu(n.filter(e=>!!e),pe.b9[ue.Hi.HELM])}getRendererBack(e,t){const n=this.column.temp;let i=n.rendererBack;return i||(i=n.rendererBack=this.notationProvider?.createCellRendererBack(e,t)),i}}function oo(e,t,n){const i=[];for(let t=0;t<e.length;++t){const o=e.getCanonical(t);let s=e.getOriginal(t);n&&(s=s.replace(de.EK,"$1")),o!==pe._S?(!n||o!==de.q7&&o!==de.WS&&o!==de.rM)&&o!==de.q7&&i.push(s):i.push(pe.b9[ue.Hi.SEPARATOR])}return i.join(t)}function so(e,t,n){if(e.graphInfo&&(e.graphInfo.connections?.length??0)>0){const i=n?"RNA":"PEPTIDE",o="$$$",s=e.graphInfo.disjointSeqStarts,r=t[1],a=t[2],l=[];for(let t=0;t<s.length;t++){const o=s[t],c=t+1<s.length?s[t+1]:e.length,u=new Array(c-o);for(let t=o;t<c;++t){const i=e.getCanonical(t);let s=i;i===pe._S?s=pe.b9[ue.Hi.HELM]:(n&&(s=s.replace(de.EK,"$1")),s=1===s.length?`${r}${s}${a}`:`${r}[${s}]${a}`),u[t-o]=s}l.push(`${i}${t+1}{${u.join(".")}}`)}return`${l.join("|")}$${e.graphInfo.connections.map(e=>`${i}${e.seqIndex1+1},${i}${e.seqIndex2+1},${e.monomerIndex1+1}:R${e.rGroup1}-${e.monomerIndex2+1}:R${e.rGroup2}`).join("|")}${o}V2.0`}{const[i,o,s,r]=t,a=new Array(e.length);for(let t=0;t<e.length;++t){const i=e.getCanonical(t);let r=i;i===pe._S?r=pe.b9[ue.Hi.HELM]:(n&&(r=r.replace(de.EK,"$1")),r=1===r.length?`${o}${r}${s}`:`${o}[${r}]${s}`),a[t]=r}return`${i}${a.join(".")}${r}`}}function ro(e){const t=e=>e&&(e.includes("-")||e.includes("*")||e.includes("[R"));if(e.graphInfo&&(e.graphInfo.connections?.length??0)>0){const n=e.graphInfo.disjointSeqStarts,i=new Array(e.length);for(let n=0;n<e.length;++n){const o=e.getCanonical(n);t(o)?i[n]=`[${o}]`:i[n]=o}for(let t=0;t<e.graphInfo.connections.length;t++){const o=e.graphInfo.connections[t],s=`${t+1}`,r=o.seqIndex1,a=o.seqIndex2,l=n[r]+o.monomerIndex1,c=n[a]+o.monomerIndex2,u=`${i[l]}(${s},${o.rGroup1})`,h=`${i[c]}(${s},${o.rGroup2})`;i[l]=u,i[c]=h}return n.map((t,o)=>{const s=o+1<n.length?n[o+1]:e.length;return i.slice(t,s).join("-")}).join(".")}{const n=new Array(e.length);for(let i=0;i<e.length;++i){const o=e.getCanonical(i);t(o)?n[i]=`[${o}]`:n[i]=o}return n.join("-")}}class ao{libHelper;rdKitModule;constructor(e,t){this.libHelper=e,this.rdKitModule=t}getSeqHandler(e){return io.forColumn(e,this)}getSeqMonomers(e){const t=this.getSeqHandler(e);return Object.keys(t.stats.freq)}async getHelmToMolfileConverter(e){const t=await(0,Dt.b2)();return new to(t,this.rdKitModule,e)}helmToAtomicLevelSingle(e,t,n,i=!0){if(!e)return Hi.vF.createEmpty();const o=t.convertToMolfileV3K([e])[0];if(!o||!o.molfile)return Hi.vF.createEmpty();let s=null;try{let e=o.molfile;if(i){if(s=this.rdKitModule.get_mol(e),!s)return Hi.vF.createEmpty();s.set_new_coords(),s.normalize_depiction(1),s.straighten_depiction(!0),e=s.get_v3Kmolblock()}return n&&(e=t.molV3KtoMolV3KOCL(e)),new Hi.vF(e,o.monomers)}catch(e){const[t,n]=(0,we.AP)(e);return Uo.logger.error(t,void 0,n),Hi.vF.createEmpty()}finally{s?.delete()}}async helmToAtomicLevel(e,t,n,i){const s=i??this.libHelper.getMonomerLib(),a=e.dataFrame,l=(0,Di.qj)(a,e.name),c=await this.getHelmToMolfileConverter(s),u=e.toList(),h=new Array(e.length),d=r.Func.find({package:"Chem",name:"beautifyMols"})[0],m=r.Func.find({package:"Chem",name:"convertToV3KViaOCL"})[0];for(let n=0;n<e.length;n++)h[n]=this.helmToAtomicLevelSingle(u[n],c,t&&!m,!d).molfile;if(d){const t=await d.apply({mols:h});if(t&&Array.isArray(t)&&t.length===e.length)for(let n=0;n<e.length;n++)t[n]&&(h[n]=t[n])}if(t&&m){const t=await m.apply({mols:h});if(t&&Array.isArray(t)&&t.length===e.length)for(let n=0;n<e.length;n++)t[n]&&(h[n]=t[n]);else o.shell.warning("OCL function returned an unexpected result")}const p=r.Column.fromStrings(l,h);return p.semType=r.SEMTYPE.MOLECULE,p.meta.units=r.UNITS.Molecule.MOLBLOCK,p.setTag(".sequence-src-col",e.name),{molCol:p,warnings:[]}}setUnitsToFastaColumn(e){if(e.column.semType!==r.SEMTYPE.MACROMOLECULE||e.column.meta.units!==ue.Hi.FASTA)throw new Error(`The column of notation '${ue.Hi.FASTA}' must be '${r.SEMTYPE.MACROMOLECULE}'.`);e.column.meta.units=ue.Hi.FASTA,io.setTags(e)}setUnitsToSeparatorColumn(e,t){if(e.column.semType!==r.SEMTYPE.MACROMOLECULE)throw new Error(`The column of notation '${ue.Hi.SEPARATOR}' must be '${r.SEMTYPE.MACROMOLECULE}'.`);if(!t)throw new Error(`The column of notation '${ue.Hi.SEPARATOR}' must have the separator tag.`);e.column.meta.units=ue.Hi.SEPARATOR,e.column.setTag(ue.gp.separator,t),io.setTags(e)}setUnitsToHelmColumn(e){if(e.column.semType!==r.SEMTYPE.MACROMOLECULE)throw new Error(`The column of notation '${ue.Hi.HELM}' must be '${r.SEMTYPE.MACROMOLECULE}'`);e.column.meta.units=ue.Hi.HELM,io.setTags(e)}}async function lo(e){let t="";try{if(!e||!e.value)return t="No sequence provided",{errorText:t,mol:""};if(!(e.cell&&e.cell.dart&&e.cell.dataFrame&&e.cell.column))return t="Atomic level conversion requeires a sequence column",{errorText:t,mol:""};const n=(await Wo.getSeqHelper()).getSeqHandler(e.cell.column);if(!n)return t="No sequence handler found",{errorText:t,mol:""};let i=50;if(n.isHelm()){const t=n.getSplitted(e.cell.rowIndex);t.graphInfo?.polymerTypes?.some(e=>"RNA"!==e)||(i=150)}if((n.getSplitted(e.cell.rowIndex)?.length??100)>i)return t="Maximum number of monomers is "+i,{errorText:t,mol:""};const o=r.Column.fromStrings("singleVal",[e.value]),s=r.DataFrame.fromColumns([o]);Object.entries(e.cell.column.tags).forEach(([e,t])=>{o.setTag(e,t)}),e.cell.column.temp[me.j.notationProvider]&&(o.temp[me.j.notationProvider]=e.cell.column.temp[me.j.notationProvider]);const a=n.getSplitted(e.cell.rowIndex),l=(a.graphInfo?.connections?.length??0)>0||n.units===ue.Hi.CUSTOM,c=n.isHelm()&&new Set(a.graphInfo?.polymerTypes??[]).size>1;if(await Wo.toAtomicLevel(s,o,l||c,!1),s.columns.length<2)return t="No structure generated",{errorText:t,mol:""};const u=s.columns.byIndex(1).get(0);return u?{errorText:"",mol:u}:(t="No structure generated",{errorText:t,mol:""})}catch(e){Uo.logger.error(e)}return t="No Structure generated",{errorText:t,mol:""}}const co="#333333",uo="rgba(60, 177, 115, 0.1)",ho="rgba(240, 240, 240, 0.5)",mo="rgba(100, 100, 100, 0.3)";class po{constructor(e=yo.DEFAULT_TRACK_HEIGHT,t=yo.MIN_TRACK_HEIGHT,n=""){this.ctx=null,this.visible=!0,this.title="",this.tooltipEnabled=!1,this.tooltipContent=null,this.height=e,this.defaultHeight=e,this.minHeight=t,this.title=n}init(e){this.ctx=e}getMonomerAt(e,t,n){return null}enableTooltip(e){this.tooltipEnabled=e}setTooltipContentGenerator(e){this.tooltipContent=e}getTooltipContent(e,t){if(!this.tooltipEnabled||!this.tooltipContent)return null;const n=this.getPositionData(e)??new Map;return this.tooltipContent(e,t,n)}getPositionData(e){return null}setVisible(e){this.visible=e}getHeight(){return this.visible?this.height:0}getDefaultHeight(){return this.defaultHeight}getMinHeight(){return this.minHeight}setHeight(e){this.height=Math.max(this.minHeight,e)}resetHeight(){this.height=this.defaultHeight}isVisible(){return this.visible}setTitle(e){this.title=e}getTitle(){return this.title}}class go extends po{constructor(e=new Map,t=yo.DEFAULT_TRACK_HEIGHT,n="",i="WebLogo"){super(t,yo.DEFAULT_TRACK_HEIGHT,i),this.data=new Map,this.monomerLib=null,this.biotype="HELM_AA",this.hoveredPosition=-1,this.hoveredMonomer=null,this.data=e,this.visible=e.size>0}setHovered(e,t){this.hoveredPosition=e,this.hoveredMonomer=t}getPositionData(e){return this.data.get(e)||null}setupDefaultTooltip(){this.enableTooltip(!0),this.setTooltipContentGenerator((e,t,n)=>this.createTooltipContent(e,t,n))}createFrequencyTable(e){let t;switch(this.biotype){case"HELM_BASE":case"HELM_SUGAR":case"HELM_NUCLETIDE":t=Fe.o.NUCLEOTIDE;break;default:t=Fe.o.AA}const n=Array.from(e.values()).reduce((e,t)=>e+t,0),i={};for(const[t,o]of e.entries())i[t]=Math.max(1,Math.round(o/n*100));const o=(0,Si.F)(i,t,this.monomerLib);return o.style.fontSize="11px",o.style.marginTop="4px",o}createTooltipContent(e,t,n){const i=[];if(i.push(s.divText(`Position: ${e+1}`,{style:{fontWeight:"bold",marginBottom:"6px",fontSize:"13px"}})),t&&(i.push(s.divText(`Monomer: ${t}`,{style:{marginBottom:"6px",fontSize:"13px"}})),n.has(t)&&i.push(s.divText(`${(100*n.get(t)).toFixed(2)}%`,{style:{marginBottom:"6px",fontSize:"13px"}}))),n&&n.size>0){const e=this.createFrequencyTable(n);i.push(e)}else i.push(s.divText("No data available",{style:{fontStyle:"italic",color:"#666"}}));const o=s.divV(i);return o.style.maxHeight="80vh",o}setMonomerLib(e){this.monomerLib=e}setBiotype(e){this.biotype=e}getMonomerAt(e,t,n){if(!this.ctx||!this.visible||0===this.data.size)return null;const i=this.data.get(n);if(!i||0===i.size)return null;const o=t,s=Array.from(i.entries()).sort((e,t)=>t[1]-e[1]),r=s.reduce((e,[t,n])=>e+n,0),a=this.height;let l=0;for(const[e,t]of s){const n=t*a/r;if(o>=l&&o<l+n)return e;l+=n}return null}updateData(e){this.data=e,this.visible=e.size>0}draw(e,t,n,i,o,s,r,a){if(!this.ctx||!this.visible||0===this.data.size)return;const l=Math.floor(n/s),c=i-4,u=t+2;for(let h=0;h<l;h++)this.drawWebLogoColumn(h,e,t,n,i,o,s,r,a,u,c)}drawWebLogoColumn(e,t,n,i,o,s,r,a,l,c,u){const h=s+e-1;if(h<0||h>=a)return;const d=this.data.get(h);if(!d||0===d.size)return;const m=t+e*r,p=r-2;s+e===l&&(this.ctx.fillStyle=uo,this.ctx.fillRect(m,n,r,o)),this.ctx.fillStyle=ho,this.ctx.fillRect(m+1,c,p,u),this.drawLettersInColumn(h,m,p,c,u,d),this.drawColumnBorder(m,c,p,u)}drawLettersInColumn(e,t,n,i,o,s){const r=Array.from(s.entries()).sort((e,t)=>t[1]-e[1]),a=r.reduce((e,[t,n])=>e+n,0),l=Math.min(1,o/(a*o));let c=i;const u=i+o;for(const[i,s]of r){const r=s*o*l,a=Math.max(4,Math.floor(r));if(a<4)continue;const h=e===this.hoveredPosition&&i===this.hoveredMonomer,d=Math.min(a,u-c);if(d<4)break;this.drawLetter(i,t+1,c,n,d,h),c+=d}}drawColumnBorder(e,t,n,i){this.ctx.strokeStyle=mo,this.ctx.lineWidth=1,this.ctx.strokeRect(e+1,t,n,i)}drawLetter(e,t,n,i,o,s=!1){if(!this.ctx)return;const r=this.getMonomerBackgroundColor(e),a=this.getMonomerTextColor(e);this.ctx.fillStyle=r,this.ctx.fillRect(t,n,i,o),s&&(this.ctx.shadowColor="rgba(255, 255, 255, 0.8)",this.ctx.shadowBlur=8,this.ctx.strokeStyle="white",this.ctx.lineWidth=2,this.ctx.strokeRect(t,n,i,o),this.ctx.shadowBlur=0),this.drawLetterSeparators(t,n,i,o),this.drawLetterText(e,t,n,i,o,a)}drawLetterSeparators(e,t,n,i){this.ctx.strokeStyle="rgba(255, 255, 255, 0.4)",this.ctx.lineWidth=1,t+i<t+this.ctx.canvas.height&&(this.ctx.beginPath(),this.ctx.moveTo(e,t+i),this.ctx.lineTo(e+n,t+i),this.ctx.stroke())}drawLetterText(e,t,n,i,o,s){const r=Math.min(.8*o,.8*i);r>=7&&(this.ctx.fillStyle=s,this.ctx.font=`bold ${r}px Roboto, Roboto Local`,this.ctx.textAlign="center",this.ctx.textBaseline="middle",this.ctx.fillText(e,t+i/2,n+o/2))}getMonomerBackgroundColor(e){if(this.monomerLib)try{const t=this.monomerLib.getMonomerColors(this.biotype,e);if(t&&t.backgroundcolor)return t.backgroundcolor}catch(e){console.warn("Error getting background color from monomerLib:",e)}return"#CCCCCC"}getMonomerTextColor(e){const t=this.getMonomerBackgroundColor(e);try{const e=r.Color.fromHtml(t),n=r.Color.getContrastColor(e);return r.Color.toHtml(n)}catch(e){return console.warn("Error calculating contrast color:",e),"#000000"}}}class fo extends po{constructor(e,t=yo.DEFAULT_TRACK_HEIGHT,n="default",i="Conservation"){super(t,yo.MIN_TRACK_HEIGHT,i),this.data=e,this.colorScheme=n,this.visible=e.length>0}updateData(e){this.data=e,this.visible=e.length>0}draw(e,t,n,i,o,s,r,a){if(!this.ctx||!this.visible||0===this.data.length)return;const l=Math.floor(n/s);for(let n=0;n<l;n++){const l=o+n;if(l>r)break;const c=e+n*s,u=s,h=c+u/2;l-1<this.data.length&&(this.drawConservationBar(l-1,c,u,h,t,i),l===a&&(this.ctx.fillStyle=uo,this.ctx.fillRect(c,t,u,i)))}}drawConservationBar(e,t,n,i,o,s){if(!this.ctx)return;const r=this.data[e];this.ctx.fillStyle=ho,this.ctx.fillRect(t+2,o,n-4,s);let a="#3CB173";if("default"===this.colorScheme)r<.5?a="#E74C3C":r<.75&&(a="#F39C12");else if("rainbow"===this.colorScheme)a=r<.2?"#E74C3C":r<.4?"#FF7F00":r<.6?"#FFFF00":r<.8?"#00FF00":"#0000FF";else if("heatmap"===this.colorScheme){const e=Math.round(255*r);a=`rgb(255, ${e}, ${e})`}const l=r*s;this.ctx.fillStyle=a,this.ctx.fillRect(t+2,o+s-l,n-4,l),this.ctx.strokeStyle=mo,this.ctx.lineWidth=1,this.ctx.strokeRect(t+2,o,n-4,s),n>20&&(this.ctx.fillStyle=co,this.ctx.font="9px monospace",this.ctx.textAlign="center",this.ctx.textBaseline="middle",this.ctx.fillText(`${Math.round(100*r)}%`,i,o+s/2))}}const yo={TITLE_HEIGHT:16,TRACK_GAP:4,DOTTED_CELL_HEIGHT:30,SLIDER_HEIGHT:8,TOP_PADDING:5,DEFAULT_TRACK_HEIGHT:45,MIN_TRACK_HEIGHT:35,ANNOTATION_TRACK_HEIGHT:20},bo={BASE:yo.DOTTED_CELL_HEIGHT+yo.SLIDER_HEIGHT,WITH_TITLE:function(){return this.BASE+yo.TITLE_HEIGHT+yo.TRACK_GAP},WITH_WEBLOGO:function(){return this.WITH_TITLE()+yo.DEFAULT_TRACK_HEIGHT+yo.TRACK_GAP},WITH_BOTH:function(){return this.WITH_WEBLOGO()+yo.DEFAULT_TRACK_HEIGHT+yo.TRACK_GAP}};class wo{constructor(e,t){this.gridColumn=t,this.canvas=null,this.ctx=null,this.tracks=new Map,this.currentHoverPosition=-1,this.currentHoverTrack=null,this.currentHoverMonomer=null,this.previousHoverPosition=-1,this.previousHoverTrack=null,this.previousHoverMonomer=null,this.dataFrame=null,this.seqHandler=null,this.seqColumn=null,this.onSelectionCallback=null,this.trackButtons=[],this.userSelectedTracks=null,this.config={x:e.x||0,y:e.y||0,width:e.width||0,height:e.height||0,windowStartPosition:e.windowStartPosition||1,positionWidth:e.positionWidth||15,totalPositions:e.totalPositions||5e3,headerHeight:e.headerHeight||bo.BASE,sliderHeight:e.sliderHeight||yo.SLIDER_HEIGHT,currentPosition:e.currentPosition||1,cellBackground:void 0===e.cellBackground||e.cellBackground,sliderColor:e.sliderColor||"rgba(220, 220, 220, 0.4)",onPositionChange:e.onPositionChange||((e,t)=>{}),onHeaderHeightChange:e.onHeaderHeightChange||(()=>{}),...e},this.eventElement=s.div(),this.eventElement.style.position="absolute",this.config.canvas.parentElement?.appendChild(this.eventElement),this.state={isDragging:!1,dragStartX:0,dragMode:"none",dragStartWindowPosition:1,dragOccurred:!1},this.setupEventListeners(),this.init()}determineVisibleTracks(){const e=this.config.headerHeight,t=this.getTrack("weblogo"),n=this.getTrack("conservation"),i=this.getTrack("annotations");if(this.tracks.forEach(e=>{e.setVisible(!1),e.setHeight(yo.DEFAULT_TRACK_HEIGHT)}),e<bo.WITH_TITLE())return;let o=0;i&&(i.setVisible(!0),i.setHeight(yo.ANNOTATION_TRACK_HEIGHT),o=yo.ANNOTATION_TRACK_HEIGHT+yo.TRACK_GAP);const s=bo.WITH_WEBLOGO()+o,r=bo.WITH_BOTH()+o;if(!(e<s))if(e<r){if(t){t.setVisible(!0);const n=e-s;t.setHeight(yo.DEFAULT_TRACK_HEIGHT+n)}}else{if(t&&t.setVisible(!0),n&&n.setVisible(!0),t&&e>r){const n=e-r;t.setHeight(yo.DEFAULT_TRACK_HEIGHT+n)}this.userSelectedTracks&&(this.tracks.forEach((e,t)=>{this.userSelectedTracks[t]||e.setVisible(!1)}),e<s&&t&&t.setVisible(!1),e<r&&n&&n.setVisible(!1))}}drawTrackButtons(){const e=70;if(!this.ctx||this.config.width<280)return;this.trackButtons=[];const t=this.getTrack("conservation"),n=this.getTrack("weblogo"),i=this.getTrack("annotations"),o=t?.isVisible()??!1,s=n?.isVisible()??!1,r=i?.isVisible()??!1;let a=this.config.width-16;const l=this.config.headerHeight>=bo.WITH_TITLE()?(yo.TITLE_HEIGHT-14)/2:2;o&&s||(!o&&t&&(a-=e,this.drawTrackButton("conservation","Conservation",a,l,e,14),a-=4),!s&&n&&(a-=e,this.drawTrackButton("weblogo","WebLogo",a,l,e,14),a-=4)),!r&&i&&(a-=e,this.drawTrackButton("annotations","Annotations",a,l,e,14))}drawTrackButton(e,t,n,i,o,s,r=!1){this.ctx&&(this.trackButtons.push({id:e,label:t,x:n,y:i,width:o,height:s}),this.ctx.fillStyle=r?"rgba(100, 150, 200, 0.8)":"rgba(240, 240, 240, 0.8)",this.ctx.fillRect(n,i,o,s),this.ctx.strokeStyle=r?"rgba(70, 120, 170, 0.8)":"rgba(180, 180, 180, 0.8)",this.ctx.lineWidth=1,this.ctx.strokeRect(n,i,o,s),this.ctx.fillStyle=r?"#ffffff":"#666666",this.ctx.font="9px Roboto, Roboto Local",this.ctx.textAlign="center",this.ctx.textBaseline="middle",this.ctx.fillText(t,n+o/2,i+s/2))}handleTrackButtonClick(e,t){for(const n of this.trackButtons)if(e>=n.x&&e<=n.x+n.width&&t>=n.y&&t<=n.y+n.height)return this.snapToTrackHeight(n.id),!0;return!1}isInsideColumnHeaderArea(e,t){return t<(this.config.headerHeight>=bo.WITH_TITLE()?yo.TITLE_HEIGHT:0)}snapToTrackHeight(e){const t=this.getTrack("annotations")?yo.ANNOTATION_TRACK_HEIGHT+yo.TRACK_GAP:0;let n;if("annotations"===e)n=bo.WITH_TITLE()+t;else if("weblogo"===e)n=bo.WITH_WEBLOGO()+t;else{if("conservation"!==e)return;n=bo.WITH_BOTH()+t}this.userSelectedTracks||(this.userSelectedTracks={},this.tracks.forEach((e,t)=>{this.userSelectedTracks[t]="annotations"===t})),"annotations"===e?this.userSelectedTracks.annotations=!0:"conservation"===e?(this.userSelectedTracks.weblogo=!0,this.userSelectedTracks.conservation=!0):"weblogo"===e&&(this.userSelectedTracks.weblogo=!0),this.config.onHeaderHeightChange&&this.config.onHeaderHeightChange(n),window.requestAnimationFrame(()=>this.redraw())}resetToAutoMode(){this.userSelectedTracks=null;const e=this.getTrack("annotations")?yo.ANNOTATION_TRACK_HEIGHT+yo.TRACK_GAP:0,t=this.tracks.size>0?bo.WITH_BOTH()+e:bo.BASE;this.config.onHeaderHeightChange&&this.config.onHeaderHeightChange(t),window.requestAnimationFrame(()=>this.redraw())}drawColumnTitle(e,t,n,i){this.ctx&&i&&this.config.headerHeight>=bo.WITH_TITLE()&&(this.ctx.fillStyle="rgba(255, 255, 255, 0.95)",this.ctx.fillRect(e,t,n,yo.TITLE_HEIGHT),this.ctx.fillStyle=co,this.ctx.font="bold 13px Roboto, Roboto Local",this.ctx.textAlign="center",this.ctx.textBaseline="middle",this.ctx.fillText(i,e+n/2,t+yo.TITLE_HEIGHT/2))}clearHoverStates(){(-1!==this.previousHoverPosition||null!==this.previousHoverTrack||null!==this.previousHoverMonomer)&&(this.previousHoverPosition=-1,this.previousHoverTrack=null,this.previousHoverMonomer=null,this.tracks.forEach(e=>{e instanceof go&&e.setHovered(-1,null)}),window.requestAnimationFrame(()=>this.redraw()))}redraw(){this.draw(this.config.x,this.config.y,this.config.width,this.config.height,this.config.currentPosition,this.config.windowStartPosition,{preventDefault:()=>{}},this.seqColumn?.name)}setSelectionData(e,t,n,i){this.dataFrame=e,this.seqColumn=t,this.seqHandler=n,this.onSelectionCallback=i||null}setupTooltipHandling(){this.eventElement.addEventListener("mousemove",this.handleTooltipMouseMove.bind(this)),this.eventElement.addEventListener("mouseleave",this.handleTooltipMouseLeave.bind(this))}handleTooltipMouseMove(e){if(!this.isValid)return;const{x:t,y:n}=this.getCoords(e),i=this.config.positionWidth,o=Math.floor(t/i),r=this.config.windowStartPosition+o-1;if(r<0||r>=this.config.totalPositions)return this.hideTooltip(),void this.clearHoverStates();const a=this.config.headerHeight>=bo.WITH_TITLE()?yo.TITLE_HEIGHT:0,l=this.config.headerHeight-yo.SLIDER_HEIGHT-yo.DOTTED_CELL_HEIGHT,c=l-yo.TRACK_GAP;if(n>=l||n<a)return this.hideTooltip(),void this.clearHoverStates();let u=null,h=0;const d=[];this.tracks.forEach((e,t)=>{e.isVisible()&&d.push({id:t,track:e})});let m=c;for(const{id:e,track:t}of d){const i=m-t.getHeight();if(n>=i&&n<m){u=e,h=n-i;break}m=i-yo.TRACK_GAP}let p=null;if(u){const e=this.tracks.get(u);e&&(p=e.getMonomerAt(t,h,r))}if((this.previousHoverPosition!==r||this.previousHoverTrack!==u||this.previousHoverMonomer!==p)&&(this.previousHoverPosition=r,this.previousHoverTrack=u,this.previousHoverMonomer=p,u)){const e=this.tracks.get(u);e instanceof go&&(e.setHovered(r,p),window.requestAnimationFrame(()=>this.redraw()))}if((r!==this.currentHoverPosition||u!==this.currentHoverTrack||p!==this.currentHoverMonomer)&&(this.currentHoverPosition=r,this.currentHoverTrack=u,this.currentHoverMonomer=p,u)){const t=this.tracks.get(u);if(t){const n=t.getTooltipContent(r,p);if(n)return void s.tooltip.show(n,e.clientX+16,e.clientY+16)}}u||(this.hideTooltip(),this.clearHoverStates())}handleTooltipMouseLeave(){this.hideTooltip(),this.clearHoverStates(),window.requestAnimationFrame(()=>this.draw(this.config.x,this.config.y,this.config.width,this.config.height,this.config.currentPosition,this.config.windowStartPosition,{preventDefault:()=>{}},this.seqColumn?.name))}hideTooltip(){this.currentHoverPosition=-1,this.currentHoverTrack=null,s.tooltip.hide()}draw(e,t,n,i,o,s,r,a){if(Object.assign(this.config,{x:e,y:t,width:n,height:i,currentPosition:o,windowStartPosition:s}),!this.isValid)return void(this.eventElement.style.display="none");this.ctx.save(),this.ctx.clearRect(e,t,n,i),this.ctx.translate(e,t),this.ctx.rect(0,0,n,i),this.ctx.clip(),this.determineVisibleTracks();const l=this.config.headerHeight>=bo.WITH_TITLE();l&&yo.TITLE_HEIGHT,a&&l&&this.drawColumnTitle(0,0,n,a);const c=i-yo.SLIDER_HEIGHT,u=c-yo.DOTTED_CELL_HEIGHT,h=u-yo.TRACK_GAP,d=[],m=[];this.tracks.forEach((e,t)=>{e.isVisible()&&m.push({id:t,track:e})});let p=h;for(const{track:e}of m){const t=e.getHeight(),i=p-t;e.draw(0,i,n,t,this.config.windowStartPosition,this.config.positionWidth,this.config.totalPositions,this.config.currentPosition),d.unshift({y:i,height:t}),p=i-yo.TRACK_GAP}if(this.drawDottedCells(0,u,n,yo.DOTTED_CELL_HEIGHT,c),d.push({y:u,height:yo.DOTTED_CELL_HEIGHT}),this.config.currentPosition>=1&&this.config.currentPosition<=this.config.totalPositions){const e=this.config.positionWidth,t=this.config.currentPosition-this.config.windowStartPosition;if(t>=0&&t<Math.floor(n/e)){const n=t*e+e/2;for(let e=0;e<d.length-1;e++){const t=d[e],i=d[e+1];this.ctx.strokeStyle="rgba(60, 177, 115, 0.4)",this.ctx.lineWidth=1,this.ctx.beginPath(),this.ctx.moveTo(n,t.y+t.height),this.ctx.lineTo(n,i.y),this.ctx.stroke()}}}this.drawTrackButtons(),this.ctx.restore(),r.preventDefault(),this.setupEventElement()}drawDottedCells(e,t,n,i,o){if(!this.ctx)return;const s=this.config.totalPositions,r=this.config.positionWidth,a=this.config.currentPosition,l=this.config.windowStartPosition,c=Math.floor(n/r),u=t+yo.TOP_PADDING;this.drawSlider(e,o,n);for(let n=0;n<c;n++){const c=l+n;if(c>s)break;const h=e+n*r,d=r,m=h+d/2;this.config.cellBackground&&(this.ctx.fillStyle=n%2==0?"rgba(248, 248, 248, 0.3)":"rgba(242, 242, 242, 0.2)",this.ctx.fillRect(h,t,d,i),this.ctx.strokeStyle="rgba(220, 220, 220, 0.7)",this.ctx.beginPath(),this.ctx.moveTo(h,t),this.ctx.lineTo(h,o),this.ctx.stroke()),this.ctx.fillStyle="#999999",this.ctx.beginPath(),this.ctx.arc(m,u+5,1,0,2*Math.PI),this.ctx.fill(),(c===a||(1===c||c%10==0)&&Math.abs(c-a)>1)&&(this.ctx.fillStyle=co,this.ctx.font="12px monospace",this.ctx.textAlign="center",this.ctx.textBaseline="middle",this.ctx.fillText(c.toString(),m,u+15)),c===a&&(this.ctx.fillStyle="rgba(60, 177, 115, 0.2)",this.ctx.fillRect(h,t,d,i))}}drawSlider(e,t,n){if(!this.ctx)return;this.ctx.fillStyle=this.config.sliderColor,this.ctx.fillRect(e,t,n,yo.SLIDER_HEIGHT);const i=Math.floor(n/this.config.positionWidth),o=this.config.windowStartPosition,s=this.config.totalPositions-i,r=this.sliderWidth,a=s<=0?0:(o-1)/s*(n-r),l=s<=0?n:r;if(this.ctx.fillStyle="rgba(150, 150, 150, 0.5)",this.ctx.fillRect(e+a,t,l,yo.SLIDER_HEIGHT),this.config.currentPosition>=1&&this.config.currentPosition<=this.config.totalPositions){const i=(this.config.currentPosition-1)/(this.config.totalPositions-1),o=Math.round(i*n);this.ctx.fillStyle="#3CB173",this.ctx.fillRect(e+o-1,t-2,3,yo.SLIDER_HEIGHT+4)}}setupEventElement(){this.eventElement.style.display="block",this.eventElement.style.left=`${this.config.x}px`,this.eventElement.style.top=`${this.config.y}px`,this.eventElement.style.width=`${this.config.width}px`,this.eventElement.style.height=`${this.config.height}px`}getCoords(e){const t=this.canvas.getBoundingClientRect();return{x:e.clientX-t.left-this.config.x,y:e.clientY-t.top-this.config.y}}isInHeaderArea(e){const{x:t,y:n}=this.getCoords(e);return t>=0&&t<=this.config.width&&n>=0&&n<=this.config.headerHeight}get positionWidth(){return this.config.positionWidth}set positionWidth(e){this.config.positionWidth=e}isInSliderArea(e){const{y:t}=this.getCoords(e),n=this.config.headerHeight-yo.SLIDER_HEIGHT;return t>n&&t<n+yo.SLIDER_HEIGHT}get sliderWidth(){const e=this.config.width/this.config.totalPositions*(this.config.width/this.config.positionWidth);return Math.max(e,20)}isInSliderDraggableArea(e){const{x:t,y:n}=this.getCoords(e),i=this.config.headerHeight-yo.SLIDER_HEIGHT,o=Math.floor(this.config.width/this.config.positionWidth),s=this.config.windowStartPosition,r=this.config.totalPositions-o,a=r<=0?0:(s-1)/r*(this.config.width-this.sliderWidth);return n>i&&n<i+yo.SLIDER_HEIGHT&&t>=a&&t<a+this.sliderWidth}setupEventListeners(){this.eventElement.addEventListener("mousemove",e=>{this.isValid&&(this.state.isDragging&&"header"===this.state.dragMode?this.eventElement.style.cursor="grabbing":this.isInSliderDraggableArea(e)?this.eventElement.style.cursor="grab":this.isInSliderArea(e)?this.eventElement.style.cursor="pointer":this.isInHeaderArea(e)?this.eventElement.style.cursor="grab":this.eventElement.style.cursor="default")}),this.eventElement.addEventListener("mousedown",this.handleMouseDown.bind(this)),this.eventElement.addEventListener("mousemove",this.handleMouseMove.bind(this)),this.eventElement.addEventListener("mouseup",this.handleMouseUp.bind(this)),this.eventElement.addEventListener("mouseleave",this.handleMouseUp.bind(this)),this.eventElement.addEventListener("click",this.handleSelectionClick.bind(this)),this.eventElement.addEventListener("click",this.handleClick.bind(this)),this.eventElement.addEventListener("wheel",this.handleMouseWheel.bind(this)),window.addEventListener("keydown",this.handleKeyDown.bind(this))}handleSelectionClick(e){if(this.state.dragOccurred)return;if(!(this.isValid&&this.dataFrame&&this.seqColumn&&this.seqHandler))return;const{x:t,y:n}=this.getCoords(e);if(this.handleTrackButtonClick(t,n))return;if(this.isInsideColumnHeaderArea(t,n))return;const i=this.config.positionWidth,o=Math.floor(t/i),s=this.config.windowStartPosition+o-1;if(s<0||s>=this.config.totalPositions)return;const r=this.config.headerHeight>=bo.WITH_TITLE()?yo.TITLE_HEIGHT:0,a=this.config.headerHeight-yo.SLIDER_HEIGHT-yo.DOTTED_CELL_HEIGHT,l=a-yo.TRACK_GAP;if(n>=a||n<r)return;let c=null,u=0;const h=[],d=this.getTrack("weblogo");d&&d.isVisible()&&h.push({id:"weblogo",track:d});const m=this.getTrack("conservation");m&&m.isVisible()&&h.push({id:"conservation",track:m});let p=l;for(const{id:e,track:t}of h){const i=p-t.getHeight();if(n>=i&&n<p){c=e,u=n-i;break}p=i-yo.TRACK_GAP}if(c){const n=this.tracks.get(c);if(n){const i=n.getMonomerAt(t,u,s);if(i){if(this.onSelectionCallback)return void this.onSelectionCallback(s,i);this.selectRowsWithMonomerAtPosition(s,i),e.stopPropagation(),e.stopImmediatePropagation()}}}}selectRowsWithMonomerAtPosition(e,t){if(this.dataFrame&&this.seqHandler)try{const n=this.dataFrame.selection,i=this.seqHandler.getMonomersAtPosition(e,!0);n.init(e=>i[e]===t)}catch(e){console.error("Error selecting rows:",e)}}init(){if(this.canvas=this.config.canvas,!this.canvas)return void console.error("Canvas not found");const e=this.canvas.getContext("2d");e?(this.ctx=e,this.tracks.forEach(t=>t.init(e))):console.error("Failed to get 2D context from canvas")}addTrack(e,t){this.ctx&&t.init(this.ctx),this.tracks.set(e,t)}removeTrack(e){this.tracks.delete(e)}getTrack(e){return this.tracks.get(e)}updateTrack(e,t){const n=this.getTrack(e);n&&t(n)}get isValid(){const e=this.gridColumn,t=e?.grid,n=t?.horzScroll?.min||0,i=t?.horzScroll?.max||1e7;return!!this.canvas&&!!this.ctx&&this.config.height>=bo.WITH_TITLE()&&t&&(vo(e.left??0,n,i)||vo(e.right??1/0,n,i))}handleMouseDown(e){if(!this.isValid)return;const{x:t,y:n}=this.getCoords(e);this.isInSliderDraggableArea(e)?(this.state.isDragging=!0,this.state.dragMode="slider",this.state.dragStartX=t,this.handleSliderDrag(t),e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()):this.isInHeaderArea(e)&&!this.isInSliderArea(e)&&(this.state.isDragging=!0,this.state.dragMode="header",this.state.dragStartX=t,this.state.dragStartWindowPosition=this.config.windowStartPosition,e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation())}handleMouseWheel(e){if(this.isValid&&this.isInHeaderArea(e)){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();const t=e.shiftKey?Math.sign(e.deltaY):Math.sign(e.deltaX||e.deltaY),n=e.shiftKey?3:1,i=this.config.windowStartPosition+t*n,o=Math.floor(this.config.width/this.config.positionWidth),s=this.config.totalPositions-o+1;this.config.windowStartPosition=Math.max(1,Math.min(s,i)),"function"==typeof this.config.onPositionChange&&this.config.onPositionChange(this.config.currentPosition,this.getWindowRange())}}handleMouseMove(e){if(!this.state.isDragging||!this.isValid)return;const t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-this.config.x;if(this.state.dragOccurred=!0,"slider"===this.state.dragMode)this.handleSliderDrag(n);else if("header"===this.state.dragMode){const e=n-this.state.dragStartX,t=Math.round(e/this.config.positionWidth),i=Math.floor(this.config.width/this.config.positionWidth),o=this.config.totalPositions-i+1;this.config.windowStartPosition=Math.max(1,Math.min(o,this.state.dragStartWindowPosition-t)),"function"==typeof this.config.onPositionChange&&this.config.onPositionChange(this.config.currentPosition,this.getWindowRange())}e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()}detach(){this.eventElement.remove(),window.removeEventListener("keydown",this.handleKeyDown.bind(this))}handleKeyDown(e){if(this.isValid&&!(this.config.currentPosition<1)&&document.activeElement?.contains(this.eventElement)&&"block"===this.eventElement.style.display){if("ArrowLeft"===e.key||"ArrowRight"===e.key){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();const t="ArrowLeft"===e.key?-1:1,n=Math.min(Math.max(this.config.currentPosition+t,1),this.config.totalPositions);if(n===this.config.currentPosition)return;this.config.currentPosition=n;const i=Math.floor(this.config.width/this.config.positionWidth),o=this.config.windowStartPosition;(n<o||n>o+i-1)&&(this.config.windowStartPosition=t<0?n:Math.max(1,n-i+1))}else{if("Escape"!==e.key)return;this.config.currentPosition=-2,e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()}"function"==typeof this.config.onPositionChange&&this.config.onPositionChange(this.config.currentPosition,this.getWindowRange())}}handleMouseUp(){this.state.isDragging=!1,this.state.dragMode="none",this.state.dragOccurred&&setTimeout(()=>{this.state.dragOccurred=!1},0)}handleSliderDrag(e){if(!this.isValid)return;const t=this.sliderWidth,n=this.config.width-t,i=Math.max(0,Math.min(this.config.width,e)),o=Math.floor(this.config.width/this.config.positionWidth),s=Math.floor(this.config.width/this.config.positionWidth),r=this.config.totalPositions-s,a=Math.max(0,i-t/2)/n*r;this.config.windowStartPosition=Math.max(1,Math.min(a,this.config.totalPositions-o+1)),"function"==typeof this.config.onPositionChange&&this.config.onPositionChange(this.config.currentPosition,this.getWindowRange())}get headerHeight(){return this.config.headerHeight}set headerHeight(e){this.config.headerHeight=e}handleClick(e){if(this.state.dragOccurred)return;if(!this.isValid)return;e.clientX,this.canvas.getBoundingClientRect().left,e.clientY,this.canvas.getBoundingClientRect().top;const{x:t,y:n}=this.getCoords(e);if(this.handleTrackButtonClick(t,n))return e.preventDefault(),void e.stopPropagation();if(this.isInsideColumnHeaderArea(t,n))this.seqColumn&&(o.shell.o=this.seqColumn);else if(n<this.config.headerHeight-yo.SLIDER_HEIGHT&&n>=0){const e=this.config.positionWidth,n=Math.round(t/e-.5),i=this.config.windowStartPosition+n;i>=1&&i<=this.config.totalPositions&&(this.config.currentPosition=i,"function"==typeof this.config.onPositionChange&&this.config.onPositionChange(this.config.currentPosition,this.getWindowRange()))}}getWindowRange(){return{start:this.config.windowStartPosition,end:Math.min(this.config.totalPositions,this.config.windowStartPosition+Math.floor(this.config.width/this.config.positionWidth))}}updateConfig(e){Object.assign(this.config,e),this.config.currentPosition=Math.min(this.config.currentPosition,this.config.totalPositions),"function"==typeof this.config.onPositionChange&&this.config.onPositionChange(this.config.currentPosition,this.getWindowRange())}getCurrentPosition(){return this.config.currentPosition}setCurrentPosition(e){this.config.currentPosition=Math.max(1,Math.min(this.config.totalPositions,e)),"function"==typeof this.config.onPositionChange&&this.config.onPositionChange(this.config.currentPosition,this.getWindowRange())}getHeightThresholds(){return{BASE:bo.BASE,WITH_TITLE:bo.WITH_TITLE(),WITH_WEBLOGO:bo.WITH_WEBLOGO(),WITH_BOTH:bo.WITH_BOTH()}}}function vo(e,t,n){return e>=t&&e<=n}class Co extends po{constructor(e,t="Annotations"){super(20,14,t),this.tableCol=e,this.regions=[],this.posList=[],this._cacheVersion=-1,this._rebuildRegions()}hasRegions(){return this._ensureUpToDate(),this.regions.length>0}getRegionAtPosition(e){this._ensureUpToDate();for(const t of this.regions)if(e>=t.startIdx&&e<=t.endIdx)return t;return null}getTooltipContent(e,t){this._ensureUpToDate();const n=this.getRegionAtPosition(e);if(!n)return null;const i=n.sourceScheme??"",o=e<this.posList.length?this.posList[e]:"",r=[],a=document.createElement("b");return a.textContent=n.name,r.push(s.div([a],{style:{fontSize:"13px",marginBottom:"4px"}})),i&&r.push(s.divText(`Scheme: ${i}`,{style:{fontSize:"12px",color:"#555"}})),r.push(s.divText(`Range: ${n.startPos} – ${n.endPos}`,{style:{fontSize:"12px",color:"#555"}})),o&&r.push(s.divText(`Position: ${o}`,{style:{fontSize:"12px",color:"#555"}})),n.description&&r.push(s.divText(n.description,{style:{fontSize:"11px",color:"#888",marginTop:"2px"}})),s.divV(r,{style:{padding:"4px"}})}draw(e,t,n,i,o,s,r,a){if(!this.ctx||!this.visible)return;if(this._ensureUpToDate(),0===this.regions.length)return;const l=this.ctx;l.save(),l.beginPath(),l.rect(e,t,n,i),l.clip();const c=o-1,u=c+Math.ceil(n/s)+2;for(const n of this.regions){if(n.endIdx<c||n.startIdx>u)continue;const o=Math.max(n.startIdx,c),r=e+(o-c)*s,a=(Math.min(n.endIdx,u)-o+1)*s;l.fillStyle=n.color,l.globalAlpha=.35,l.fillRect(r,t,a,i),l.globalAlpha=1,l.strokeStyle=n.color,l.globalAlpha=.6,l.lineWidth=1,l.strokeRect(r+.5,t+.5,a-1,i-1),l.globalAlpha=1,l.font="bold 9px Roboto, Roboto Local, sans-serif",a>l.measureText(n.name).width+4&&(l.fillStyle="#333",l.textAlign="center",l.textBaseline="middle",l.fillText(n.name,r+a/2,t+i/2))}l.restore()}_ensureUpToDate(){this._cacheVersion!==this.tableCol.version&&(this._rebuildRegions(),this._cacheVersion=this.tableCol.version)}_rebuildRegions(){this.regions=[];const e=this.tableCol.getTag(pe.gp.annotations);if(!e)return;let t;try{t=JSON.parse(e)}catch{return}if(this.posList=this._getPosList(),0!==this.posList.length)for(const e of t){if(e.category!==St.eI.Structure)continue;if(null==e.start||null==e.end)continue;const t=this.posList.indexOf(e.start),n=this.posList.indexOf(e.end);t<0||n<0||this.regions.push({name:e.name,color:e.color??this._defaultColor(e),startIdx:t,endIdx:n,startPos:e.start,endPos:e.end,sourceScheme:e.sourceScheme,description:e.description})}}_getPosList(){const e=this.tableCol.getTag(pe.gp.positionNames);return e?e.split(", "):[]}_defaultColor(e){if(e.name.startsWith("CDR")){const t=parseInt(e.name.replace("CDR",""))-1;return St.D5.structure.CDR[t%St.D5.structure.CDR.length]}if(e.name.startsWith("FR")){const t=parseInt(e.name.replace("FR",""))-1;return St.D5.structure.FR[t%St.D5.structure.FR.length]}return"#90CAF9"}}class Ao{static conservationCache=new r.LruCache(100);static webLogoCache=new r.LruCache(100);static lastInvalidationTime=0;static CHUNK_SIZE=50;static clearAllCaches(){Ao.conservationCache=new r.LruCache(100),Ao.webLogoCache=new r.LruCache(100),Ao.lastInvalidationTime=Date.now()}static getLastInvalidationTime(){return Ao.lastInvalidationTime}static getChunkCacheKey(e,t,n){const i=e.dataFrame;return`${i.id}_${e.name}_f${i.filter.version}_${t}_${n}`}static getConservationChunk(e,t,n,i){return Ao.conservationCache.getOrCreate(i,()=>{const o=Ao.getWebLogoChunk(e,t,n,i),s=new Array(n-t).fill(0);for(let i=t;i<n;i++){const n=o.get(i);if(!n||0===n.size)continue;let r=0,a=0;const l=e.defaultGapOriginal;for(const[e,t]of n.entries())e&&e!==l&&(r+=t,t>a&&(a=t));s[i-t]=r>0?a/r:0}return s})}static getWebLogoChunk(e,t,n,i){return Ao.webLogoCache.getOrCreate(i,()=>{const i=e.column.dataFrame,o=new Map,s=i.filter.trueCount;if(s<=1)return o;for(let e=t;e<n;e++)o.set(e,new Map);const r=i.filter,a=1/s;for(let i=-1;-1!==(i=r.findNext(i,!0));){const s=e.getSplitted(i).getOriginalRegion(t,n);if(0!==s.length)for(let e=0;e<s.length;e++){const n=s[e],i=o.get(t+e);i.set(n,(i.get(n)||0)+a)}}return o})}static getConservationForViewport(e,t,n,i){const o=new Array(i).fill(0),s=Math.floor(t/Ao.CHUNK_SIZE)*Ao.CHUNK_SIZE,r=Math.ceil(n/Ao.CHUNK_SIZE)*Ao.CHUNK_SIZE;for(let t=s;t<r;t+=Ao.CHUNK_SIZE){const n=Math.min(t+Ao.CHUNK_SIZE,i),s=Ao.getChunkCacheKey(e.column,t,n),r=Ao.getConservationChunk(e,t,n,s);for(let e=0;e<r.length&&t+e<i;e++)o[t+e]=r[e]}return o}static getWebLogoForViewport(e,t,n,i){const o=new Map,s=Math.floor(t/Ao.CHUNK_SIZE)*Ao.CHUNK_SIZE,r=Math.ceil(n/Ao.CHUNK_SIZE)*Ao.CHUNK_SIZE;for(let t=s;t<r;t+=Ao.CHUNK_SIZE){const n=Math.min(t+Ao.CHUNK_SIZE,i),s=Ao.getChunkCacheKey(e.column,t,n),r=Ao.getWebLogoChunk(e,t,n,s);for(const[e,t]of r.entries())e<i&&o.set(e,t)}return o}}class To extends go{seqHandler;maxLength;lastViewportStart=-1;lastViewportEnd=-1;lastInvalidationTime=0;forceNextUpdate=!1;constructor(e,t,n=45,i="WebLogo"){super(new Map,n,"",i),this.seqHandler=e,this.maxLength=t,this.visible=e.column.dataFrame.filter.trueCount>1}forceUpdate(){this.forceNextUpdate=!0}resetViewportTracking(){this.lastViewportStart=-1,this.lastViewportEnd=-1}updateForViewport(e,t){const n=Ao.getLastInvalidationTime(),i=n>this.lastInvalidationTime;if(!(Math.abs(this.lastViewportStart-e)>=10||Math.abs(this.lastViewportEnd-t)>=10||i||this.forceNextUpdate))return;this.forceNextUpdate=!1,this.lastViewportStart=e,this.lastViewportEnd=t,this.lastInvalidationTime=n;const o=Math.max(0,e-20),s=Math.min(this.maxLength,t+20),r=Ao.getWebLogoForViewport(this.seqHandler,o,s,this.maxLength);this.updateData(r)}draw(e,t,n,i,o,s,r,a){const l=Math.ceil(n/s)+2,c=Math.min(o+l,r);this.updateForViewport(o-1,c-1),super.draw(e,t,n,i,o,s,r,a)}}class Eo extends fo{seqHandler;maxLength;lastViewportStart=-1;lastViewportEnd=-1;lastInvalidationTime=0;forceNextUpdate=!1;constructor(e,t,n=45,i="default",o="Conservation"){super([],n,i,o),this.seqHandler=e,this.maxLength=t,this.visible=e.column.dataFrame.filter.trueCount>1}forceUpdate(){this.forceNextUpdate=!0}resetViewportTracking(){this.lastViewportStart=-1,this.lastViewportEnd=-1}updateForViewport(e,t){const n=Ao.getLastInvalidationTime(),i=n>this.lastInvalidationTime;if(!(Math.abs(this.lastViewportStart-e)>=10||Math.abs(this.lastViewportEnd-t)>=10||i||this.forceNextUpdate))return;this.forceNextUpdate=!1,this.lastViewportStart=e,this.lastViewportEnd=t,this.lastInvalidationTime=n;const o=Math.max(0,e-20),s=Math.min(this.maxLength,t+20),r=Ao.getConservationForViewport(this.seqHandler,o,s,this.maxLength);this.updateData(r)}draw(e,t,n,i,o,s,r,a){const l=Math.ceil(n/s)+2,c=Math.min(o+l,r);this.updateForViewport(o-1,c-1),super.draw(e,t,n,i,o,s,r,a)}}const So="__msa-scroller-initialized",Mo="__msa-scroller-subscription";class xo extends no.$G{separator;seqHelper;seqCol;splitter;get defaultGapOriginal(){return""}static get notationName(){return pe.Hi.BILN}static get implementsFromHelm(){return!1}static convertFromHelm(e,t){throw new Error("Canonical way of converting from helm to biln must be used")}constructor(e,t,n){super(),this.separator=e,this.seqHelper=t,this.seqCol=n,this.splitter=Oe.bR.bind(this)}setUnits(){}getHelm(e,t){const n=this.splitter(e);return this.seqHelper.getSeqHandler(this.seqCol).getJoiner({notation:pe.Hi.HELM})(n)}createCellRendererBack(e,t){const n=Uo.properties.maxMonomerLength||4,i=new Po(e,t,n,this.seqHelper);return i.init().then(()=>{}),i}}class Po extends $e.Jy{constructor(e,t,n,i){super(e,t,Uo.logger,n,()=>{const e=i.getSeqHandler(t),{font:n,fontWidth:o}=$e.Jy.getFontSettings(t);return{seqHandler:e,font:n,fontCharWidth:o,separatorWidth:0,monomerToShort:Oe.zS}})}}var Lo=n(6520),Io={};Io.styleTagTransform=C(),Io.setAttributes=y(),Io.insert=g().bind(null,"head"),Io.domAPI=m(),Io.insertStyleElement=w(),h()(Lo.A,Io),Lo.A&&Lo.A.locals&&Lo.A.locals;class _o{view=null;libHelper=null;monomerLib=null;collectionNames=[];filteredNames=[];displayedCount=0;cardsContainer=null;loadMoreContainer=null;searchInput=null;currentUser="";collectionsCache=new Map;selectedCollections=new Set;cardElements=new Map;handler=new jn;static VIEW_NAME="Monomer Collections";async init(){this.libHelper=await bn.getInstance(),await this.libHelper.awaitLoaded(),this.monomerLib=this.libHelper.getMonomerLib(),this.currentUser=r.User.current().login,this.view=r.View.create(),this.view.name=_o.VIEW_NAME,this.view._mcView=this;const e=s.icons.add(()=>this.showAddCollectionDialog(),"Create new monomer collection"),t=s.iconFA("sync",()=>this.refresh(),"Refresh collections");return this.view.setRibbonPanels([[e,t]]),this.view.root.addEventListener("contextmenu",e=>{const t=e.target;if(t.closest(".monomer-collection-card")||t.closest(".monomer-collection-add-card"))return;e.preventDefault();const n=r.Menu.popup();n.item("New Collection...",()=>this.showAddCollectionDialog()),n.item("Refresh",()=>this.refresh()),n.show()}),this.view.root.addEventListener("click",e=>{const t=e.target;t.closest(".monomer-collection-card")||t.closest(".monomer-collection-add-card")||this.clearSelection()}),this.view.root.tabIndex=0,this.view.root.addEventListener("keydown",e=>{"Escape"===e.key&&this.clearSelection()}),await this.buildContent(),this.view}async buildContent(){if(!this.view)return;this.view.root.innerHTML="";const e=s.div([],{classes:"monomer-collections-view"});this.searchInput=s.input.string("Monomer Collections",{value:"",placeholder:"Search by name or tag..."}),this.searchInput.root.classList.add("monomer-collections-search");const t=this.searchInput.input;t.style.width="100%",t.style.marginBottom="12px";let n=null;t.addEventListener("input",()=>{n&&clearTimeout(n),n=setTimeout(()=>this.applyFilter(),250)}),this.cardsContainer=s.div([],{classes:"monomer-collections-grid"}),this.loadMoreContainer=s.div([],{classes:"monomer-collections-load-more"}),e.appendChild(this.searchInput.root),e.appendChild(this.cardsContainer),e.appendChild(this.loadMoreContainer),this.view.root.appendChild(e),await this.loadCollections()}async loadCollections(){try{this.collectionNames=await this.libHelper.listMonomerCollections()}catch(e){Uo.logger.error(`Error listing monomer collections: ${e instanceof Error?e.message:e.toString()}`),o.shell.error("Error loading monomer collections"),this.collectionNames=[]}this.collectionsCache.clear();for(const e of this.collectionNames)this.libHelper.readMonomerCollection(e).then(t=>{this.collectionsCache.set(e,t)}).catch(()=>{});this.applyFilter()}applyFilter(){const e=(this.searchInput?.value??"").trim().toLowerCase();this.filteredNames=e?this.collectionNames.filter(t=>{if(t.replace(/\.json$/i,"").toLowerCase().includes(e))return!0;const n=this.collectionsCache.get(t);return!!n?.tags?.some(t=>t.toLowerCase().includes(e))}):[...this.collectionNames],this.displayedCount=0,this.cardsContainer.innerHTML="",this.cardElements.clear(),this.showNextPage()}showNextPage(){const e=Math.min(this.displayedCount+19,this.filteredNames.length);for(let t=this.displayedCount;t<e;t++){const e=this.createCollectionCard(this.filteredNames[t]);this.cardsContainer.appendChild(e),this.cardElements.set(this.filteredNames[t],e)}this.displayedCount=e;const t=this.cardsContainer.querySelector(".monomer-collection-add-card");t&&t.remove(),this.cardsContainer.appendChild(this.createAddCard());const n=this.cardsContainer.querySelector(".monomer-collection-empty-state");if(n&&n.remove(),0===this.filteredNames.length){const e=0===this.collectionNames.length?'No monomer collections found. Click "+" to create one.':"No collections match your search.",t=s.div([s.divText(e)],{classes:"monomer-collection-empty-state"});this.cardsContainer.prepend(t)}if(this.loadMoreContainer.innerHTML="",this.displayedCount<this.filteredNames.length){const e=this.filteredNames.length-this.displayedCount,t=s.button(`Load more (${e} remaining)`,()=>this.showNextPage());this.loadMoreContainer.appendChild(t)}}createCollectionCard(e){const t=e.replace(/\.json$/i,""),n=s.div([t],{classes:"monomer-collection-card-title"});s.tooltip.bind(n,t);const i=s.div([n],{classes:"monomer-collection-card-header"}),a=s.div([],{classes:"monomer-collection-card-body"}),l=s.div([],{classes:"monomer-collection-card-actions"}),c=s.div([i,a,l],{classes:"monomer-collection-card"});c.dataset.collectionName=e,this.selectedCollections.has(e)&&c.classList.add("monomer-collection-card-selected"),c.addEventListener("click",t=>{const n=t.target;n.closest(".monomer-collection-card-actions")||n.closest(".monomer-collection-tag")||(t.stopPropagation(),this.handleCardClick(e,t.ctrlKey||t.metaKey))}),c.addEventListener("contextmenu",t=>{t.preventDefault(),t.stopPropagation(),this.selectedCollections.has(e)||this.handleCardClick(e,!1),this.showCardContextMenu(t)});const u=async()=>{const t=await this.libHelper.readMonomerCollection(e);if(this.collectionsCache.set(e,t),t.description){const e=s.div([t.description],{classes:"monomer-collection-card-description"});s.tooltip.bind(e,t.description),i.appendChild(e)}if(t.tags&&t.tags.length>0){const e=s.div([],{classes:"monomer-collection-card-tags"});for(const n of t.tags){const t=s.div([n],{classes:"monomer-collection-card-tag"});e.appendChild(t)}i.appendChild(e)}const n=[];if(t.updatedBy&&n.push(`by ${t.updatedBy}`),t.updatedOn)try{n.push(new Date(t.updatedOn).toLocaleDateString())}catch{}n.length>0&&i.appendChild(s.div([n.join(" | ")],{classes:"monomer-collection-card-meta"}));const a=s.div([],{classes:"monomer-collection-tags"}),c=t.monomerSymbols??[];for(const e of c){const t=s.div([e],{classes:"monomer-collection-tag"});t.addEventListener("mouseenter",()=>{if(this.monomerLib){const n=this.getMonomerTooltipSafe(e);if(n){const e=t.getBoundingClientRect();s.tooltip.show(n,e.left,e.bottom+4)}}}),t.addEventListener("mouseleave",()=>s.tooltip.hide()),t.addEventListener("click",t=>{t.stopPropagation(),o.shell.o=r.SemanticValue.fromValueType(e,Ve.uF.MONOMER)}),a.appendChild(t)}const u=s.divText(`${c.length} monomer(s)`,{style:{fontSize:"11px",color:"var(--grey-4)",marginBottom:"6px"}}),h=s.divV([u,a]),d=t.updatedBy===this.currentUser,m=s.button("Edit",()=>{d&&this.showEditCollectionDialog(e,t)}),p=s.button("Delete",()=>{d&&this.confirmDeleteCollection(e)});if(!d){for(const e of[m,p])e.style.opacity="0.4",e.style.cursor="default";s.tooltip.bind(m,"Only the author can edit"),s.tooltip.bind(p,"Only the author can delete")}return l.appendChild(m),l.appendChild(p),h};return a.appendChild(s.wait(()=>u())),c}handleCardClick(e,t){t?this.selectedCollections.has(e)?this.selectedCollections.delete(e):this.selectedCollections.add(e):(this.selectedCollections.clear(),this.selectedCollections.add(e)),this.updateCardSelectionStyles(),this.setCurrentObject()}clearSelection(){this.selectedCollections.clear(),this.updateCardSelectionStyles()}updateCardSelectionStyles(){for(const[e,t]of this.cardElements)this.selectedCollections.has(e)?t.classList.add("monomer-collection-card-selected"):t.classList.remove("monomer-collection-card-selected")}async setCurrentObject(){const e=[...this.selectedCollections];if(0===e.length)return;const t=[];for(const n of e){let e=this.collectionsCache.get(n);if(!e)try{e=await this.libHelper.readMonomerCollection(n)}catch{continue}t.push({name:n,displayName:n.replace(/\.json$/i,""),data:e})}1===t.length?o.shell.o=t[0]:t.length>1&&(o.shell.o=t)}showCardContextMenu(e){const t=r.Menu.popup(),n=[...this.selectedCollections];if(n.length<=1&&n.length>0){const e=n[0],i=this.collectionsCache.get(e);if(i){const n={name:e,displayName:e.replace(/\.json$/i,""),data:i};jn.buildContextMenu(t,n,this.handler)}}else if(n.length>1){const e=n.map(e=>{const t=this.collectionsCache.get(e);return t?{name:e,displayName:e.replace(/\.json$/i,""),data:t}:null}).filter(e=>null!==e);e.length>0&&jn.buildMultiContextMenu(t,e,this.handler)}t.show()}getMonomerTooltipSafe(e){if(!this.monomerLib)return null;const t=[Fe.o.AA,Fe.o.NUCLEOTIDE,Fe.o.CHEM,Fe.o.BLOB];for(const n of t)try{if(this.monomerLib.getWebEditorMonomer(n,e))return this.monomerLib.getTooltip(n,e)}catch(e){}return null}createAddCard(){const e=s.iconFA("plus",()=>{},"");e.style.fontSize="32px",e.style.marginBottom="8px";const t=s.span(["New Collection"]),n=s.div([e,t],{classes:"monomer-collection-add-card-content"}),i=s.div([n],{classes:"monomer-collection-add-card"});return i.addEventListener("click",()=>this.showAddCollectionDialog()),i}showAddCollectionDialog(){const e=s.input.string("Name",{nullable:!1,placeholder:"Enter collection name"}),t=s.input.string("Description",{nullable:!0,placeholder:"Optional description"}),n=s.input.string("Tags",{nullable:!0,placeholder:"Comma-separated tags"}),i=s.input.choice("Polymer Type",{items:["PEPTIDE","RNA","CHEM"],value:"PEPTIDE",nullable:!1}),r=new Yn(this.monomerLib,i.value,[],this.libHelper);i.onChanged.subscribe(()=>{r.setPolymerType(i.value)}),s.dialog({title:"New Monomer Collection"}).add(s.divV([e,t,n,i,s.element("hr"),r.root])).onOK(async()=>{const i=e.value?.trim();if(!i)return void o.shell.warning("Collection name is required");const s=r.getSelectedMonomers();if(0===s.length)return void o.shell.warning("Please select at least one monomer");const a=No(n.value);try{await this.libHelper.addOrUpdateMonomerCollection(i,s,t.value??void 0,a.length>0?a:void 0),o.shell.info(`Collection "${i}" created successfully`),await this.refresh()}catch(e){o.shell.error("Error creating collection"),Uo.logger.error(`Error creating collection: ${e instanceof Error?e.message:e.toString()}`)}}).show({resizable:!0}).root.style.width="550px",r.focus()}editCollectionPublic(e,t){this.showEditCollectionDialog(e,t)}showEditCollectionDialog(e,t){const n=e.replace(/\.json$/i,""),i=s.input.string("Name",{value:n,nullable:!1}),r=s.input.string("Description",{value:t.description??"",nullable:!0}),a=s.input.string("Tags",{value:(t.tags??[]).join(", "),nullable:!0,placeholder:"Comma-separated tags"}),l=s.input.choice("Polymer Type",{items:["PEPTIDE","RNA","CHEM"],value:"PEPTIDE",nullable:!1}),c=new Yn(this.monomerLib,l.value,[...t.monomerSymbols??[]],this.libHelper);l.onChanged.subscribe(()=>{c.setPolymerType(l.value)}),s.dialog({title:`Edit Collection: ${n}`}).add(s.divV([i,r,a,l,s.element("hr"),c.root])).onOK(async()=>{const t=i.value?.trim();if(!t)return void o.shell.warning("Collection name is required");const s=c.getSelectedMonomers();if(0===s.length)return void o.shell.warning("Please select at least one monomer");const l=No(a.value);try{t!==n&&await this.libHelper.deleteMonomerCollection(e),await this.libHelper.addOrUpdateMonomerCollection(t,s,r.value??void 0,l.length>0?l:void 0),o.shell.info(`Collection "${t}" saved successfully`),await this.refresh()}catch(e){o.shell.error("Error saving collection"),Uo.logger.error(`Error saving collection: ${e instanceof Error?e.message:e.toString()}`)}}).show({resizable:!0}).root.style.width="550px",c.focus()}confirmDeleteCollection(e){const t=e.replace(/\.json$/i,"");s.dialog({title:"Delete Collection"}).add(s.divText(`Are you sure you want to delete the collection "${t}"?`)).onOK(async()=>{try{await this.libHelper.deleteMonomerCollection(e),o.shell.info(`Collection "${t}" deleted`),await this.refresh()}catch(e){o.shell.error("Error deleting collection"),Uo.logger.error(`Error deleting collection: ${e instanceof Error?e.message:e.toString()}`)}}).show()}async refresh(){this.selectedCollections.clear(),await this.loadCollections()}}function No(e){return e?e.split(",").map(e=>e.trim()).filter(e=>e.length>0):[]}class Ro{colInput;constructor(e,t){const n=t.filter;this.colInput=s.input.column(e,{...t,filter:e=>e.semType===r.SEMTYPE.MACROMOLECULE&&(!n||n(e))});const i=s.iconFA("cut",()=>this.onRegionIconClick(),"Extract a region from the sequence");this.colInput.addOptions(i)}static create(e,t){return new Ro(e,t)}get root(){return this.colInput.root}get value(){return this.colInput.value}set value(e){this.colInput.value=e}get inputBase(){return this.colInput}onRegionIconClick(){const e=this.colInput.value;e?function(e,t){const n=Uo.seqHelper.getSeqHandler(e),i=s.input.string("Name",{value:""}),a=s.input.choice("Start Position",{value:n.posList[0],items:n.posList,onValueChanged:()=>h()}),l=s.input.choice("End Position",{value:n.posList[n.posList.length-1],items:n.posList,onValueChanged:()=>h()});let c=null;const u=()=>c?`${e.name}(${c}): ${a.value}-${l.value}`:`${e.name}:${a.value}-${l.value}`,h=()=>{i.value||i.input.setAttribute("placeholder",u())};h();const d=function(e,t,n,i){let o=null;const r=e.getTag(ue.gp.annotations);if(r)try{const e=JSON.parse(r).filter(e=>e.category===St.eI.Structure&&e.start&&e.end);e.length>0&&(o=e.map(e=>({name:e.name,start:e.start,end:e.end})))}catch{}if(!o){const t=e.getTag(ue.gp.regions);if(t)try{o=JSON.parse(t)}catch{}}if(!o||0===o.length)return null;const a=["",...o.map(e=>`${e.name}: ${e.start}-${e.end}`)];return s.input.choice("Region",{value:"",items:a,onValueChanged:e=>{if(!e)return void i?.(null);const s=o.find(t=>`${t.name}: ${t.start}-${t.end}`===e);s&&(t.value=s.start,n.value=s.end,i?.(s.name))}})}(e,a,l,e=>{c=e,h()}),m=[];d&&m.push(d),m.push(i,a,l);const p=s.dialog({title:"Get Region"}).add(s.inputs(m)).onOK(()=>{const n=r.TaskBarProgressIndicator.create("Getting region...");try{const n=i.value||u(),o=Ii(e,a.value,l.value,n);e.dataFrame.columns.add(o),o.setTag(r.TAGS.CELL_RENDERER,"sequence"),t?.(o)}catch(e){o.shell.error(e.toString())}finally{n.close()}});p.show()}(e,e=>{this.colInput.value=e}):o.shell.warning("Select a macromolecule column first.")}}var $o,Oo,Ho=n(6839),Do=n(9422),Fo=n(9287),ko=n(9036);!function(e){e.embed=async function(e){return await o.functions.call("Bio:Embed",{molecule:e})},e.molToHelmConverterPy=async function(e,t,n){return await o.functions.call("Bio:MolToHelmConverterPy",{moleculesDataframe:e,moleculesColumn:t,libraryFile:n})},e.sequenceGenerator=async function(e,t,n,i,s,r,a,l,c,u,h,d,m,p,g,f,y){return await o.functions.call("Bio:SequenceGenerator",{clusters:e,num_sequences:t,alphabet_key:n,motif_length:i,max_variants_position:s,random_length:r,dispersion:a,activity_range:l,cliff_probability:c,cliff_strength:u,cliff_strength_dispersion:h,assay_noise_levels:d,assay_scales:m,disable_negatives:p,fasta_separator:g,helm_library_file:f,helm_connection_mode:y})}}($o||($o={})),function(e){e.test1=async function(){return await o.functions.call("Bio:Test1",{})},e.getMonomerLibHelper=async function(){return await o.functions.call("Bio:GetMonomerLibHelper",{})},e.initBio=async function(){return await o.functions.call("Bio:InitBio",{})},e.sequenceTooltip=async function(e){return await o.functions.call("Bio:SequenceTooltip",{col:e})},e.standardiseMonomerLibrary=async function(e){return await o.functions.call("Bio:StandardiseMonomerLibrary",{library:e})},e.matchWithMonomerLibrary=async function(e,t,n){return await o.functions.call("Bio:MatchWithMonomerLibrary",{table:e,molecules:t,polymerType:n})},e.getBioLib=async function(){return await o.functions.call("Bio:GetBioLib",{})},e.getSeqHandler=async function(e){return await o.functions.call("Bio:GetSeqHandler",{sequence:e})},e.getRegionPanel=async function(e){return await o.functions.call("Bio:GetRegionPanel",{seqCol:e})},e.libraryPanel=async function(e){return await o.functions.call("Bio:LibraryPanel",{seqColumn:e})},e.getRegionEditor=async function(e){return await o.functions.call("Bio:GetRegionEditor",{call:e})},e.splitToMonomersEditor=async function(e){return await o.functions.call("Bio:SplitToMonomersEditor",{call:e})},e.sequenceSpaceEditor=async function(e){return await o.functions.call("Bio:SequenceSpaceEditor",{call:e})},e.seqActivityCliffsEditor=async function(e){return await o.functions.call("Bio:SeqActivityCliffsEditor",{call:e})},e.customSequenceCellRenderer=async function(){return await o.functions.call("Bio:CustomSequenceCellRenderer",{})},e.fastaSequenceCellRenderer=async function(){return await o.functions.call("Bio:FastaSequenceCellRenderer",{})},e.separatorSequenceCellRenderer=async function(){return await o.functions.call("Bio:SeparatorSequenceCellRenderer",{})},e.bilnSequenceCellRenderer=async function(){return await o.functions.call("Bio:BilnSequenceCellRenderer",{})},e.refineNotationProviderForBiln=async function(e,t,n){return await o.functions.call("Bio:RefineNotationProviderForBiln",{col:e,stats:t,separator:n})},e.macroMolColumnPropertyPanel=async function(e){return await o.functions.call("Bio:MacroMolColumnPropertyPanel",{molColumn:e})},e.compositionAnalysisWidget=async function(e){return await o.functions.call("Bio:CompositionAnalysisWidget",{sequence:e})},e.monomerInfoPanel=async function(e){return await o.functions.call("Bio:MonomerInfoPanel",{monomerSv:e})},e.macromoleculeDifferenceCellRenderer=async function(){return await o.functions.call("Bio:MacromoleculeDifferenceCellRenderer",{})},e.sequenceAlignment=async function(e,t,n,i,s){return await o.functions.call("Bio:SequenceAlignment",{alignType:e,alignTable:t,gap:n,seq1:i,seq2:s})},e.webLogoViewer=async function(){return await o.functions.call("Bio:WebLogoViewer",{})},e.vdRegionsViewer=async function(){return await o.functions.call("Bio:VdRegionsViewer",{})},e.getRegion=async function(e,t,n,i){return await o.functions.call("Bio:GetRegion",{sequence:e,start:t,end:n,name:i})},e.getRegionTopMenu=async function(e,t,n,i,s){return await o.functions.call("Bio:GetRegionTopMenu",{table:e,sequence:t,start:n,end:i,name:s})},e.applyNumberingScheme=async function(){return await o.functions.call("Bio:ApplyNumberingScheme",{})},e.scanLiabilities=async function(){return await o.functions.call("Bio:ScanLiabilities",{})},e.manageAnnotations=async function(){return await o.functions.call("Bio:ManageAnnotations",{})},e.sequenceColumnInput=async function(e,t){return await o.functions.call("Bio:SequenceColumnInput",{name:e,options:t})},e.activityCliffs=async function(e,t,n,i,s,r,a,l,c){return await o.functions.call("Bio:ActivityCliffs",{table:e,molecules:t,activities:n,similarity:i,methodName:s,similarityMetric:r,preprocessingFunction:a,options:l,demo:c})},e.seqActivityCliffsInitFunction=async function(e){return await o.functions.call("Bio:SeqActivityCliffsInitFunction",{sp:e})},e.seqActivityCliffsTransform=async function(e,t,n,i,s,r,a,l,c){return await o.functions.call("Bio:SeqActivityCliffsTransform",{table:e,molecules:t,activities:n,similarity:i,methodName:s,similarityMetric:r,options:a,isDemo:l,axesNames:c})},e.macromoleculePreprocessingFunction=async function(e,t,n,i,s){return await o.functions.call("Bio:MacromoleculePreprocessingFunction",{col:e,metric:t,gapOpen:n,gapExtend:i,fingerprintType:s})},e.helmPreprocessingFunction=async function(e,t){return await o.functions.call("Bio:HelmPreprocessingFunction",{col:e,_metric:t})},e.sequenceSpaceTopMenu=async function(e,t,n,i,s,r,a,l,c){return await o.functions.call("Bio:SequenceSpaceTopMenu",{table:e,molecules:t,methodName:n,similarityMetric:i,plotEmbeddings:s,preprocessingFunction:r,options:a,clusterEmbeddings:l,isDemo:c})},e.sequenceSpaceTransform=async function(e,t,n,i,s,r,a,l,c){return await o.functions.call("Bio:SequenceSpaceTransform",{table:e,molecules:t,methodName:n,similarityMetric:i,plotEmbeddings:s,options:r,clusterEmbeddings:a,embedColsNames:l,clusterColName:c})},e.moleculesToHelmTopMenu=async function(e,t){return await o.functions.call("Bio:MoleculesToHelmTopMenu",{table:e,molecules:t})},e.moleculeToHelmSingle=async function(e){return await o.functions.call("Bio:MoleculeToHelmSingle",{molecule:e})},e.toAtomicLevel=async function(e,t,n,i){return await o.functions.call("Bio:ToAtomicLevel",{table:e,seqCol:t,nonlinear:n,highlight:i})},e.toAtomicLevelAction=async function(e){return await o.functions.call("Bio:ToAtomicLevelAction",{seqCol:e})},e.toAtomicLevelPanel=async function(e){return await o.functions.call("Bio:ToAtomicLevelPanel",{sequence:e})},e.toAtomicLevelSingleSeq=async function(e){return await o.functions.call("Bio:ToAtomicLevelSingleSeq",{sequence:e})},e.sequence3dStructureWidget=async function(e){return await o.functions.call("Bio:Sequence3dStructureWidget",{sequence:e})},e.multipleSequenceAlignmentDialog=async function(){return await o.functions.call("Bio:MultipleSequenceAlignmentDialog",{})},e.alignSequences=async function(e,t,n){return await o.functions.call("Bio:AlignSequences",{sequenceCol:e,clustersCol:t,options:n})},e.pepseaMsa=async function(e,t,n,i){return await o.functions.call("Bio:PepseaMsa",{sequenceCol:e,method:t,gapOpen:n,gapExtend:i})},e.immunumAntibodyNumbering=async function(e,t,n){return await o.functions.call("Bio:ImmunumAntibodyNumbering",{df:e,seqCol:t,scheme:n})},e.compareSequences=async function(){return await o.functions.call("Bio:CompareSequences",{})},e.compositionAnalysis=async function(){return await o.functions.call("Bio:CompositionAnalysis",{})},e.importFasta=async function(e){return await o.functions.call("Bio:ImportFasta",{fileContent:e})},e.importBam=async function(e){return await o.functions.call("Bio:ImportBam",{fileContent:e})},e.convertDialog=async function(){return await o.functions.call("Bio:ConvertDialog",{})},e.convertColumnAction=async function(e){return await o.functions.call("Bio:ConvertColumnAction",{col:e})},e.monomerCellRenderer=async function(){return await o.functions.call("Bio:MonomerCellRenderer",{})},e.testDetectMacromolecule=async function(e){return await o.functions.call("Bio:TestDetectMacromolecule",{path:e})},e.splitToMonomersTopMenu=async function(e,t){return await o.functions.call("Bio:SplitToMonomersTopMenu",{table:e,sequence:t})},e.getHelmMonomers=async function(e){return await o.functions.call("Bio:GetHelmMonomers",{sequence:e})},e.similaritySearchViewer=async function(){return await o.functions.call("Bio:SimilaritySearchViewer",{})},e.similaritySearchTopMenu=async function(){return await o.functions.call("Bio:SimilaritySearchTopMenu",{})},e.diversitySearchViewer=async function(){return await o.functions.call("Bio:DiversitySearchViewer",{})},e.diversitySearchTopMenu=async function(){return await o.functions.call("Bio:DiversitySearchTopMenu",{})},e.searchSubsequenceEditor=async function(e){return await o.functions.call("Bio:SearchSubsequenceEditor",{call:e})},e.subsequenceSearchTopMenu=async function(e){return await o.functions.call("Bio:SubsequenceSearchTopMenu",{macromolecules:e})},e.sequenceIdentityScoring=async function(e,t,n){return await o.functions.call("Bio:SequenceIdentityScoring",{table:e,macromolecule:t,reference:n})},e.sequenceSimilarityScoring=async function(e,t,n){return await o.functions.call("Bio:SequenceSimilarityScoring",{table:e,macromolecule:t,reference:n})},e.manageMonomerLibraries=async function(){return await o.functions.call("Bio:ManageMonomerLibraries",{})},e.manageLibrariesView=async function(){return await o.functions.call("Bio:ManageLibrariesView",{})},e.manageMonomersView=async function(){return await o.functions.call("Bio:ManageMonomersView",{})},e.manageMonomerLibrariesView=async function(e){return await o.functions.call("Bio:ManageMonomerLibrariesView",{path:e})},e.manageMonomerLibrariesViewTreeBrowser=async function(e){return await o.functions.call("Bio:ManageMonomerLibrariesViewTreeBrowser",{treeNode:e})},e.monomerCollectionsApp=async function(){return await o.functions.call("Bio:MonomerCollectionsApp",{})},e.saveAsFasta=async function(){return await o.functions.call("Bio:SaveAsFasta",{})},e.bioSubstructureFilter=async function(){return await o.functions.call("Bio:BioSubstructureFilter",{})},e.bioSubstructureFilterTest=async function(){return await o.functions.call("Bio:BioSubstructureFilterTest",{})},e.webLogoLargeApp=async function(){return await o.functions.call("Bio:WebLogoLargeApp",{})},e.webLogoAggApp=async function(){return await o.functions.call("Bio:WebLogoAggApp",{})},e.getRegionApp=async function(){return await o.functions.call("Bio:GetRegionApp",{})},e.getRegionHelmApp=async function(){return await o.functions.call("Bio:GetRegionHelmApp",{})},e.longSeqTableSeparator=async function(){return await o.functions.call("Bio:LongSeqTableSeparator",{})},e.longSeqTableFasta=async function(){return await o.functions.call("Bio:LongSeqTableFasta",{})},e.longSeqTableHelm=async function(){return await o.functions.call("Bio:LongSeqTableHelm",{})},e.addCopyMenu=async function(e,t){return await o.functions.call("Bio:AddCopyMenu",{cell:e,menu:t})},e.demoBioSimilarityDiversity=async function(){return await o.functions.call("Bio:DemoBioSimilarityDiversity",{})},e.demoBioSequenceSpace=async function(){return await o.functions.call("Bio:DemoBioSequenceSpace",{})},e.demoBioActivityCliffs=async function(){return await o.functions.call("Bio:DemoBioActivityCliffs",{})},e.demoBioAtomicLevel=async function(){return await o.functions.call("Bio:DemoBioAtomicLevel",{})},e.demoBioSiRNA=async function(){return await o.functions.call("Bio:DemoBioSiRNA",{})},e.sdfToJsonLib=async function(e){return await o.functions.call("Bio:SdfToJsonLib",{table:e})},e.demoAntibodies=async function(){return await o.functions.call("Bio:DemoAntibodies",{})},e.seq2atomic=async function(e,t){return await o.functions.call("Bio:Seq2atomic",{seq:e,nonlinear:t})},e.seqIdentity=async function(e,t){return await o.functions.call("Bio:SeqIdentity",{seq:e,ref:t})},e.detectMacromoleculeProbe=async function(e,t,n){return await o.functions.call("Bio:DetectMacromoleculeProbe",{file:e,colName:t,probeCount:n})},e.getSeqHelper=async function(){return await o.functions.call("Bio:GetSeqHelper",{})},e.getMolFromHelm=async function(e,t,n){return await o.functions.call("Bio:GetMolFromHelm",{df:e,helmCol:t,chiralityEngine:n})}}(Oo||(Oo={}));var Go=function(e,t,n,i){var o,s=arguments.length,r=s<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(r=(s<3?o(r):s>3?o(t,n,r):o(t,n))||r);return s>3&&r&&Object.defineProperty(t,n,r),r},Bo=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},Vo=function(e,t){return function(n,i){t(n,i,e)}};const Uo=new Ei;let qo=null;o.decorators||(o.decorators={}),["func","init","param","panel","editor","demo","app","appTreeBrowser","fileHandler","fileExporter","model","viewer","filter","cellRenderer","autostart","dashboard","folderViewer","semTypeDetector","packageSettingsEditor","functionAnalysis","converter","fileViewer","model","treeBrowser","polyfill"].forEach(e=>{o.decorators[e]||(o.decorators[e]=function(e){return function(e,t,n){}})});class Wo{static async getMonomerLibHelper(){return await bn.getInstance()}static async initBio(){null==qo&&(qo=async function(){const e="Bio: _package.initBio()";Uo.logger.debug(`${e}, start`);const t=window.performance.now(),n=await(0,Ie.j)(),i=await Uo.getProperties(),s=new Ti(i);Uo.properties=s;const a=await bn.getInstance(),l=await(0,Le.u)();l.explicit&&(l.explicit=[],await(0,Le.E)(l)),await a.awaitLoaded(1/0),a.initialLoadCompleted||await a.loadMonomerLib(),a.loadMonomerSets();const u=a.getMonomerLib(),h=a.getMonomerSets(),d=window.performance.now();Uo.logger.debug(`${e}, loading ET: ${d-t} ms`);const m=new ao(a,n);Uo.completeInit(m,u,h,n),r.ObjectHandler.register(new jn),Uo.logger.debug(`${e}, end`),function(){const e=t=>{setTimeout(()=>{if(t.isDetached)return;const n=t.dataFrame;if(!n)return;t.temp[Mo]||(t.temp[Mo]=[]);let i=t.temp[Mo];i.forEach(e=>e.unsubscribe()),t.temp[Mo]=i=[];const s=e=>{i.push(e)},a=n.columns.bySemTypeAll(r.SEMTYPE.MACROMOLECULE);s(r.debounce(c.merge(n.onColumnsAdded,n.onColumnsRemoved,n.onSemanticTypeDetected,t.onEvent("d4-data-frame-changed")),200).subscribe(()=>e(t)));for(const e of a){const i=t.col(e.name);if(!i)continue;const a=!0===i.temp[So];i.temp[So]=!0;let l=null;try{l=Uo.seqHelper.getSeqHandler(e)}catch(t){console.warn(`Failed to get SeqHandler for column ${e.name}`);continue}if(!l)continue;if(l.isHelm()||l.alphabet===ue.YI.UN)continue;let u=!!t.tableView&&Array.from(t.tableView.viewers).some(e=>"Sequence Position Statistics"===e.type);const h=(e,t)=>Number.isNaN(e)||null==e?t:e,d=()=>h(Math.max(Number.parseInt(e.getTag(ue.gp.positionShift)??"0"),0),0)+1,m=()=>h(Number.parseInt(e.getTag(ue.gp.selectedPosition)??"-2"),-2),p=()=>$e.Jy.getFontSettings(e).fontWidth;let g=0,f=0;const y=e.categories;for(let e=0;e<y.length;e++){const t=y[e];t&&t.length>f&&(f=t.length,g=e)}const b=y[g],w=l.splitter(b),v=w?w.length:30,C=e.getTag(ue.gp.annotations)?24:0,A={WITH_TITLE:58,WITH_WEBLOGO:107+C,WITH_BOTH:156+C};let T;T=e.length>1e5||v<50?A.WITH_TITLE+C:e.length>5e4?A.WITH_WEBLOGO:A.WITH_BOTH;let E=null,S=null;const M=r.debounce(c.merge(n.onFilterChanged,n.onDataChanged.pipe((0,R.filter)(t=>t?.args?.column===e))),100).subscribe(()=>{Ao.clearAllCaches(),E&&(E.resetViewportTracking(),E.forceUpdate()),S&&(S.resetViewportTracking(),S.forceUpdate()),setTimeout(()=>{t.isDetached||t.invalidate()},50)});s(M);const x=o=>{const c=[],h=new Co(e,"Annotations");h.hasRegions()&&c.push({id:"annotations",track:h,priority:0});const g=new To(l,v,45,"WebLogo");E=g,o&&(g.setMonomerLib(o),g.setBiotype(l.defaultBiotype||"HELM_AA")),g.setupDefaultTooltip(),c.push({id:"weblogo",track:g,priority:1});const f=new Eo(l,v,45,"default","Conservation");S=f,c.push({id:"conservation",track:f,priority:2});const y=new wo({canvas:t.overlay,headerHeight:T,totalPositions:v+1,onPositionChange:(n,i)=>{setTimeout(()=>{const o=d(),s=m();if(o!==i.start&&e.setTag(ue.gp.positionShift,(i.start-1).toString()),s!==n&&(e.setTag(ue.gp.selectedPosition,n.toString()),n>=0&&!u&&t.tableView&&ee()(t.dataFrame?.columns.numerical).find(e=>!0))){u=!0;const n=t.tableView.addViewer("Sequence Position Statistics",{sequenceColumnName:e.name});t.tableView.dockManager.dock(n,r.DOCK_TYPE.DOWN,null,"Sequence Position Statistics",.4)}})},onHeaderHeightChange:e=>{t.isDetached||e<A.WITH_TITLE||setTimeout(()=>t.props.colHeaderHeight=e)}},i);y.setupTooltipHandling(),c.sort((e,t)=>e.priority-t.priority),c.forEach(({id:e,track:t})=>{y.addTrack(e,t)}),y.setSelectionData(n,e,l),v>50&&!a&&(t.props.colHeaderHeight=T,setTimeout(()=>{t.isDetached||(i.width=400)},300)),s({unsubscribe:()=>y.detach()});const b=i.column;s(t.onCellRender.subscribe(t=>{const n=t.cell;if(!n||!n.isColHeader||n?.tableColumn?.dart!==b?.dart)return;const i=t.bounds;if(!i)return;y.headerHeight=i.height;const o=p();y.positionWidth=o+8;const s=d();y.draw(i.x,i.y,i.width,i.height,m(),s,t,e.name)}))};(0,ye.pj)().then(e=>{const t=e.getMonomerLib();x(t)}).catch(e=>{o.shell.warning("Failed to initialize monomer library"),console.error("Failed to initialize monomer library:",e)})}},1e3)},t=(o.events.onViewerAdded.subscribe(t=>{if(!(t.args&&t.args.viewer instanceof r.Grid))return;const n=t.args.viewer;e(n)}),o.shell.tableViews);for(const n of t){const t=n?.grid;t&&e(t)}}()}()),await qo}static sequenceTooltip(e){const t=new Pi(e,Uo.seqHelper);return t.init().then(()=>{}).catch(e=>{const t=e instanceof Error?e.message:e.toString();o.shell.error(t)}),t}static async standardiseMonomerLibrary(e){return await async function(e){const t=JSON.parse(e);if(!t||!Array.isArray(t)||0===t.length)throw new Error("Invalid library format, expected an array of monomers");const n=(await xn(t)).map(e=>({...e,lib:void 0,wem:void 0}));return JSON.stringify(n,null,2)}(e)}static async matchWithMonomerLibrary(e,t,n="PEPTIDE"){const i=await async function(e,t,n,i="PEPTIDE"){const s=n.duplicateMonomers?.[i]??{},a=r.Func.find({package:"Chem",name:"convertMoleculeNotation"})[0];if(!a)throw new Error("Function convertMoleculeNotation not found, please install Chem package");const l=n.getMonomerSymbolsByType(i).map(e=>n.getMonomer(i,e)).filter(e=>e&&(e.smiles||e.molfile)),c=await xn(l);c.forEach((e,t)=>{e.lib=l[t].lib});const{cappedMap:u,uncappedMap:h}=await async function(e,t,n){const i={};for(const t of e){if(!t.smiles)continue;const e={symbol:t.symbol,smiles:t.smiles,original:t.smiles,source:t.lib?.source??""};i[t.smiles]||(i[t.smiles]=[]),i[t.smiles].push(e)}const o=e.map((e,n)=>({symbol:e.symbol,smiles:Fn(e.smiles??"",e.rgroups??[]),original:e.smiles,source:t[n]?.lib?.source??""})).filter(e=>!!e.smiles&&!e.smiles.includes("[*:")),s=r.Column.fromList(r.COLUMN_TYPE.STRING,"CappedSmiles",o.map(e=>e.smiles));s.semType=r.SEMTYPE.MOLECULE;const a=await n.apply({molecule:s,targetNotation:r.chem.Notation.Smiles});if(!a||a.length!==s.length)throw new Error("Error canonicalizing capped monomer SMILES");const l={},c=a.toList();for(let e=0;e<c.length;e++){const t=c[e];if(!t)continue;o[e].smiles=t;const n=o[e];l[t]||(l[t]=[]),l[t].push(n)}return{cappedMap:l,uncappedMap:i}}(c,l,a),d=await async function(e,t,n){const i=e.col(t).toList().map(e=>{if(!e)return e;try{const t=e.includes("\n");return Hn([],t?void 0:e,t?e:void 0)}catch(t){return e}}),o=r.Column.fromList(r.COLUMN_TYPE.STRING,"MoleculesCorrected",i);o.semType=r.SEMTYPE.MOLECULE,r.DataFrame.fromColumns([o]);const s=await n.apply({molecule:o,targetNotation:r.chem.Notation.Smiles});if(!s||s.length!==o.length)throw new Error("Error canonicalizing molecules");return s.toList()}(e,t,a),m=new Array(d.length).fill(null).map(()=>[]),p=[];for(let e=0;e<d.length;e++){const t=d[e];if(!t)continue;const n=An(t,u,h);n.length>0?m[e]=n:p.push(e)}if(p.length>0)try{const{fpMap:e}=await async function(e){const t=Object.keys(e);if(0===t.length)return{fpMap:{},cappedSmilesList:[]};const n=r.Column.fromList(r.COLUMN_TYPE.STRING,"MonomerSmiles",t);n.semType=r.SEMTYPE.MOLECULE;const i=await o.functions.call("Chem:getMorganFingerprints",{molColumn:n}),s={};for(let n=0;n<i.length;n++){const o=i.get(n);if(!o)continue;const r=o.toBinaryString(),a=e[t[n]]??[];s[r]||(s[r]=[]),s[r].push(...a)}return{fpMap:s,cappedSmilesList:t}}(u),t=await async function(e,t,n){const i=new Map;if(0===e.length||0===Object.keys(n).length)return i;const s=e.map(e=>t[e]??""),a=s.map(e=>{if(!e)return"";const t=Fn(e,Cn);return t!==e?o.chem.convert(t,r.chem.Notation.Unknown,r.chem.Notation.Smiles):e}),l=r.Column.fromList(r.COLUMN_TYPE.STRING,"UnmatchedMols",s);l.semType=r.SEMTYPE.MOLECULE;const c=r.Column.fromList(r.COLUMN_TYPE.STRING,"UnmatchedMolsCapped",a);c.semType=r.SEMTYPE.MOLECULE;const[u,h]=await Promise.all([o.functions.call("Chem:getMorganFingerprints",{molColumn:l}),o.functions.call("Chem:getMorganFingerprints",{molColumn:c})]);for(let t=0;t<e.length;t++){const o=e[t],s=u.get(t);if(s){const e=n[s.toBinaryString()];if(e&&e.length>0){i.set(o,e);continue}}const r=h.get(t);if(r){const e=n[r.toBinaryString()];e&&e.length>0&&i.set(o,e)}}return i}(p,d,e);for(const[e,n]of t)m[e]=n}catch(e){console.warn("Fingerprint fallback matching failed, continuing with SMILES matches only:",e)}const g=e.clone(),f=g.columns.addNewString(g.columns.getUnusedName("Matched monomer symbol")),y=g.columns.addNewString(g.columns.getUnusedName("Matched monomer smiles"));y.semType=r.SEMTYPE.MOLECULE;const b=g.columns.addNewString(g.columns.getUnusedName("Matched monomer source")),w=g.columns.addNewInt(g.columns.getUnusedName("Match count")),v=g.columns.addNewString(g.columns.getUnusedName("Match method"));g.columns.setOrder([t,f.name,y.name,b.name,w.name,v.name]);for(let e=0;e<m.length;e++){const t=m[e];if(0===t.length)continue;const n=Tn(t),i=En(n,s);f.set(e,n.map(e=>e.symbol).join(" | "),!1),y.set(e,n[0].original??n[0].smiles,!1),b.set(e,i,!1),w.set(e,n.length,!1);const o=p.includes(e)?"fingerprint":"exact";v.set(e,o,!1)}return g}(e,t.name,Uo.monomerLib,n);o.shell.addTableView(i)}static getBioLib(){return Uo.monomerLib}static getSeqHandler(e){return Uo.seqHelper.getSeqHandler(e)}static getRegionPanel(e){const t="getRegionTopMenu",n=r.Func.find({package:Uo.name,name:t});if(1!==n.length)throw new Error(`Package '${Uo.name}' func '${t}' not found`);const i=n[0].prepare({table:e.dataFrame,sequence:e});return new Ri(i,Uo.seqHelper).widget()}static async libraryPanel(e){return async function(){const e=s.label("Manage monomer libraries");return zn()(e).addClass("d4-link-action"),e.onclick=async()=>await ti(),new r.Widget(e)}()}static GetRegionEditor(e){try{new Ri(e,Uo.seqHelper).dialog()}catch(e){const t=e instanceof Error?e.message:e.toString(),n=e instanceof Error?e.stack:void 0;o.shell.error(`Get region editor error: ${t}`),Uo.logger.error(t,void 0,n)}}static SplitToMonomersEditor(e){const t=new yi;s.dialog({title:"Split to Monomers"}).add(t.paramsUI).onOK(async()=>e.func.prepare(t.funcParams).call(!0)).show()}static SequenceSpaceEditor(e){const t=new N({semtype:r.SEMTYPE.MACROMOLECULE}),n=s.dialog({title:"Sequence Space"}).add(t.getEditor()).onOK(async()=>{const n=t.getParams();return e.func.prepare({molecules:n.col,table:n.table,methodName:n.methodName,similarityMetric:n.similarityMetric,plotEmbeddings:n.plotEmbeddings,options:n.options,preprocessingFunction:n.preprocessingFunction,clusterEmbeddings:n.clusterEmbeddings}).call()});n.history(()=>({editorSettings:t.getStringInput()}),e=>t.applyStringInput(e.editorSettings)),n.show()}static SeqActivityCliffsEditor(e){const t=new Ce({semtype:r.SEMTYPE.MACROMOLECULE}),n=s.dialog({title:"Activity Cliffs"}).add(t.getEditor()).onOK(async()=>{const n=t.getParams();return e.func.prepare({table:n.table,molecules:n.col,activities:n.activities,similarity:n.similarityThreshold,methodName:n.methodName,similarityMetric:n.similarityMetric,preprocessingFunction:n.preprocessingFunction,options:n.options}).call()});n.history(()=>({editorSettings:t.getStringInput()}),e=>t.applyStringInput(e.editorSettings)),n.show()}static customSequenceCellRenderer(){return new We}static fastaSequenceCellRenderer(){return new We}static separatorSequenceCellRenderer(){return new We}static bilnSequenceCellRenderer(){return new We}static refineNotationProviderForBiln(e,t,n){if("-"!==n)return!1;if(!Object.keys(t.freq).some(e=>e.match(/^.+\(\d{1,2},\d{1,2}\)$/))){const e=Object.keys(t.freq).filter(e=>e.startsWith("[")),n=Object.keys(t.freq).filter(e=>e.endsWith("]"));if(Object.keys(t.freq).filter(e=>(e.includes("[")||e.includes("]"))&&!e.startsWith("[")&&!e.endsWith("]")).length>0||0==e.length||0==n.length)return!1;if(Object.keys(t.freq).some(e=>e.startsWith("*")||e.startsWith("$")||e.startsWith("@")||e.startsWith("%")))return!1}return e.setTag("aligned","SEQ"),e.setTag("alphabet","UN"),e.setTag(".alphabetIsMultichar","true"),e.meta.units=ue.Hi.BILN,e.temp[me.j.notationProvider]=new xo(n,Uo.seqHelper,e),!0}static macroMolColumnPropertyPanel(e){return function(e){const t=Array.from(e.dataFrame.columns).filter(e=>e.semType===r.SEMTYPE.MOLECULE).map(e=>e.name);new Set(t).delete(e.name);let i=Uo.properties?Uo.properties.maxMonomerLength:4;if(Re.gp.maxMonomerLength in e.tags){const t=parseInt(e.getTag(Re.gp.maxMonomerLength));i=isNaN(t)?i:t}if(".mm.cellRenderer.maxMonomerLength"in e.temp){const t=parseInt(e.temp[".mm.cellRenderer.maxMonomerLength"]);i=isNaN(t)?i:t}const o=s.input.int("Max Monomer Length",{value:i,nullable:!0,min:1,max:50,step:1,onValueChanged:t=>{if(0==t)setTimeout(()=>{o.value=null},0);else{const n=t??"",i=null==n?"":n.toString();e.temp[".mm.cellRenderer.maxMonomerLength"]=i,e.temp[".mm.cellRenderer.settingsChanged"]=ke.s.true,e.dataFrame.fireValuesChanged()}},tooltipText:"The max length of monomer symbol displayed without shortening, empty to no limit"});let a=Uo.properties?Uo.properties.fontSize:12;".mm.cellRenderer.fontSize"in e.temp&&e.temp[".mm.cellRenderer.fontSize"]&&!isNaN(e.temp[".mm.cellRenderer.fontSize"])&&(a=e.temp[".mm.cellRenderer.fontSize"]);const l=s.input.int("Font Size",{value:a,nullable:!0,min:1,max:50,step:1,onValueChanged:t=>{if(t&&t>0){const n=t??12;e.temp[".mm.cellRenderer.fontSize"]=n,e.temp[".mm.cellRenderer.settingsChanged"]=ke.s.true,e.dataFrame.fireValuesChanged()}},tooltipText:"The font size of monomer symbol in sequence renderer"}),c=s.input.int("Monomer Margin",{value:e.temp[".mm.cellRenderer.gapLength"]??0,onValueChanged:t=>{e.temp[".mm.cellRenderer.gapLength"]=t,e.temp[".mm.cellRenderer.settingsChanged"]=ke.s.true,e.dataFrame.fireValuesChanged()},tooltipText:"The size of margin between monomers (in pixels)"}),u=s.input.bool("Color Code",{value:null==e?.temp["color-code"]||e.temp["color-code"],onValueChanged:t=>{e.temp["color-code"]=t,e.dataFrame.fireValuesChanged()},tooltipText:"Color code"}),h=s.input.string("Reference Sequence",{value:null!=e?.temp["reference-sequence"]?e?.temp["reference-sequence"]:"",nullable:!0,onValueChanged:t=>{e.temp["reference-sequence"]=t,e.dataFrame.fireValuesChanged()},tooltipText:"Reference sequence is not empty, then the sequence will be render \nas a difference from the reference sequence"}),d=s.input.bool("Compare with current",{value:null==e?.temp["compare-with-current"]||e.temp["compare-with-current"],onValueChanged:t=>{e.temp["compare-with-current"]=t,e.dataFrame.fireValuesChanged()},tooltipText:'When on, all sequences get rendered in the "diff" mode'});let m=null;e.meta.units!==ue.Hi.HELM&&(m=s.input.bool("Multiline Rendering",{value:"true"===e.getTag("renderMultiline"),onValueChanged:t=>{e.tags.renderMultiline=t?"true":"false",e.dataFrame.fireValuesChanged()},tooltipText:"Render sequences across multiple lines when they exceed cell width"}));const p=[l,o,c,h,u,d];m&&p.push(m);const g=s.inputs(p),f=(0,Et.Ln)(e),y=s.divV([]);if(f.length>0){const t=e.getTag(ue.gp.numberingScheme),i=f.filter(e=>e.category===St.eI.Structure),o=f.filter(e=>e.category===St.eI.Liability);if(t&&y.append(s.divText(`Numbering: ${t}`,{style:{fontSize:"12px",marginBottom:"4px"}})),i.length>0){const e=i.map(e=>e.name).join(", ");y.append(s.divText(`Regions: ${e}`,{style:{fontSize:"12px",marginBottom:"4px"}}))}if(o.length>0){const e=o.reduce((e,t)=>{const n=t.description?.match(/\((\d+) hits\)/);return e+(n?parseInt(n[1]):0)},0);y.append(s.divText(`Liabilities: ${o.length} rules (${e} hits)`,{style:{fontSize:"12px",marginBottom:"4px"}}))}const r=s.button("Manage",()=>{Promise.resolve().then(n.bind(n,9287)).then(e=>e.showAnnotationManagerDialog())}),a=s.button("Clear All",()=>{(0,Et.OW)(e.dataFrame,e),e.dataFrame.fireValuesChanged()});y.append(s.divH([r,a],{style:{gap:"4px",marginTop:"4px"}}))}else{y.append(s.divText("No annotations",{style:{fontSize:"12px",color:"#888"}}));const e=s.button("Scan Liabilities",()=>{Promise.resolve().then(n.bind(n,9422)).then(e=>e.showLiabilityScannerDialog())}),t=s.button("Apply Numbering",()=>{Promise.resolve().then(n.bind(n,6839)).then(e=>e.showNumberingSchemeDialog())});y.append(s.divH([e,t],{style:{gap:"4px",marginTop:"4px"}}))}const b=s.accordion();return b.addPane("Renderer Settings",()=>g),b.addPane("Annotations",()=>y),new r.Widget(b.root)}(e)}static compositionAnalysisWidget(e){return function(e,t,n){const i=s.div();i.classList.add("macromolecule-cell-comp-analysis-host");const o=e.cell.column.tags[ue.gp.alphabet],a=o===ue.YI.DNA||o===ue.YI.RNA?Fe.o.NUCLEOTIDE:Fe.o.AA,l={},c=n.getSeqHandler(e.cell.column),u=e.cell.rowIndex,h=c.getSplitted(u),d={};ee().count(0).take(h.length).filter(e=>!h.isGap(e)).forEach(e=>{let t=h.getCanonical(e);a===Fe.o.NUCLEOTIDE&&c.isHelm()&&"("===t[1]&&")"===t[t.length-2]&&(t=t.substring(2,t.length-2));const n=l[t]||0;if(l[t]=n+1,!d[t]&&h.graphInfo?.polymerTypes){const n=h.graphInfo.polymerTypes[e];d[t]=(0,Oe.MD)(n)}});const m=(0,Si.F)(l,a,t,Object.keys(d).length?d:void 0);return Array.from(m.rows).forEach(e=>{const t=e.getElementsByClassName("macromolecule-cell-comp-analysis-bar")[0].style.backgroundColor;e.cells[0].style.color=t}),i.appendChild(m),new r.Widget(i)}(e,Uo.monomerLib,Uo.seqHelper)}static monomerInfoPanel(e){return function(e,t){const n=e.value;if(!n)return new r.Widget(s.divText("No monomer value."));const i=function(e){try{const t=e.cell?.column;if(t)return t.temp[pe.sc]??null}catch{}return null}(e),o=(i?i.canonicalize(n):n).split(pe.ot).map(e=>e.trim()).filter(e=>e.length>0).map(e=>({symbol:e,monomer:t.getMonomer(null,e)})).filter(e=>null!==e.monomer);if(0===o.length)return new r.Widget(s.divText(`Monomer '${n}' not found in the library.`));const a=s.accordion("Monomer");if(1===o.length){const e=o[0].monomer;a.addPane("Details",()=>Bn(e),!0),a.addPane("Molecule",()=>Vn(e),!0)}else for(const{symbol:e,monomer:t}of o)a.addPane(e,()=>s.divV([Bn(t),s.element("hr"),Vn(t)]),!0);return new r.Widget(a.root)}(e,Uo.monomerLib)}static macromoleculeDifferenceCellRenderer(){return new je}static sequenceAlignment(e,t,n,i,o){const s=new ct(i,o,n,t);return"Local alignment"==e?s.smithWaterman():s.needlemanWunsch()}static webLogoViewer(){return new tt.oP}static vdRegionsViewer(){return new rt}static getRegion(e,t,n,i){return Ii(e,t??null,n??null,i??null)}static async getRegionTopMenu(e,t,n,i,s){const r=Ii(t,n??null,i??null,s??null);t.dataFrame.columns.add(r),await o.data.detectSemanticTypes(t.dataFrame)}static applyNumberingScheme(){(0,Ho.showNumberingSchemeDialog)()}static scanLiabilities(){(0,Do.showLiabilityScannerDialog)()}static manageAnnotations(){(0,Fo.showAnnotationManagerDialog)()}static sequenceColumnInput(e,t){return Ro.create(e,t)}static async activityCliffs(e,t,n,i,c,u,h,d,m){if(_e(e),!(0,di.V)(t,"Activity Cliffs"))return;const p=c===l.c.UMAP?2e5:2e4,g=c===l.c.UMAP?5e3:2e3;if(e.rowCount>p)return void o.shell.warning(`Too many rows, maximum for sequence activity cliffs is ${p}`);const f=Se(e),y=async()=>{await r.Func.find({name:"seqActivityCliffsTransform"})[0].prepare({table:e,molecules:t,activities:n,similarity:i,methodName:c,similarityMetric:u,options:JSON.stringify(d),isDemo:m,axesNames:f}).call(void 0,void 0,{processed:!1}),_e(e);const s=o.shell.tv,a=`Molecules: ${t.name}, activities: ${n.name}, method: ${c}, ${d?`options: ${JSON.stringify(d)},`:""} similarity: ${u}, similarity cutoff: ${i}`;s.addViewer(r.VIEWER.SCATTER_PLOT,{xColumnName:f[0],yColumnName:f[1],color:n.name,showXSelector:!1,showYSelector:!1,showSizeSelector:!1,showColorSelector:!1,markerMinSize:5,markerMaxSize:25,title:"Activity cliffs",initializationFunction:"seqActivityCliffsInitFunction",description:a,descriptionVisibilityMode:"Never"})},b=r.TaskBarProgressIndicator.create("Running sequence activity cliffs ...");try{e.rowCount>g&&!d?.[a.vb]?await new Promise((e,t)=>{s.dialog().add(s.divText("Activity cliffs analysis might take several minutes.\n Do you want to continue?")).onOK(async()=>{y().then(()=>e()).catch(e=>t(e))}).onCancel(()=>{e()}).show()}):await y()}catch(e){const[t,n]=(0,we.AP)(e);throw Uo.logger.error(t,void 0,n),e}finally{b.close()}}static async seqActivityCliffsInitFunction(e){const t=e.dataFrame.getTag("seqActivityCliffsParams");if(!t)return void o.shell.error("Sequence activity cliffs parameters not found in table tags");const n=JSON.parse(t),i=e.dataFrame.col(n.seqColName),s=e.dataFrame.col(n.activityColName),a=r.Func.find({name:"macromoleculePreprocessingFunction",package:"Bio"})[0],l=await a.apply({col:i,metric:n.similarityMetric}),c=[e.getOptions().look.xColumnName,e.getOptions().look.yColumnName],u={units:i.meta.units,aligned:i.getTag(ue.gp.aligned),separator:i.getTag(ue.gp.separator),alphabet:i.getTag(ue.gp.alphabet)};await le(e,e.dataFrame,i,l,s,c,n.similarity,n.similarityMetric,n.options??{},r.SEMTYPE.MACROMOLECULE,u,dt,mt,yt,void 0,n.isDemo)}static async seqActivityCliffsTransform(e,t,i,o,s,a,l,c,u){await e.meta.detectSemanticTypes();const h=r.Func.find({name:"macromoleculePreprocessingFunction",package:"Bio"})[0];u||(u=Se(e)),await async function(e,t,i,o,s,r,a,l){const c=l.inputs,u=await l.apply({[c[0].name]:t,[c[1].name]:s,...a.preprocessingFuncArgs??{}});let h=[];if(r===I){const t=await function(e,t,i,o,s,r,a=10,l=!1,c=2){const u=new Worker(new URL(n.p+n.u(980),n.b));let h;return u.postMessage({data:e,threshold:t,weights:i,aggregationMethod:o,distanceFns:s,distanceFnArgs:r,maxIterations:a,useWebGPU:l,inflate:c}),{promise:new Promise((e,t)=>{h=e,u.onmessage=t=>{setTimeout(()=>u.terminate(),100),e(t.data.res)},u.onerror=e=>{setTimeout(()=>u.terminate(),100),t(e)}}),terminate:()=>{try{h(null),u.terminate()}catch(e){console.error(e)}}}}([u.entries],o,[1],"MANHATTAN",[s],[u.options??{}],a?.maxIterations??5,a.useWebGPU??!1).promise;e.columns.addNewInt(e.columns.getUnusedName("MCL Cluster")).init(e=>t.clusters[e]),h=[t.embedX,t.embedY]}else h=await W([u.entries],r,[s],[1],"MANHATTAN",{...a,distanceFnArgs:[u.options??{}]});if(h.length!==i.length)throw new Error("Number of axes names should be equal to number of embedding dimensions");for(let t=0;t<h.length;++t)e.columns.addNewFloat(i[t]).init(e=>h[t][e])}(e,t,u,o,a,s,JSON.parse(l??"{}"),h);const d={seqColName:t.name,activityColName:i.name,similarityMetric:a,similarity:o,options:l??{},isDemo:c};e.setTag("seqActivityCliffsParams",JSON.stringify(d))}static async macromoleculePreprocessingFunction(e,t,n=1,i=.6,o="Morgan"){if(e.semType!==r.SEMTYPE.MACROMOLECULE)return{entries:e.toList(),options:{}};const{seqList:s,options:a}=await ut(e,t,o,n,i);return{entries:s,options:a}}static async helmPreprocessingFunction(e,t){e.version!==e.temp["last-invalidated-version"]&&await(0,ht.BQ)(e,Uo.seqHelper,!1);const n=e.temp["monomeric-mols"],i=await o.functions.call("Chem:getMorganFingerprints",{molColumn:n}),s=new Array(i.length).fill(null);for(let e=0;e<i.length;e++){if(i.isNone(e)||!i.get(e))continue;const t=i.get(e);s[e]=G.A.fromUint32Array(t.length,new Uint32Array(t.getBuffer().buffer))}return{entries:s,options:{}}}static async sequenceSpaceTopMenu(e,t,n,i,s,a,l,c,u){if(_e(e),!(0,di.V)(t,"Sequence Space"))return;const h=e.columns.getUnusedName("Cluster (DBSCAN)"),d=Se(e);let m;if(await r.Func.find({name:"sequenceSpaceTransform"})[0].prepare({table:e,molecules:t,methodName:n,similarityMetric:i,plotEmbeddings:!1,options:JSON.stringify(l),clusterEmbeddings:c,embedColsNames:d,clusterColName:h}).call(void 0,void 0,{processed:!1}),s){_e(e),m=o.shell.tv.scatterPlot({x:d[0],y:d[1],title:"Sequence space"});const s=`Molecules column: ${t.name}, method: ${n}, ${l?`options: ${JSON.stringify(l)},`:""} similarity: ${i}`;m.setOptions({description:s,descriptionVisibilityMode:"Never"}),c&&(m.props.colorColumnName=h)}return m}static async sequenceSpaceTransform(e,t,n,i,s,l,c,u,h){await e.meta.detectSemanticTypes();const d=r.Func.find({name:"macromoleculePreprocessingFunction",package:"Bio"})[0],m=JSON.parse(l??"{}"),p=o.shell.tv?.dataFrame==e?o.shell.tv:void 0;return await xe(e,[t],n,[i],[1],[d],"MANHATTAN",s,c??!1,{...m,preprocessingFuncArgs:[m.preprocessingFuncArgs??{}]},{fastRowCount:1e4,scatterPlotName:"Sequence space",bypassLargeDataWarning:m?.[a.vb],tableView:p,embedColsNames:u,clusterColName:h})}static async moleculesToHelmTopMenu(e,t){const n=Uo.monomerLib,i=JSON.stringify(n.toJSON()),o=r.FileInfo.fromString("monomerLib.json",i);await $o.molToHelmConverterPy(e,t,o);const s=e.columns.toList().find(e=>e.name.toLowerCase().includes("regenerated sequence")&&e.semType!==r.SEMTYPE.MACROMOLECULE);s&&(s.meta.units=ue.Hi.HELM,s.semType=r.SEMTYPE.MACROMOLECULE,s.setTag("cell.renderer","helm"))}static async moleculeToHelmSingle(e){const t=r.Column.fromStrings("molecule",[e]);t.semType=r.SEMTYPE.MOLECULE;const n=r.DataFrame.fromColumns([t]);await Wo.moleculesToHelmTopMenu(n,t);const i=n.columns.toList().find(e=>e.name.toLowerCase().includes("regenerated sequence"))?.get(0);return i??""}static async toAtomicLevel(e,t,n=!0,i=!1){const o=r.TaskBarProgressIndicator.create("Converting to atomic level ...");try{await qo;const o=t.temp[".mm.cellRenderer.overriddenLibrary"]??Uo.monomerLib,s=Uo.seqHelper,r=Uo.rdKitModule;await(0,$i.V)(e,t,n,i,o,s,r)}finally{o.close()}}static async toAtomicLevelAction(e){if(!e?.dataFrame)throw new Error("Sequence column is not found or its data frame is not empty");const t=r.Func.find({name:"toAtomicLevel",package:"Bio"})[0];if(!t)throw new Error("To Atomic level Function not found");t.prepare({table:e.dataFrame,seqCol:e}).edit()}static async toAtomicLevelPanel(e){return async function(e){const t=await lo(e);if(t.errorText||!t.mol)return r.Widget.fromRoot(s.divText(t.errorText??"No structure generated"));try{const e=r.SemanticValue.fromValueType(t.mol,r.SEMTYPE.MOLECULE),n=s.panels.infoPanel(e);let i=null;if(n){const e=s.accordion("Sequence Molfile details");e.addPane("Explore",()=>n.root),i=r.Widget.fromRoot(e.root)}const a=o.chem.drawMolecule(t.mol,300,300,!1);return a.style.cursor="pointer",s.tooltip.bind(a,"Click to expand"),a.onclick=()=>{const e=window.innerWidth-200,n=window.innerHeight-200,i=o.chem.drawMolecule(t.mol,e,n,!1);s.dialog({title:"Molecule"}).add(i).showModal(!0)},i&&i.root.prepend(a),i??r.Widget.fromRoot(a)}catch(e){Uo.logger.error(e)}return r.Widget.fromRoot(s.divText("No structure generated"))}(e)}static async toAtomicLevelSingleSeq(e){const t=e.includes("$$"),n=e.split("").filter(e=>"/"==e).length>2,i=e.split("").filter(e=>"-"==e).length>2,o=r.Column.fromStrings("sequence",[e]);o.semType=r.SEMTYPE.MACROMOLECULE,o.meta.units=t?ue.Hi.HELM:n?ue.Hi.SEPARATOR:i?ue.Hi.BILN:ue.Hi.FASTA,o.setTag(ue.gp.aligned,"SEQ"),n&&o.setTag(ue.gp.separator,"/"),i&&o.setTag(ue.gp.separator,"-");const s=e.split("").every(e=>"AGCT".includes(e)||"/"===e||"-"===e),a=!s&&e.split("").every(e=>"AGCU".includes(e)||"/"===e||"-"===e);o.setTag(ue.gp.alphabet,s?ue.YI.DNA:a?ue.YI.RNA:"UN"),o.setTag(ue.gp.alphabetIsMultichar,"true");const l=r.DataFrame.fromColumns([o]).cell(0,"sequence"),c=r.SemanticValue.fromTableCell(l),u=await lo(c);if(u.errorText||!u.mol)throw new Error(u.errorText);return u.mol}static async sequence3dStructureWidget(e){return async function(e){const t=r.TaskBarProgressIndicator.create("Creating 3D view");let n,i="";try{await(r.Func.find({name:"getPdbHelper"})[0]?.apply({}));try{const a=await lo(e);if(a.errorText||!a.mol)return n=s.divText(a.errorText??"No structure generated"),t.close(),new r.Widget(n);const l=a.mol;i=await o.functions.call("Bio:Embed",{molecule:l});const c=Fi.Molecule.fromMolfile(i);c?i=c.toMolfile():console.warn("Failed to convert molv3 to molv2")}catch(e){console.warn(e)}try{i=i.replaceAll("\\n","\n");const e=new Blob([i],{type:"text/plain"}),t=s.div([],{classes:"d4-ngl-viewer",id:"ngl-3d-host"});t.style.setProperty("height","100%","important");const o=new NGL.Stage(t,{backgroundColor:"white"});o.loadFile(e,{ext:"sdf"}).then(function(e){o.setSize(300,300),e.addRepresentation("ball+stick"),e.autoView()}),n=s.div([t],{style:{aspectRatio:"1"}})}catch(e){n=s.divText("Couldn't get 3D structure")}}catch(e){n=s.divText("Couldn't get 3D structure")}return t.close(),new r.Widget(n)}(e)}static multipleSequenceAlignmentDialog(){(0,pi.D)({},Uo.seqHelper).catch(e=>{const[t,n]=(0,we.AP)(e);if(e instanceof mi.Ap)return o.shell.warning(e.element),void Uo.logger.warning(t);o.shell.error(t),Uo.logger.error(t,void 0,n)})}static async alignSequences(e=null,t=null,n){return(0,pi.D)({col:e,clustersCol:t,...n},Uo.seqHelper)}static async pepseaMsa(e,t="mafft --auto",n=1.53,i=0){return(0,gi.Gf)(e,t,n,i)}static async immunumAntibodyNumbering(e,t,n){return(0,ko.C)(t,n)}static compareSequences(){!function(){const e=o.shell.tv;if(!e||!e.dataFrame)return void o.shell.error("No active table");const t=e.dataFrame,n=(0,Ne.me)();if(n.length<2)return void o.shell.error("Current table needs at least two Macromolecule columns");const i=n.map(e=>e.name),a=s.input.choice("Sequence column 1",{value:i[0],items:i}),l=s.input.choice("Sequence column 2",{value:i[1],items:i}),c=s.input.string("Result column name",{value:""});c.setTooltip("Leave empty to auto-generate from the chosen columns"),s.dialog({title:"Compare Sequences"}).add(a).add(l).add(c).onOK(()=>{const e=t.col(a.value??""),n=t.col(l.value??"");if(!e||!n)return void o.shell.error("Could not resolve chosen columns");const i=function(e,t){return e===t?"Please choose two distinct columns":e.semType!==r.SEMTYPE.MACROMOLECULE||t.semType!==r.SEMTYPE.MACROMOLECULE?"Both columns must be Macromolecule semantic type":e.getTag(r.TAGS.UNITS)!==t.getTag(r.TAGS.UNITS)?"Columns must use the same notation (units)":(e.getTag(ue.gp.separator)??"")!==(t.getTag(ue.gp.separator)??"")?"Columns must use the same separator":(e.getTag(ue.gp.alphabet)??"")!==(t.getTag(ue.gp.alphabet)??"")?"Columns must use the same alphabet":null}(e,n);if(null!=i)return void o.shell.error(i);const s=(c.value??"").trim()||`${e.name} vs ${n.name}`,u=function(e,t,n){const i=Math.min(e.length,t.length),o=new Array(i);for(let n=0;n<i;n++){const i=e.get(n)??"",s=t.get(n)??"";o[n]=`${i}#${s}`}const s=n??`${e.name} vs ${t.name}`,a=r.Column.fromStrings(s,o);a.semType=Ve.uF.MACROMOLECULE_DIFFERENCE;const l=e.getTag(ue.gp.separator);null!=l&&(a.tags[ue.gp.separator]=l);const c=e.getTag(r.TAGS.UNITS);null!=c&&(a.tags[r.TAGS.UNITS]=c);const u=e.getTag(ue.gp.aligned);null!=u&&(a.tags[ue.gp.aligned]=u);const h=e.getTag(ue.gp.alphabet);return null!=h&&(a.tags[ue.gp.alphabet]=h),a.tags[r.TAGS.CELL_RENDERER]=Ve.uF.MACROMOLECULE_DIFFERENCE,a.temp[me.j.notationProvider]=e.temp[me.j.notationProvider],a}(e,n,t.columns.getUnusedName(s));t.columns.add(u)}).show()}()}static async compositionAnalysis(){const e=o.shell.tv,t=e.dataFrame.columns.toList().filter(e=>e.semType==r.SEMTYPE.MACROMOLECULE&&(Uo.seqHelper.getSeqHandler(e),!0)),n=async t=>{if(!(0,di.V)(t,"Composition"))return;const n=e.addViewer("WebLogo",{sequenceColumnName:t.name});o.shell.tv.dockManager.dock(n,r.DOCK_TYPE.DOWN,null,"Composition analysis",.25)};let i=null;if(0!=t.length){if(t.length>1){const e=t.map(e=>e.name),i=t.find(e=>Uo.seqHelper.getSeqHandler(e).isMsa()),o=s.input.choice("Column",{value:i?i.name:e[0],items:e});s.dialog({title:"Composition Analysis",helpUrl:"https://datagrok.ai/help/datagrok/solutions/domains/bio/#sequence-composition"}).add(s.div([o])).onOK(async()=>{const e=t.find(e=>e.name==o.value)??null;e&&await n(e)}).show()}else i=t[0];i&&await n(i)}else o.shell.error("Current table does not contain sequences")}static importFasta(e){return new he.m(e).importFasta()}static importBam(e){return console.log(e),[]}static convertDialog(){const e=(0,Ne.me)()[0];(0,Tt.C)(e,Uo.seqHelper)}static convertColumnAction(e){(0,Tt.C)(e,Uo.seqHelper)}static monomerCellRenderer(){return new Ci}static async testDetectMacromolecule(e){const t=r.TaskBarProgressIndicator.create("Test detectMacromolecule..."),n=(await o.dapi.files.list(e,!0,"")).filter(e=>e.fileName.endsWith(".csv"));let i=0;const s=[];for(const a of n)try{const t=await o.dapi.files.readAsText(e+a.fullPath),n=r.DataFrame.fromCsv(t);for(const e of n.columns)await o.functions.call("Bio:detectMacromolecule",{col:e})===r.SEMTYPE.MACROMOLECULE&&s.push({file:a.path,result:"detected",column:e.name,message:`units: ${e.meta.units}`})}catch(e){s.push({file:a.path,result:"error",column:null,message:e instanceof Error?e.message:e.toString()})}finally{i+=1,t.update(100*i/n.length,`Test ${a.fileName}`)}o.shell.info("Test Demo:Files for detectMacromolecule finished."),t.close();const a=r.DataFrame.fromObjects(s);return a.name=`datasets_detectMacromolecule_${e}`,a}static async splitToMonomersTopMenu(e,t){return await async function(e,t){if(await r.delay(10),!(0,di.V)(t,"Sequence space"))return e;const n=ge(t,Uo.seqHelper);n.name="splitToMonomers";const i=t.dataFrame;for(const e of n.columns)e.semType=Ve.uF.MONOMER,e.setTag(pe.gp.alphabet,t.getTag(pe.gp.alphabet));const s=/(\d+)(?: \((\d+)\))?/,a=e=>{s.lastIndex=0;const t=e.match(s);return t?`${t[1]} (${parseInt(t[2]??"0")+1})`:e};for(let e=0;e<n.columns.length;e++){const o=n.columns.byIndex(e);o.semType=Ve.uF.MONOMER,o.setTag(pe.gp.alphabet,t.getTag(pe.gp.alphabet));const s=100;let r=0;for(;i.columns.byName(o.name)&&r<s;)o.name=a(o.name),r++;i.columns.add(o)}await o.data.detectSemanticTypes(i);for(let e=0;e<n.columns.length;e++){const t=n.columns.byIndex(e);t.setTag(r.TAGS.CELL_RENDERER,"Monomer"),t.setTag(".use-as-filter","false")}return i}(e,t)}static getHelmMonomers(e){return Uo.seqHelper.getSeqMonomers(e)}static similaritySearchViewer(){return new Ct(Uo.seqHelper)}static similaritySearchTopMenu(){const e=o.shell.v,t=e.addViewer("Sequence Similarity Search");e.dockManager.dock(t,"down")}static diversitySearchViewer(){return new At(Uo.seqHelper)}static diversitySearchTopMenu(){const e=o.shell.v,t=e.addViewer("Sequence Diversity Search");e.dockManager.dock(t,"down")}static searchSubsequenceEditor(e){const t=(0,Ne.me)();1===t.length?e.func.prepare({macromolecules:t[0]}).call(!0):new ht.a7(t,Uo.seqHelper)}static SubsequenceSearchTopMenu(e){o.shell.tv.getFiltersGroup({createDefaultFilters:!1}).updateOrAdd({type:"Bio:bioSubstructureFilter",column:e.name,columnName:e.name}),o.shell.tv.grid.scrollToCell(e,0)}static async sequenceIdentityScoring(e,t,n){const i=Uo.seqHelper;return Oi(e,t,n,fe.IDENTITY,i)}static async sequenceSimilarityScoring(e,t,n){const i=Uo.seqHelper;return Oi(e,t,n,fe.SIMILARITY,i)}static async manageMonomerLibraries(){ti()}static async manageLibrariesView(){await ni()}static async manageMonomersView(){const e=await Ln.getInstance();await e.getViewRoot()}static async manageMonomerLibrariesView(e){const t=await ni(!1);return t.parentCall=o.functions.getCurrentCall(),t}static async manageMonomerLibrariesViewTreeBrowser(e){(await(await bn.getInstance()).getAvaliableLibraryNames()).forEach(t=>{const n=t.endsWith(".json")?t.substring(0,t.length-5):t;e.item(n).onSelected.subscribe(async()=>{const e=await Ln.getInstance();(await e.getViewRoot(t,!0)).parentCall=o.functions.getCurrentCall(),e.resetCurrentRowFollowing()})})}static async monomerCollectionsApp(){return await async function(e=!0){if(e){const e=Array.from(o.shell.views).find(e=>e.name===_o.VIEW_NAME);if(e)return o.shell.v=e,e}const t=new _o,n=await t.init();return e&&o.shell.addView(n),n}(!1)}static saveAsFasta(){(0,Un.TE)()}static bioSubstructureFilter(){return new qn._i(Uo.seqHelper,Uo.logger)}static bioSubstructureFilterTest(){return new qn._i(Uo.seqHelper,Uo.logger)}static async webLogoLargeApp(){const e=r.TaskBarProgressIndicator.create("WebLogo");try{const e=new URLSearchParams(window.location.search),t=new fi(e,"webLogoLargeApp"),n=await Uo.files.readCsv("data/sample_PT_100000x5.csv");await o.data.detectSemanticTypes(n),await t.init(n)}finally{e.close()}}static async webLogoAggApp(){const e=r.TaskBarProgressIndicator.create("WebLogo ...");try{const e=new URLSearchParams(window.location.search),t=new fi(e,"webLogoAggApp"),n=await Uo.files.readCsv("samples/FASTA_PT_activity.csv");await o.data.detectSemanticTypes(n),await t.init(n)}finally{e.close()}}static async getRegionApp(){const e=r.TaskBarProgressIndicator.create("getRegion ...");try{const e=new URLSearchParams(window.location.search),t=new Ni(e,"getRegionApp");await t.init()}finally{e.close()}}static async getRegionHelmApp(){const e=r.TaskBarProgressIndicator.create("getRegion ...");try{const e=new URLSearchParams(window.location.search),t=await Uo.files.readCsv("samples/HELM_empty_vals.csv"),n=new Ni(e,"getRegionHelmApp");await n.init({df:t,colName:"HELM"})}finally{e.close()}}static longSeqTableSeparator(){const e=r.DataFrame.fromColumns((0,Pe.dW)());o.shell.addTableView(e)}static longSeqTableFasta(){const e=r.DataFrame.fromColumns([(0,Pe.Hx)(Uo.seqHelper,ue.Hi.FASTA)]);o.shell.addTableView(e)}static longSeqTableHelm(){const e=r.DataFrame.fromColumns([(0,Pe.Hx)(Uo.seqHelper,ue.Hi.HELM)]);o.shell.addTableView(e)}static addCopyMenu(e,t){!function(e,t,i){const s=Object.values(ue.Hi).filter(e=>e!==ue.Hi.CUSTOM);t.group("Copy").items(s,t=>{const n=e.column,s=e.rowIndex,r=i.getSeqHandler(n),a=t===ue.Hi.SEPARATOR?Uo.properties.defaultSeparator??"-":void 0,l=r.getJoiner({notation:t,separator:a})(r.getSplitted(s));navigator.clipboard?(navigator.clipboard.writeText(l),o.shell.info(`Value of notation '${t}' copied to clipboard`)):o.shell.warning("The clipboard functionality requires a secure origin — either HTTPS or localhost")});const r=e.column,a=(0,Et.Ln)(r);if(a.length>0&&new Li.$(r).hasAnnotations()){const e=a.filter(e=>e.category===St.eI.Structure);if(e.length>0){const s=t.group("Annotations");for(const t of e)t.start&&t.end&&s.item(`Extract ${t.name} as Column`,()=>{n.e(288).then(n.bind(n,9288)).then(e=>{try{e.extractAnnotatedRegion(r.dataFrame,r,t.name,i)}catch(e){o.shell.error(`Failed to extract region: ${e.message??e}`)}})});a.filter(e=>e.category===St.eI.Liability).length>0&&s.item("Filter: Rows with Liability Hits",()=>{n.e(288).then(n.bind(n,9288)).then(e=>{e.filterByLiabilityHits(r.dataFrame,r)})})}}}(e,t,Uo.seqHelper)}static async demoBioSimilarityDiversity(){await async function(){const e=await Uo.files.readCsv("samples/peptides-non-natural.csv"),t=o.shell.addTableView(e);Uo.files.readAsText("demo-files/bio_similarity_diversity.layout").then(async e=>{const n=r.ViewLayout.fromJson(e);await r.delay(100),t.loadLayout(n)})}()}static async demoBioSequenceSpace(){await async function(){const e=await o.functions.eval("Bio:SeqSpaceDemo"),t=await o.dapi.projects.find(e.id);await t.open()}()}static async demoBioActivityCliffs(){await async function(){o.shell.windows.showContextPanel=!0;const e=await o.functions.eval("Bio:BioDemoActivityCliffs"),t=await o.dapi.projects.find(e.id);await t.open();let n,i=null;for(const e of o.shell.tv.viewers)e.type==r.VIEWER.SCATTER_PLOT&&(i=e);try{await(0,hi.bk)(()=>{const e=i?.root.getElementsByClassName("scatter_plot_link");return!!e?.length&&(n=e[0],!0)},"",1e4),n.click()}catch(e){}}()}static async demoBioAtomicLevel(){await async function(){const e=await Uo.files.readCsv("demo-files/Atomic_Level.csv");await e.meta.detectSemanticTypes();const t=o.shell.addTableView(e);await r.delay(100),await(0,He.Qc)(e.col("helm"),e.col("molfile(helm)"),Uo.monomerLib,Uo.seqHelper,Uo.rdKitModule,!0),(0,Ne.Kd)(t.grid,"molfile(HELM)",500,300,!0),(0,Ne.Kd)(t.grid,"HELM",500,void 0,!0),e.col("molfile(helm)").setTag(".sequence-src-highlight-monomers","false"),e.col("molfile(helm)").setTag(".sequence-src-col","HELM"),o.shell.info("Hover over monomers in HELM column to highlight them in molecular structure.",{timeout:10})}()}static async demoBioSiRNA(){await async function(){const e=await Uo.files.readCsv("demo-files/SIRNA.csv"),t=await Uo.files.readAsText("demo-files/SIRNA.layout"),n=r.ViewLayout.fromJson(t),i=o.shell.addTableView(e);await r.delay(100),i.loadLayout(n,!0),await e.meta.detectSemanticTypes(),o.shell.info("Hover over the oligo structrues to see modifications to different sugars, linkers and residues.",{timeout:10})}()}static async sdfToJsonLib(e){const t=function(e){const t=[];for(let n=0;n<e.rowCount;n++){const i={};Object.keys(de.Ec).forEach(t=>{if("symbol"===t){const o=e.get(de.Ec[t],n);i[t]="."===o?e.get(de.yw,n):o}else if("rgroups"===t){const o=e.get(de.Ec[t],n).split("\n"),s=[];o.forEach(e=>{const t={},n=e.substring(e.lastIndexOf("]")+1),i=e.match(/\[R(\d+)\]/)[1];t.capGroupSmiles="H"===n?`[*:${i}][H]`:`O[*:${i}]`,t.alternateId="H"===n?`R${i}-H`:`R${i}-OH`,t.capGroupName="H"===n?"H":"OH",t.label=`R${i}`,s.push(t)}),i[t]=s}else de.Ec[t]&&(i[t]=e.get(de.Ec[t],n))}),i.author??(i.author=""),i.id??(i.id=0),i.smiles??(i.smiles=""),i.monomerType??(i.monomerType="Backbone"),i.createDate??(i.createDate=null),t.push(i)}return t}(e),n=JSON.stringify(t);r.Utils.download(`${e.name}.json`,n)}static async demoAntibodies(){await async function(){const e=await Uo.files.readCsv("demo-files/Antibody_HC.csv"),t=e.col("AntibodyHC");[["units","fasta"],["aligned","SEQ.MSA"],["alphabet","PT"],["cell.renderer","sequence"],["quality","Macromolecule"],[".semantic-detection-duration","8"],[".annotations",'[{"id":"deamid-ng","name":"Deamidation (NG)","description":"deamidation liability pattern (111 hits)","start":null,"end":null,"visualType":"motif","category":"liability","color":"#E53935","severity":"high","motifPattern":"NG","autoGenerated":true},{"id":"deamid-ns","name":"Deamidation (NS)","description":"deamidation liability pattern (859 hits)","start":null,"end":null,"visualType":"motif","category":"liability","color":"#E53935","severity":"medium","motifPattern":"NS","autoGenerated":true},{"id":"deamid-na","name":"Deamidation (NA)","description":"deamidation liability pattern (69 hits)","start":null,"end":null,"visualType":"motif","category":"liability","color":"#E53935","severity":"low","motifPattern":"NA","autoGenerated":true},{"id":"deamid-nd","name":"Deamidation (ND)","description":"deamidation liability pattern (18 hits)","start":null,"end":null,"visualType":"motif","category":"liability","color":"#E53935","severity":"low","motifPattern":"ND","autoGenerated":true},{"id":"deamid-nt","name":"Deamidation (NT)","description":"deamidation liability pattern (546 hits)","start":null,"end":null,"visualType":"motif","category":"liability","color":"#E53935","severity":"low","motifPattern":"NT","autoGenerated":true},{"id":"isom-dg","name":"Isomerization (DG)","description":"isomerization liability pattern (118 hits)","start":null,"end":null,"visualType":"motif","category":"liability","color":"#FF9800","severity":"high","motifPattern":"DG","autoGenerated":true},{"id":"isom-ds","name":"Isomerization (DS)","description":"isomerization liability pattern (306 hits)","start":null,"end":null,"visualType":"motif","category":"liability","color":"#FF9800","severity":"medium","motifPattern":"DS","autoGenerated":true},{"id":"oxid-m","name":"Oxidation (Met)","description":"oxidation liability pattern (1220 hits)","start":null,"end":null,"visualType":"point","category":"liability","color":"#9C27B0","severity":"medium","motifPattern":"M","autoGenerated":true},{"id":"oxid-w","name":"Oxidation (Trp)","description":"oxidation liability pattern (2593 hits)","start":null,"end":null,"visualType":"point","category":"liability","color":"#9C27B0","severity":"low","motifPattern":"W","autoGenerated":true},{"id":"glyco-nxst","name":"N-glycosylation","description":"glycosylation liability pattern (38 hits)","start":null,"end":null,"visualType":"motif","category":"liability","color":"#4CAF50","severity":"high","motifPattern":"N[^P][ST]","autoGenerated":true},{"id":"free-cys","name":"Free Cysteine","description":"freeCysteine liability pattern (2327 hits)","start":null,"end":null,"visualType":"point","category":"liability","color":"#607D8B","severity":"info","motifPattern":"C","autoGenerated":true},{"id":"kabat-heavy-fr1","name":"FR1","description":"FR1 (KABAT 1-30)","start":"1","end":"30","visualType":"region","category":"structure","sourceScheme":"KABAT","autoGenerated":true},{"id":"kabat-heavy-cdr1","name":"CDR1","description":"CDR1 (KABAT 31-35)","start":"31","end":"35","visualType":"region","category":"structure","sourceScheme":"KABAT","autoGenerated":true},{"id":"kabat-heavy-fr2","name":"FR2","description":"FR2 (KABAT 36-49)","start":"36","end":"49","visualType":"region","category":"structure","sourceScheme":"KABAT","autoGenerated":true},{"id":"kabat-heavy-cdr2","name":"CDR2","description":"CDR2 (KABAT 50-65)","start":"50","end":"65","visualType":"region","category":"structure","sourceScheme":"KABAT","autoGenerated":true},{"id":"kabat-heavy-fr3","name":"FR3","description":"FR3 (KABAT 66-94)","start":"66","end":"94","visualType":"region","category":"structure","sourceScheme":"KABAT","autoGenerated":true},{"id":"kabat-heavy-cdr3","name":"CDR3","description":"CDR3 (KABAT 95-102)","start":"95","end":"102","visualType":"region","category":"structure","sourceScheme":"KABAT","autoGenerated":true},{"id":"kabat-heavy-fr4","name":"FR4","description":"FR4 (KABAT 103-113)","start":"103","end":"113","visualType":"region","category":"structure","sourceScheme":"KABAT","autoGenerated":true}]'],[".annotationColumnName","~AntibodyHC_annotations"],[".id","750dcca0-48b0-11f1-e663-211b32f9e20c"],[".numberingScheme","kabat"],[".regions",'[{"name":"FR1","description":"FR1 (KABAT 1-30)","start":"1","end":"30"},{"name":"CDR1","description":"CDR1 (KABAT 31-35)","start":"31","end":"35"},{"name":"FR2","description":"FR2 (KABAT 36-49)","start":"36","end":"49"},{"name":"CDR2","description":"CDR2 (KABAT 50-65)","start":"50","end":"65"},{"name":"FR3","description":"FR3 (KABAT 66-94)","start":"66","end":"94"},{"name":"CDR3","description":"CDR3 (KABAT 95-102)","start":"95","end":"102"},{"name":"FR4","description":"FR4 (KABAT 103-113)","start":"103","end":"113"}]'],[".positionShift","42.10943057774151"]].forEach(([e,n])=>t.setTag(e,n));const n=e.col("cluster (dbscan)"),i=n.convertTo(r.TYPE.STRING);e.columns.remove(n.name),e.columns.add(i);const s=await Uo.files.readAsText("demo-files/Antibody_HC.layout"),a=r.ViewLayout.fromJson(s);a.columns.forEach(t=>{const n=e.col(t.name);n&&Object.entries(t.tags).forEach(([e,t])=>n.setTag(e,t))});const l=o.shell.addTableView(e);await r.delay(100),l.loadLayout(a,!0)}()}static async seq2atomic(e,t){return e.trim()?Wo.toAtomicLevelSingleSeq(e):""}static async seqIdentity(e,t){if(!e.trim())return null;try{const n=r.Column.fromList(r.COLUMN_TYPE.STRING,"seq",[e]),i=r.DataFrame.fromColumns([n]);if(!await o.functions.call("Bio:detectMacromolecule",{col:n}))throw new Error("Macromolecule required");return(await Oi(i,n,t,fe.IDENTITY,Uo.seqHelper)).get(0)}catch(e){const[t,n]=(0,we.AP)(e);throw Uo.logger.error(t,void 0,n),e}}static async detectMacromoleculeProbe(e,t="",n=100){const i=await e.readAsString();await async function(e,t,n){const i=r.TaskBarProgressIndicator.create("detectMacromolecule probe ...");try{let s=0;const a=await o.functions.call("Bio:detectMacromoleculeEnableStore");let l=0;for(let c=0;c<n;++c){const u=r.DataFrame.fromCsv(e),h=t?u.getCol(t):u.columns.byIndex(0);await o.functions.call("Bio:detectMacromolecule",{col:h})!==r.SEMTYPE.MACROMOLECULE&&(++l,console.warn(`Reject reason: ${a.last.rejectReason}`));const d=c/n;d-s>=.1&&(s=d,i.update(100*d,`detectMacromolecule probe ${l}/${c}/${n} ...`),await r.delay(0))}l>0?o.shell.warning(`detectMacromolecule failed ${l} / ${n}`):o.shell.info(`detectMacromolecule success ${n}`)}finally{i.close()}}(i,t,n)}static async getSeqHelper(){return await Wo.initBio(),Uo.seqHelper}static async getMolFromHelm(e,t,n=!0){return async function(e,t,n=!0,i){const o=Uo.seqHelper,s=(await o.getHelmToMolfileConverter(i)).convertToRdKitBeautifiedMolfileColumn(t,n,Uo.rdKitModule,i);return s.semType=r.SEMTYPE.MOLECULE,s}(0,t,n,Uo.monomerLib)}}Go([o.decorators.func({description:"Returns an instance of the monomer library helper",outputs:[{type:"object",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"getMonomerLibHelper",null),Go([o.decorators.init({tags:["init"]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"initBio",null),Go([o.decorators.func({meta:{role:"tooltip"},tags:["tooltip"]}),Vo(0,o.decorators.param({options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column]),Bo("design:returntype",r.Widget)],Wo,"sequenceTooltip",null),Go([o.decorators.func({}),Bo("design:type",Function),Bo("design:paramtypes",[String]),Bo("design:returntype",Promise)],Wo,"standardiseMonomerLibrary",null),Go([o.decorators.func({"top-menu":"Bio | Manage | Match with Monomer Library...",description:"Matches molecules in a column with monomers from the selected library(s)"}),Vo(1,o.decorators.param({type:"column",options:{semType:"Molecule"}})),Vo(2,o.decorators.param({type:"string",options:{choices:["PEPTIDE","RNA","CHEM"],initialValue:"PEPTIDE",caption:"Polymer Type"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,String]),Bo("design:returntype",Promise)],Wo,"matchWithMonomerLibrary",null),Go([o.decorators.func({outputs:[{type:"object",name:"monomerLib"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Object)],Wo,"getBioLib",null),Go([o.decorators.func({outputs:[{type:"object",name:"result"}]}),Vo(0,o.decorators.param({type:"column",options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column]),Bo("design:returntype",Object)],Wo,"getSeqHandler",null),Go([o.decorators.panel({name:"Bioinformatics | Get Region",description:"Creates a new column with sequences of the region between start and end",tags:["panel"]}),Vo(0,o.decorators.param({type:"column",options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column]),Bo("design:returntype",r.Widget)],Wo,"getRegionPanel",null),Go([o.decorators.panel({name:"Bioinformatics | Manage Monomer Libraries",meta:{"exclude-actions-panel":"true"},tags:["exclude-actions-panel"]}),Vo(0,o.decorators.param({name:"seqColumn",options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column]),Bo("design:returntype",Promise)],Wo,"libraryPanel",null),Go([o.decorators.editor({tags:["editor"]}),Bo("design:type",Function),Bo("design:paramtypes",[r.FuncCall]),Bo("design:returntype",void 0)],Wo,"GetRegionEditor",null),Go([o.decorators.editor({tags:["editor"]}),Bo("design:type",Function),Bo("design:paramtypes",[r.FuncCall]),Bo("design:returntype",void 0)],Wo,"SplitToMonomersEditor",null),Go([o.decorators.editor({tags:["editor"]}),Bo("design:type",Function),Bo("design:paramtypes",[r.FuncCall]),Bo("design:returntype",void 0)],Wo,"SequenceSpaceEditor",null),Go([o.decorators.editor({tags:["editor"]}),Bo("design:type",Function),Bo("design:paramtypes",[r.FuncCall]),Bo("design:returntype",void 0)],Wo,"SeqActivityCliffsEditor",null),Go([o.decorators.func({name:"customSequenceCellRenderer",tags:["cellRenderer"],meta:{cellType:"sequence",columnTags:"quality=Macromolecule, units=custom",role:"cellRenderer"},outputs:[{type:"grid_cell_renderer",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",r.GridCellRenderer)],Wo,"customSequenceCellRenderer",null),Go([o.decorators.func({name:"fastaSequenceCellRenderer",tags:["cellRenderer"],meta:{cellType:"sequence",columnTags:"quality=Macromolecule, units=fasta",role:"cellRenderer"},outputs:[{type:"grid_cell_renderer",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",We)],Wo,"fastaSequenceCellRenderer",null),Go([o.decorators.func({name:"separatorSequenceCellRenderer",tags:["cellRenderer"],meta:{cellType:"sequence",columnTags:"quality=Macromolecule, units=separator",role:"cellRenderer"},outputs:[{type:"grid_cell_renderer",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",We)],Wo,"separatorSequenceCellRenderer",null),Go([o.decorators.func({name:"bilnSequenceCellRenderer",tags:["cellRenderer"],meta:{cellType:"sequence",columnTags:"quality=Macromolecule, units=biln",role:"cellRenderer"},outputs:[{type:"grid_cell_renderer",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",We)],Wo,"bilnSequenceCellRenderer",null),Go([o.decorators.func({name:"refineNotationProviderForBiln",outputs:[{type:"bool",name:"result"}],tags:["notationRefiner"],meta:{role:"notationRefiner"}}),Vo(0,o.decorators.param({type:"column"})),Vo(1,o.decorators.param({type:"object"})),Vo(2,o.decorators.param({type:"string",options:{nullable:!0,optional:!0}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column,Object,Object]),Bo("design:returntype",Boolean)],Wo,"refineNotationProviderForBiln",null),Go([o.decorators.panel({name:"Bioinformatics | Sequence Renderer",tags:["panel"]}),Vo(0,o.decorators.param({options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column]),Bo("design:returntype",r.Widget)],Wo,"macroMolColumnPropertyPanel",null),Go([o.decorators.panel({name:"Composition analysis",tags:["bio","widgets","panel"],meta:{role:"widgets",domain:"bio"}}),Vo(0,o.decorators.param({options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.SemanticValue]),Bo("design:returntype",r.Widget)],Wo,"compositionAnalysisWidget",null),Go([o.decorators.panel({name:"Monomer",tags:["bio","panel"],meta:{domain:"bio"}}),Vo(0,o.decorators.param({options:{semType:"Monomer"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.SemanticValue]),Bo("design:returntype",r.Widget)],Wo,"monomerInfoPanel",null),Go([o.decorators.func({name:"MacromoleculeDifferenceCellRenderer",tags:["cellRenderer"],meta:{cellType:"MacromoleculeDifference",columnTags:"quality=MacromoleculeDifference",role:"cellRenderer"},outputs:[{type:"grid_cell_renderer",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",je)],Wo,"macromoleculeDifferenceCellRenderer",null),Go([o.decorators.func({outputs:[{type:"object",name:"result"}]}),Vo(0,o.decorators.param({options:{choices:["Local alignment","Global alignment"]}})),Vo(1,o.decorators.param({options:{choices:["AUTO","NUCLEOTIDES","BLOSUM45","BLOSUM50","BLOSUM62","BLOSUM80","BLOSUM90","PAM30","PAM70","PAM250","SCHNEIDER","TRANS"]}})),Bo("design:type",Function),Bo("design:paramtypes",[String,String,Number,String,String]),Bo("design:returntype",void 0)],Wo,"sequenceAlignment",null),Go([o.decorators.panel({name:"WebLogo",description:"WebLogo",tags:["viewer","panel"],meta:{icon:"files/icons/weblogo-viewer.svg",role:"viewer"},outputs:[{type:"viewer",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"webLogoViewer",null),Go([o.decorators.panel({name:"VdRegions",description:"V-Domain regions viewer",tags:["viewer"],meta:{icon:"files/icons/vdregions-viewer.svg",role:"viewer"},outputs:[{type:"viewer",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"vdRegionsViewer",null),Go([o.decorators.func({name:"getRegion",description:"Gets a new column with sequences of the region between start and end"}),Vo(0,o.decorators.param({type:"column"})),Vo(1,o.decorators.param({type:"string",options:{optional:!0}})),Vo(2,o.decorators.param({type:"string",options:{optional:!0}})),Vo(3,o.decorators.param({type:"string",options:{optional:!0,description:"Name of the column to be created"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column,Object,Object,Object]),Bo("design:returntype",r.Column)],Wo,"getRegion",null),Go([o.decorators.func({name:"Get Region Top Menu",description:"Get sequences for a region specified from a Macromolecule","top-menu":"Bio | Calculate | Extract Region...",editor:"Bio:GetRegionEditor"}),Vo(0,o.decorators.param({options:{description:"Input data table"}})),Vo(1,o.decorators.param({options:{semType:"Macromolecule",description:"Sequence column"}})),Vo(2,o.decorators.param({type:"string",options:{optional:!0,description:"Region start position name"}})),Vo(3,o.decorators.param({type:"string",options:{optional:!0,description:"Region end position name"}})),Vo(4,o.decorators.param({type:"string",options:{optional:!0,description:"Region column name"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,Object,Object,Object]),Bo("design:returntype",Promise)],Wo,"getRegionTopMenu",null),Go([o.decorators.func({name:"Apply Numbering Scheme",description:"Assigns antibody numbering (IMGT/Kabat/Chothia/AHo)","top-menu":"Bio | Annotate | Apply Numbering Scheme..."}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"applyNumberingScheme",null),Go([o.decorators.func({name:"Scan Liabilities",description:"Scans macromolecule sequences for deamidation, oxidation, and other liabilities","top-menu":"Bio | Annotate | Scan Liabilities..."}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"scanLiabilities",null),Go([o.decorators.func({name:"Manage Annotations",description:"View and manage sequence annotations on macromolecule columns","top-menu":"Bio | Annotate | Manage Annotations..."}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"manageAnnotations",null),Go([o.decorators.func({name:"Sequence Column Input",description:"Creates a new input for sequence columns with ability to extract a region"}),Bo("design:type",Function),Bo("design:paramtypes",[String,Object]),Bo("design:returntype",Object)],Wo,"sequenceColumnInput",null),Go([o.decorators.func({name:"Sequence Activity Cliffs",description:"Detects pairs of molecules with similar structure and significant difference in any given property","top-menu":"Bio | Analyze | Activity Cliffs...",editor:"Bio:SeqActivityCliffsEditor",outputs:[]}),Vo(0,o.decorators.param({options:{description:"Input data table"}})),Vo(1,o.decorators.param({type:"string",options:{semType:"Macromolecule",description:"Input data table"}})),Vo(3,o.decorators.param({options:{initialValue:"80",description:"Similarity cutoff"}})),Vo(4,o.decorators.param({type:"string",options:{choices:["UMAP","t-SNE"]}})),Vo(5,o.decorators.param({type:"string",options:{choices:["Hamming","Levenshtein","Monomer chemical distance"]}})),Vo(6,o.decorators.param({type:"func"})),Vo(7,o.decorators.param({type:"object",options:{optional:!0}})),Vo(8,o.decorators.param({options:{optional:!0}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,r.Column,Number,String,String,r.Func,Object,Boolean]),Bo("design:returntype",Promise)],Wo,"activityCliffs",null),Go([o.decorators.func({name:"seqActivityCliffsInitFunction"}),Vo(0,o.decorators.param({type:"viewer"})),Bo("design:type",Function),Bo("design:paramtypes",[r.ScatterPlotViewer]),Bo("design:returntype",Promise)],Wo,"seqActivityCliffsInitFunction",null),Go([o.decorators.func({meta:{role:"transform"}}),Vo(0,o.decorators.param({options:{description:"Input data table"}})),Vo(1,o.decorators.param({type:"column",options:{semType:"Macromolecule"}})),Vo(2,o.decorators.param({type:"column",options:{type:"numerical"}})),Vo(3,o.decorators.param({options:{description:"Similarity cutoff",initialValue:"80"}})),Vo(4,o.decorators.param({type:"string"})),Vo(5,o.decorators.param({type:"string"})),Vo(6,o.decorators.param({options:{optional:!0}})),Vo(7,o.decorators.param({options:{optional:!0}})),Vo(8,o.decorators.param({options:{optional:!0}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,r.Column,Number,String,String,String,Boolean,Array]),Bo("design:returntype",Promise)],Wo,"seqActivityCliffsTransform",null),Go([o.decorators.func({name:"Encode Sequences",tags:["dim-red-preprocessing-function"],meta:{supportedSemTypes:"Macromolecule",supportedTypes:"string",supportedDistanceFunctions:"Hamming,Levenshtein,Monomer chemical distance,Needlemann-Wunsch",role:"dim-red-preprocessing-function"},outputs:[{type:"object",name:"result"}]}),Vo(0,o.decorators.param({options:{semType:"Macromolecule"}})),Vo(1,o.decorators.param({type:"string"})),Vo(2,o.decorators.param({options:{initialValue:"1",caption:"Gap open penalty",optional:!0}})),Vo(3,o.decorators.param({options:{initialValue:"0.6",caption:"Gap extension penalty",optional:!0}})),Vo(4,o.decorators.param({options:{caption:"Fingerprint type",initialValue:"Morgan",choices:["Morgan","RDKit","Pattern","AtomPair","MACCS","TopologicalTorsion"],optional:!0}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column,String,Number,Number,String]),Bo("design:returntype",Promise)],Wo,"macromoleculePreprocessingFunction",null),Go([o.decorators.func({name:"Helm Fingerprints",meta:{supportedSemTypes:"Macromolecule",supportedTypes:"string",supportedUnits:"helm",supportedDistanceFunctions:"Tanimoto,Asymmetric,Cosine,Sokal"},outputs:[{type:"object",name:"result"}]}),Vo(0,o.decorators.param({type:"column",options:{semType:"Macromolecule"}})),Vo(1,o.decorators.param({type:"string"})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column,String]),Bo("design:returntype",Promise)],Wo,"helmPreprocessingFunction",null),Go([o.decorators.func({name:"Sequence Space",description:"Creates 2D sequence space with projected sequences by pairwise distance","top-menu":"Bio | Analyze | Sequence Space...",editor:"Bio:SequenceSpaceEditor",outputs:[{type:"viewer",name:"result"}]}),Vo(1,o.decorators.param({options:{semType:"Macromolecule"}})),Vo(2,o.decorators.param({type:"string",options:{choices:["UMAP","t-SNE"]}})),Vo(3,o.decorators.param({type:"string",options:{choices:["Hamming","Levenshtein","Monomer chemical distance"]}})),Vo(4,o.decorators.param({options:{initialValue:"true"}})),Vo(5,o.decorators.param({type:"func",options:{optional:!0}})),Vo(6,o.decorators.param({type:"object",options:{optional:!0}})),Vo(7,o.decorators.param({options:{optional:!0,initialValue:"true"}})),Vo(8,o.decorators.param({options:{optional:!0}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,String,String,Boolean,r.Func,Object,Boolean,Boolean]),Bo("design:returntype",Promise)],Wo,"sequenceSpaceTopMenu",null),Go([o.decorators.func({outputs:[{type:"viewer",name:"result"}],meta:{role:"transform"}}),Vo(1,o.decorators.param({options:{semType:"Macromolecule"}})),Vo(2,o.decorators.param({type:"string"})),Vo(3,o.decorators.param({type:"string"})),Vo(4,o.decorators.param({options:{initialValue:"true"}})),Vo(5,o.decorators.param({options:{optional:!0}})),Vo(6,o.decorators.param({options:{optional:!0}})),Vo(7,o.decorators.param({options:{optional:!0}})),Vo(8,o.decorators.param({options:{optional:!0}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,String,String,Boolean,String,Boolean,Array,String]),Bo("design:returntype",Promise)],Wo,"sequenceSpaceTransform",null),Go([o.decorators.func({name:"Molecules to HELM","top-menu":"Bio | Transform | Molecules to HELM...",description:"Converts Peptide molecules to HELM notation by matching with monomer library"}),Vo(0,o.decorators.param({name:"table",options:{description:"Input data table"}})),Vo(1,o.decorators.param({name:"molecules",options:{semType:"Molecule",description:"Molecule column"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column]),Bo("design:returntype",Promise)],Wo,"moleculesToHelmTopMenu",null),Go([o.decorators.func({name:"Molecule to HELM Single",description:"Converts a single molecule to HELM notation without requiring a table or column",outputs:[{name:"result",type:"string",options:{semType:"Macromolecule",units:"helm"}}]}),Vo(0,o.decorators.param({name:"molecule",options:{semType:"Molecule",description:"Input molecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[String]),Bo("design:returntype",Promise)],Wo,"moleculeToHelmSingle",null),Go([o.decorators.func({name:"To Atomic Level",description:"Converts sequences to molblocks","top-menu":"Bio | Transform | To Atomic Level..."}),Vo(0,o.decorators.param({options:{description:"Input data table"}})),Vo(1,o.decorators.param({options:{semType:"Macromolecule",caption:"Sequence"}})),Vo(2,o.decorators.param({options:{initialValue:"true",caption:"Non-linear",description:"Slower mode for cycling/branching HELM structures"}})),Vo(3,o.decorators.param({options:{initialValue:"false",caption:"Highlight monomers",description:"Highlight monomers' substructures of the molecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,Boolean,Boolean]),Bo("design:returntype",Promise)],Wo,"toAtomicLevel",null),Go([o.decorators.func({name:"To Atomic Level...",meta:{action:"to atomic level"}}),Vo(0,o.decorators.param({options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column]),Bo("design:returntype",Promise)],Wo,"toAtomicLevelAction",null),Go([o.decorators.panel({name:"Molecular Structure",tags:["bio","widgets","panel"],meta:{role:"widgets",domain:"bio"}}),Vo(0,o.decorators.param({name:"sequence",type:"semantic_value",options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.SemanticValue]),Bo("design:returntype",Promise)],Wo,"toAtomicLevelPanel",null),Go([o.decorators.func({name:"To Atomic Level Single sequence",description:"Converts a single sequence to molblock",outputs:[{name:"molfile",type:"string",options:{semType:"Molecule"}}]}),Vo(0,o.decorators.param({name:"sequence",type:"string",options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[String]),Bo("design:returntype",Promise)],Wo,"toAtomicLevelSingleSeq",null),Go([o.decorators.panel({name:"Molecular 3D Structure",tags:["bio","widgets","panel"],meta:{role:"widgets",domain:"bio"}}),Vo(0,o.decorators.param({type:"semantic_value",options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.SemanticValue]),Bo("design:returntype",Promise)],Wo,"sequence3dStructureWidget",null),Go([o.decorators.panel({name:"MSA",description:"Performs multiple sequence alignment",tags:["bio","panel"],meta:{domain:"bio"},"top-menu":"Bio | Analyze | MSA..."}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"multipleSequenceAlignmentDialog",null),Go([o.decorators.func({name:"Multiple Sequence Alignment",description:"Multiple sequence alignment",meta:{domain:"bio"}}),Vo(0,o.decorators.param({type:"column",options:{semType:"Macromolecule"}})),Vo(1,o.decorators.param({type:"column"})),Vo(2,o.decorators.param({type:"object",options:{optional:!0}})),Bo("design:type",Function),Bo("design:paramtypes",[Object,Object,Object]),Bo("design:returntype",Promise)],Wo,"alignSequences",null),Go([o.decorators.func({name:"PepSeA",description:"Aligns non-canonical peptide sequences using PepSeA Docker container (MAFFT)",meta:{role:"sequenceMSA"},outputs:[{name:"result",type:"column"}]}),Vo(0,o.decorators.param({type:"column",options:{semType:"Macromolecule"}})),Vo(1,o.decorators.param({type:"string",options:{choices:["mafft --auto","mafft","linsi","ginsi","einsi","fftns","fftnsi","nwns","nwnsi"],initialValue:"mafft --auto"}})),Vo(2,o.decorators.param({type:"double",options:{initialValue:"1.53"}})),Vo(3,o.decorators.param({type:"double",options:{initialValue:"0"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column,String,Number,Number]),Bo("design:returntype",Promise)],Wo,"pepseaMsa",null),Go([o.decorators.func({name:"Immunum",description:"Assigns antibody numbering (IMGT/Kabat) using the immunum WASM library",meta:{role:"antibodyNumbering"}}),Vo(0,o.decorators.param({type:"dataframe"})),Vo(1,o.decorators.param({type:"column",options:{semType:"Macromolecule"}})),Vo(2,o.decorators.param({type:"string",options:{choices:["imgt","kabat"],initialValue:"imgt"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,String]),Bo("design:returntype",Promise)],Wo,"immunumAntibodyNumbering",null),Go([o.decorators.func({name:"Compare Sequences",description:"Builds a MacromoleculeDifference column from two sequence columns (seq1#seq2)","top-menu":"Bio | Analyze | Compare sequences..."}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"compareSequences",null),Go([o.decorators.func({name:"Composition Analysis",description:"Visualizes sequence composition on a WebLogo plot","top-menu":"Bio | Analyze | Composition",meta:{icon:"files/icons/composition-analysis.svg"},outputs:[{name:"result",type:"viewer"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"compositionAnalysis",null),Go([o.decorators.fileHandler({name:"importFasta",tags:["fileHandler"],description:"Opens FASTA file",ext:"fasta, fna, ffn, faa, frn, fa, fst"}),Bo("design:type",Function),Bo("design:paramtypes",[String]),Bo("design:returntype",Array)],Wo,"importFasta",null),Go([o.decorators.fileHandler({name:"importBam",tags:["fileHandler"],description:"Opens Bam file",ext:"bam, bai"}),Bo("design:type",Function),Bo("design:paramtypes",[String]),Bo("design:returntype",Array)],Wo,"importBam",null),Go([o.decorators.func({name:"convertDialog","top-menu":"Bio | Transform | Convert Sequence Notation..."}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"convertDialog",null),Go([o.decorators.func({name:"Convert Notation...",meta:{action:"Convert Notation..."}}),Vo(0,o.decorators.param({options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column]),Bo("design:returntype",void 0)],Wo,"convertColumnAction",null),Go([o.decorators.func({name:"monomerCellRenderer",tags:["cellRenderer"],meta:{cellType:"Monomer",columnTags:"quality=Monomer",role:"cellRenderer"},outputs:[{type:"grid_cell_renderer",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Ci)],Wo,"monomerCellRenderer",null),Go([o.decorators.func({name:"testDetectMacromolecule"}),Vo(0,o.decorators.param({options:{choices:["Demo:Files/","System:AppData/"]}})),Bo("design:type",Function),Bo("design:paramtypes",[String]),Bo("design:returntype",Promise)],Wo,"testDetectMacromolecule",null),Go([o.decorators.func({name:"Split to Monomers","top-menu":"Bio | Transform | Split to Monomers...",editor:"Bio:SplitToMonomersEditor"}),Vo(1,o.decorators.param({options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column]),Bo("design:returntype",Promise)],Wo,"splitToMonomersTopMenu",null),Go([o.decorators.func({name:"Bio: getHelmMonomers",outputs:[{name:"result",type:"object"}]}),Vo(0,o.decorators.param({type:"column",options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column]),Bo("design:returntype",Array)],Wo,"getHelmMonomers",null),Go([o.decorators.func({name:"Sequence Similarity Search",meta:{icon:"files/icons/sequence-similarity-viewer.svg",role:"viewer"},tags:["viewer"],outputs:[{name:"result",type:"viewer"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Ct)],Wo,"similaritySearchViewer",null),Go([o.decorators.func({name:"similaritySearch",description:"Finds similar sequences","top-menu":"Bio | Search | Similarity Search",outputs:[{name:"result",type:"viewer"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"similaritySearchTopMenu",null),Go([o.decorators.func({name:"Sequence Diversity Search",tags:["viewer"],meta:{icon:"files/icons/sequence-diversity-viewer.svg",role:"viewer"},outputs:[{name:"result",type:"viewer"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",At)],Wo,"diversitySearchViewer",null),Go([o.decorators.func({name:"diversitySearch",description:"Finds the most diverse sequences","top-menu":"Bio | Search | Diversity Search",outputs:[{name:"result",type:"viewer"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"diversitySearchTopMenu",null),Go([o.decorators.editor({name:"SearchSubsequenceEditor",tags:["editor"]}),Bo("design:type",Function),Bo("design:paramtypes",[r.FuncCall]),Bo("design:returntype",void 0)],Wo,"searchSubsequenceEditor",null),Go([o.decorators.func({name:"Subsequence Search","top-menu":"Bio | Search | Subsequence Search ...",editor:"Bio:SearchSubsequenceEditor"}),Bo("design:type",Function),Bo("design:paramtypes",[r.Column]),Bo("design:returntype",void 0)],Wo,"SubsequenceSearchTopMenu",null),Go([o.decorators.func({name:"Identity",description:"Adds a column with fraction of matching monomers","top-menu":"Bio | Calculate | Identity..."}),Vo(0,o.decorators.param({options:{description:"Table containing Macromolecule column"}})),Vo(1,o.decorators.param({options:{semType:"Macromolecule",description:"Sequences to score"}})),Vo(2,o.decorators.param({options:{description:"Sequence,matching column format"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,String]),Bo("design:returntype",Promise)],Wo,"sequenceIdentityScoring",null),Go([o.decorators.func({name:"Similarity",description:"Adds a column with similarity scores, calculated as sum of monomer fingerprint similarities","top-menu":"Bio | Calculate | Similarity..."}),Vo(0,o.decorators.param({options:{description:"Table containing Macromolecule column"}})),Vo(1,o.decorators.param({options:{semType:"Macromolecule",description:"Sequences to score"}})),Vo(2,o.decorators.param({options:{description:"Sequence,matching column format"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,String]),Bo("design:returntype",Promise)],Wo,"sequenceSimilarityScoring",null),Go([o.decorators.func({name:"Manage Monomer Libraries",description:"Manage HELM monomer libraries"}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"manageMonomerLibraries",null),Go([o.decorators.func({name:"Manage Monomer Libraries View","top-menu":"Bio | Manage | Monomer Libraries"}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"manageLibrariesView",null),Go([o.decorators.func({name:"manageMonomersView",description:"Edit and create monomers","top-menu":"Bio | Manage | Monomers"}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"manageMonomersView",null),Go([o.decorators.app({tags:["app"],name:"Manage Monomer Libraries",browsePath:"Peptides",icon:"files/icons/monomers.png"}),Vo(0,o.decorators.param({options:{metaUrl:!0,optional:!0}})),Bo("design:type",Function),Bo("design:paramtypes",[String]),Bo("design:returntype",Promise)],Wo,"manageMonomerLibrariesView",null),Go([o.decorators.func({name:"Monomer Manager Tree Browser",meta:{role:"appTreeBrowser",app:"Manage Monomer Libraries"}}),Bo("design:type",Function),Bo("design:paramtypes",[r.TreeViewGroup]),Bo("design:returntype",Promise)],Wo,"manageMonomerLibrariesViewTreeBrowser",null),Go([o.decorators.app({tags:["app"],name:"Monomer Collections",browsePath:"Peptides",icon:"files/icons/monomers.png"}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"monomerCollectionsApp",null),Go([o.decorators.fileExporter({description:"As FASTA..."}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"saveAsFasta",null),Go([o.decorators.func({name:"Bio Substructure Filter",description:"Substructure filter for macromolecules",tags:["filter"],meta:{semType:"Macromolecule",role:"filter"},outputs:[{type:"filter",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",qn._i)],Wo,"bioSubstructureFilter",null),Go([o.decorators.func({name:"Bio Substructure Filter Test",description:"Substructure filter for Helm package tests",outputs:[{name:"result",type:"object"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",qn._i)],Wo,"bioSubstructureFilterTest",null),Go([o.decorators.func(),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"webLogoLargeApp",null),Go([o.decorators.func(),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"webLogoAggApp",null),Go([o.decorators.func(),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"getRegionApp",null),Go([o.decorators.func(),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"getRegionHelmApp",null),Go([o.decorators.func(),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"longSeqTableSeparator",null),Go([o.decorators.func(),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"longSeqTableFasta",null),Go([o.decorators.func(),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"longSeqTableHelm",null),Go([o.decorators.func(),Vo(0,o.decorators.param({type:"object"})),Vo(1,o.decorators.param({type:"object"})),Bo("design:type",Function),Bo("design:paramtypes",[r.Cell,r.Menu]),Bo("design:returntype",void 0)],Wo,"addCopyMenu",null),Go([o.decorators.demo({description:"Sequence similarity tracking and evaluation dataset diversity",demoPath:"Bioinformatics | Similarity, Diversity",path:"/apps/Tutorials/Demo/Bioinformatics/Similarity,%20Diversity"}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"demoBioSimilarityDiversity",null),Go([o.decorators.demo({description:"Exploring sequence space of Macromolecules, comparison with hierarchical clustering results",demoPath:"Bioinformatics | Sequence Space",path:"/apps/Tutorials/Demo/Bioinformatics/Sequence%20Space",meta:{isDemoDashboard:"true"}}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"demoBioSequenceSpace",null),Go([o.decorators.demo({description:"Activity Cliffs analysis on Macromolecules data",demoPath:"Bioinformatics | Activity Cliffs",path:"/apps/Tutorials/Demo/Bioinformatics/Activity%20Cliffs"}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"demoBioActivityCliffs",null),Go([o.decorators.demo({description:"Atomic level structure of Macromolecules",demoPath:"Bioinformatics | Atomic Level",path:"/apps/Tutorials/Demo/Bioinformatics/Atomic%20Level",meta:{demoSkip:"true"}}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"demoBioAtomicLevel",null),Go([o.decorators.demo({description:"SI-RNA sequences, molecular structures, curves and assay data",demoPath:"Bioinformatics | SI-RNA",path:"/apps/Tutorials/Demo/Bioinformatics/SI-RNA",meta:{demoSkip:"true"}}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"demoBioSiRNA",null),Go([o.decorators.func({name:"SDF to JSON Library"}),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame]),Bo("design:returntype",Promise)],Wo,"sdfToJsonLib",null),Go([o.decorators.demo({description:"Antibody sequences, numbering, liabilities, extraction and SAR",demoPath:"Bioinformatics | Antibodies",path:"/apps/Tutorials/Demo/Bioinformatics/Antibodies"}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"demoAntibodies",null),Go([o.decorators.func({friendlyName:"seq2atomic",description:"Converts a `Macromolecule` sequence to its atomic level `Molecule` representation",outputs:[{name:"molfile",type:"string",options:{semType:"Molecule"}}]}),Vo(0,o.decorators.param({options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[String,Boolean]),Bo("design:returntype",Promise)],Wo,"seq2atomic",null),Go([o.decorators.func({name:"seqIdentity",friendlyName:"seqIdentity",description:"Gets identity to a reference sequence"}),Vo(0,o.decorators.param({options:{semType:"Macromolecule"}})),Vo(1,o.decorators.param({options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[String,String]),Bo("design:returntype",Promise)],Wo,"seqIdentity",null),Go([o.decorators.func(),Vo(2,o.decorators.param({options:{initialValue:"100"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.FileInfo,String,Number]),Bo("design:returntype",Promise)],Wo,"detectMacromoleculeProbe",null),Go([o.decorators.func({outputs:[{type:"object",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"getSeqHelper",null),Go([o.decorators.func(),Vo(1,o.decorators.param({type:"column"})),Vo(2,o.decorators.param({options:{initialValue:"true"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,Boolean]),Bo("design:returntype",Promise)],Wo,"getMolFromHelm",null)},4954(e,t,n){"use strict";n.d(t,{a7:()=>d,if:()=>p,BQ:()=>g,nI:()=>m});var i=n(4328),o=n(7389),s=n(6082),r=n(2003),a=n(439);async function l(e,t,n=!1,o){const r=t.getSeqHandler(e);let a;o??=new Map;const l=r.isHelm()?t.getSeqMonomers(e):Object.keys(r.stats.freq).filter(e=>""!==e);for(let e=0;e<l.length;e++)o.has(l[e])||o.set(l[e],`${o.size+1}`);if(r.isHelm())a=await i.functions.call("HELM:getMolFiles",{col:e}),a=function(e,t,n=!1){const i=new Array(e.length);for(let o=0;o<e.length;o++){let s=0,r=0,a="\n Datagrok macromolecule handler\n\n 0 0 0 0 0 0 999 V3000\nM V30 BEGIN CTAB\n";const l=e.get(o);s=l.indexOf("\n",s)+1,s=l.indexOf("\n",s)+1,s=l.indexOf("\n",s)+1;const c=parseInt(l.substring(s,s+3)),u=parseInt(l.substring(s+3,s+6));a+=`M V30 COUNTS ${c} ${u} 0 0 0\n`,a+="M V30 BEGIN ATOM\n";for(let e=0;e<c;e++){s=l.indexOf("\n",s)+1+31,r=l.indexOf(" ",s);const i=l.substring(s,r);a+=n?`M V30 ${e+1} R${t.get(i)} 0.000 0.000 0 0\n`:`M V30 ${e+1} At 0.000 0.000 0 0 MASS=${t.get(i)}\n`}a+="M V30 END ATOM\n",a+="M V30 BEGIN BOND\n";for(let e=0;e<u;e++){s=l.indexOf("\n",s)+1;const t=parseInt(l.substring(s,s+3).trim()),n=parseInt(l.substring(s+3,s+6).trim());a+=`M V30 ${e+1} ${parseInt(l.substring(s+6,s+9).trim())} ${t} ${n}\n`}a+="M V30 END BOND\n",a+="M V30 END CTAB\n",a+="M END",i[o]=a}return i}(a,o,n);else{a=new Array(e.length);for(let t=0;t<e.length;t++){const e=c(r.getSplitted(t),o,n);a[t]=e}}return s.Column.fromStrings("monomericMols",a)}function c(e,t,n=!1){let i="\n Datagrok macromolecule handler\n\n 0 0 0 0 0 0 999 V3000\nM V30 BEGIN CTAB\n";i+=`M V30 COUNTS ${e.length} ${e.length?e.length-1:0} 0 0 0\n`,i+="M V30 BEGIN ATOM\n";for(let o=0;o<e.length;o++){const s=e.getCanonical(o);s!==a._S&&(i+=n?`M V30 ${o+1} R${t.get(s)} 0.000 0.000 0 0\n`:`M V30 ${o+1} At 0.000 0.000 0 0 MASS=${t.get(s)}\n`)}i+="M V30 END ATOM\n",i+="M V30 BEGIN BOND\n";for(let t=0;t<e.length-1;t++)i+=`M V30 ${t+1} 1 ${t+1} ${t+2}\n`;return i+="M V30 END BOND\n",i+="M V30 END CTAB\n",i+="M END",i}var u=n(4870);const h="substr_helm";class d{seqHelper;units;separator;inputsDiv;substructureInput;separatorInput;editHelmLink;columnsInput;grid;col;dialog;constructor(e,t){this.seqHelper=t,this.col=e[0],this.createUI()}editHelmLinkAction(){(0,u.Ku)(this.inputsDiv,this.grid.root),o.tools.waitForElementInDom(this.grid.root).then(()=>{setTimeout(()=>{this.grid.cell(h,0).element.children[0].dispatchEvent(new KeyboardEvent("keydown",{key:"Enter"}))},100)})}updateInputs(){const e=this.units===r.Hi.HELM?o.divV([this.columnsInput,this.editHelmLink]):this.units===r.Hi.SEPARATOR?o.inputs([this.columnsInput,this.substructureInput,this.separatorInput]):o.inputs([this.columnsInput,this.substructureInput]);(0,u.Ku)(this.inputsDiv,e)}updateNotationDiv(){this.units=this.col.meta.units,this.separator=this.col.getTag(r.gp.separator);const e=this.dialog.root.getElementsByClassName("notation-text")[0];e&&(e.textContent=`Notation: ${this.units}`)}createUI(){const e=i.shell.tv.dataFrame;this.columnsInput=o.input.column("Column",{table:e,value:this.col,onValueChanged:e=>{this.col=e,this.updateNotationDiv(),this.updateInputs()},filter:e=>e.semType===s.SEMTYPE.MACROMOLECULE}),this.substructureInput=o.input.string("Substructure",{value:""}),this.editHelmLink=o.link("Edit helm",()=>this.editHelmLinkAction(),void 0,{style:{position:"relative",left:"95px"}});const t=s.DataFrame.create(1);t.columns.addNewString(h).init(e=>""),t.col(h).semType=this.col.semType,t.col(h).meta.units=r.Hi.HELM,this.grid=t.plot.grid(),this.separatorInput=o.input.string("Separator",{value:this.separator}),this.inputsDiv=o.div(),this.units=this.col.meta.units,this.separator=this.col.getTag(r.gp.separator),this.updateInputs(),this.dialog=o.dialog("Substructure Search").add(o.divV([o.divText(`Notation: ${this.units}`,"notation-text"),this.inputsDiv])).onOK(async()=>{let e,n=this.units===r.Hi.HELM?t.get(h,0):this.substructureInput.value;this.units===r.Hi.SEPARATOR&&this.separatorInput.value!==this.separator&&this.separatorInput.value&&(n=n.replaceAll(this.separatorInput.value,this.separator)),e=this.units===r.Hi.HELM?await p(n,this.col,this.seqHelper):m(n,this.col),this.col.dataFrame.filter.and(e)}).show()}}function m(e,t,n){const i=n?function(e,t){const n=`${t}`.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),i=e.charAt(0)===t,o=e.charAt(e.length-1)===t,s=e.replace(new RegExp(`^${n}|${n}$`,"g"),"");return i?o?`${n}${s}${n}`:`${n}${s}${n}|${n}${s}$`:o?`^${s}${n}|${n}${s}${n}`:`^${s}${n}|${n}${s}${n}|${n}${s}$`}(e,n):e,o=s.BitSet.create(t.length);for(let n=0;n<t.length;n++){const s=t.get(n);(s.match(i)||s===e)&&o.set(n,!0,!1)}return o}async function p(e,t,n){t.version!==t.temp["last-invalidated-version"]&&await g(t,n,!0);const o=s.Column.string("helm",1).init(t=>e);o.semType=s.SEMTYPE.MACROMOLECULE,o.meta.units=r.Hi.HELM;const a=await l(o,n,!0,t.temp["monomers-dict"]);return(await i.functions.call("Chem:searchSubstructure",{molStringsColumn:t.temp["monomeric-mols"],molString:a.get(0),molBlockFailover:""})).get(0)}async function g(e,t,n){const i=s.TaskBarProgressIndicator.create(`Invalidating molfiles for ${e.name}`);try{await s.delay(10);const i=new Map,o=await l(e,t,n,i);e.temp["monomeric-mols"]=o,e.temp["monomers-dict"]=i,e.temp["last-invalidated-version"]=e.version}finally{i.close()}}},9287(e,t,n){"use strict";n.d(t,{showAnnotationManagerDialog:()=>u});var i=n(4328),o=n(7389),s=n(6082),r=n(4517),a=n(3736);const l={[r.eI.Structure]:"Structure (FR/CDR)",[r.eI.Liability]:"Liability",[r.eI.PTM]:"Post-translational Modification",[r.eI.Custom]:"Custom"},c={[r.Hq.High]:"High",[r.Hq.Medium]:"Medium",[r.Hq.Low]:"Low",[r.Hq.Info]:"Info"};function u(){const e=i.shell.tv?.dataFrame;if(!e)return void i.shell.warning("No table open");const t=e.columns.bySemTypeAll(s.SEMTYPE.MACROMOLECULE);if(0===t.length)return void i.shell.warning("No macromolecule columns found");let n=t[0];const r=o.input.column("Sequence Column",{table:e,value:n,filter:e=>e.semType===s.SEMTYPE.MACROMOLECULE,onValueChanged:e=>{n=e,h()}}),u=o.divV([],{style:{maxHeight:"380px",overflowY:"auto",paddingRight:"8px"}});function h(){u.innerHTML="";const t=(0,a.Ln)(n);if(0!==t.length)for(const i of t){const t=l[i.category]??i.category,r=i.severity?` [${c[i.severity]??i.severity}]`:"",d=i.start&&i.end?` (${i.start}-${i.end})`:"",m=i.sourceScheme?` ${i.sourceScheme}`:"",p=o.iconFA("trash",()=>{const t=(0,a.Ln)(n).filter(e=>e.id!==i.id);(0,a.fh)(n,t),e.fireValuesChanged(),h()},"Delete");p.style.cursor="pointer",p.style.color="#999",p.style.marginLeft="8px";const g=i.color??"#ccc";let f=g;const y=o.div([],{style:{width:"12px",height:"12px",borderRadius:"2px",backgroundColor:f,display:"inline-block",marginRight:"6px",flexShrink:"0",cursor:"pointer"}});o.colorPicker(s.Color.fromHtml(i.color??"#ccc"),e=>{f=s.Color.toHtml(e)},y,()=>{const t=(0,a.Ln)(n).map(e=>e.id===i.id?{...e,color:f}:e);(0,a.fh)(n,t),e.fireValuesChanged(),h()},()=>{f=g,y.style.backgroundColor=f});const b=o.divH([y,o.divText(`${i.name}${d}${m}${r}`,{style:{flex:"1",fontSize:"12px",padding:"4px"}}),o.divText(t,{style:{color:"#888",fontSize:"11px",marginRight:"8px"}}),p],{style:{alignItems:"center",padding:"4px 0",borderBottom:"1px solid #eee"}});u.append(b)}else u.append(o.divText("No annotations on this column.",{style:{color:"#888",padding:"8px"}}))}h();const d=o.button("Clear All",()=>{(0,a.OW)(e,n),e.fireValuesChanged(),h(),i.shell.info("All annotations cleared")});o.dialog({title:"Manage Annotations"}).add(o.inputs([r])).add(o.h3("Annotations")).add(u).add(o.divH([d],{style:{marginTop:"8px"}})).onOK(()=>{}).show()}},3736(e,t,n){"use strict";n.d(t,{JG:()=>u,Ln:()=>s,Lz:()=>l,OW:()=>m,VT:()=>a,bq:()=>p,fh:()=>r,wi:()=>h,z5:()=>d});var i=n(2003),o=n(4517);function s(e){const t=e.getTag(i.gp.annotations);if(t)try{return JSON.parse(t)}catch{}const n=e.getTag(i.gp.regions);if(n)try{return JSON.parse(n).map((e,t)=>({id:`legacy-region-${t}`,name:e.name,description:e.description,start:e.start,end:e.end,visualType:o.ao.Region,category:o.eI.Structure,autoGenerated:!0}))}catch{}return[]}function r(e,t){e.setTag(i.gp.annotations,JSON.stringify(t));const n=t.filter(e=>e.category===o.eI.Structure);if(n.length>0){const t=n.filter(e=>null!=e.start&&null!=e.end).map(e=>({name:e.name,description:e.description??"",start:e.start,end:e.end}));e.setTag(i.gp.regions,JSON.stringify(t))}}function a(e){return`~${e}_annotations`}function l(e,t){const n=a(t.name);let o=e.columns.byName(n);return o||(o=e.columns.addNewString(n),t.setTag(i.gp.annotationColumnName,n)),o}const c=new WeakMap;function u(e,t){const n=c.get(e);if(n&&n.version===e.version&&void 0!==n.data[t])return n.data[t];const i=e.get(t);if(!i)return null;try{return JSON.parse(i)}catch{return null}}function h(e){const t=c.get(e);if(t&&t.version===e.version)return t.data;const n=new Array(e.length);for(let t=0;t<e.length;t++){const i=e.get(t);if(i)try{n[t]=JSON.parse(i)}catch{n[t]=null}else n[t]=null}return c.set(e,{version:e.version,data:n}),n}function d(e,t,n){e.set(t,n.length>0?JSON.stringify(n):"")}function m(e,t){t.setTag(i.gp.annotations,"");const n=a(t.name);e.columns.byName(n)&&e.columns.remove(n),t.setTag(i.gp.regions,"")}function p(e,t,n,i){let o=e;return n&&(o=o.filter(e=>null==e.endPositionIndex)),i&&(o=o.filter(e=>null!=e.endPositionIndex)),[...o,...t]}},9422(e,t,n){"use strict";n.d(t,{showLiabilityScannerDialog:()=>d});var i=n(4328),o=n(7389),s=n(6082),r=n(3328),a=n(4517),l=n(3736);const c=[{id:"deamid-ng",name:"Deamidation (NG)",pattern:/NG/g,length:2,severity:a.Hq.High,ruleCategory:"deamidation",color:a.D5.liability.deamidation,enabled:!0},{id:"deamid-ns",name:"Deamidation (NS)",pattern:/NS/g,length:2,severity:a.Hq.Medium,ruleCategory:"deamidation",color:a.D5.liability.deamidation,enabled:!0},{id:"deamid-na",name:"Deamidation (NA)",pattern:/NA/g,length:2,severity:a.Hq.Low,ruleCategory:"deamidation",color:a.D5.liability.deamidation,enabled:!0},{id:"deamid-nd",name:"Deamidation (ND)",pattern:/ND/g,length:2,severity:a.Hq.Low,ruleCategory:"deamidation",color:a.D5.liability.deamidation,enabled:!0},{id:"deamid-nt",name:"Deamidation (NT)",pattern:/NT/g,length:2,severity:a.Hq.Low,ruleCategory:"deamidation",color:a.D5.liability.deamidation,enabled:!0},{id:"isom-dg",name:"Isomerization (DG)",pattern:/DG/g,length:2,severity:a.Hq.High,ruleCategory:"isomerization",color:a.D5.liability.isomerization,enabled:!0},{id:"isom-ds",name:"Isomerization (DS)",pattern:/DS/g,length:2,severity:a.Hq.Medium,ruleCategory:"isomerization",color:a.D5.liability.isomerization,enabled:!0},{id:"oxid-m",name:"Oxidation (Met)",pattern:/M/g,length:1,severity:a.Hq.Medium,ruleCategory:"oxidation",color:a.D5.liability.oxidation,enabled:!0},{id:"oxid-w",name:"Oxidation (Trp)",pattern:/W/g,length:1,severity:a.Hq.Low,ruleCategory:"oxidation",color:a.D5.liability.oxidation,enabled:!0},{id:"glyco-nxst",name:"N-glycosylation",pattern:/N[^P][ST]/g,length:3,severity:a.Hq.High,ruleCategory:"glycosylation",color:a.D5.liability.glycosylation,enabled:!0},{id:"free-cys",name:"Free Cysteine",pattern:/C/g,length:1,severity:a.Hq.Info,ruleCategory:"freeCysteine",color:a.D5.liability.freeCysteine,enabled:!1}];function u(e,t){const n=e.getSplitted(t),i=new Array(n.length);for(let e=0;e<n.length;e++)i[e]=n.getOriginal(e);return i.join("")}const h={[a.Hq.High]:"High",[a.Hq.Medium]:"Medium",[a.Hq.Low]:"Low",[a.Hq.Info]:"Info"};function d(){const e=i.shell.tv?.dataFrame;if(!e)return void i.shell.warning("No table open");const t=e.columns.bySemTypeAll(s.SEMTYPE.MACROMOLECULE);if(0===t.length)return void i.shell.warning("No macromolecule columns found");const n=c.map(e=>({...e,pattern:new RegExp(e.pattern.source,"g")})),d=o.input.table("Table",{value:e}),m=o.input.column("Sequence",{table:e,value:t[0],filter:e=>e.semType===s.SEMTYPE.MACROMOLECULE}),p=[],g=o.divV([]);for(const e of n){const t=o.input.bool(e.name,{value:e.enabled,tooltipText:`Severity: ${h[e.severity]??e.severity}`});p.push({rule:e,input:t}),g.append(t.root)}const f=o.input.bool("Highlight in cell renderer",{value:!0}),y=o.input.bool("Create annotation column",{value:!0}),b=o.input.bool("Create summary count column",{value:!1}),w=o.dialog({title:"Scan Sequence Liabilities"}).add(o.inputs([d,m])).add(o.h3("Rules")).add(g).add(o.h3("Output")).add(o.inputs([f,y,b])).onOK(()=>{try{const t=m.value,o=r._package.seqHelper.getSeqHandler(t);for(const{rule:e,input:t}of p)e.enabled=t.value;const s=function(e,t,n){const i=n.filter(e=>e.enabled),o=t.posList,s=new Map,r=new Array(e.length);let l=0;for(let n=0;n<e.length;n++){const e=u(t,n),a=[];for(const t of i){let n;for(t.pattern.lastIndex=0;null!==(n=t.pattern.exec(e));)a.push({annotationId:t.id,positionIndex:n.index,positionName:n.index<o.length?o[n.index]:void 0,matchedMonomers:n[0]}),s.set(t.id,(s.get(t.id)??0)+1),l++}r[n]=a}return{annotations:i.filter(e=>s.has(e.id)).map(e=>({id:e.id,name:e.name,description:`${e.ruleCategory} liability pattern (${s.get(e.id)} hits)`,start:null,end:null,visualType:1===e.length?a.ao.Point:a.ao.Motif,category:a.eI.Liability,color:e.color,severity:e.severity,motifPattern:e.pattern.source,autoGenerated:!0})),rowData:r,totalHits:l}}(t,o,n);(y.value||f.value)&&function(e,t,n){const i=(0,l.Ln)(t).filter(e=>e.category!==a.eI.Liability);(0,l.fh)(t,[...i,...n.annotations]);const o=(0,l.Lz)(e,t);for(let e=0;e<n.rowData.length;e++){const t=(0,l.JG)(o,e)??[];(0,l.z5)(o,e,(0,l.bq)(t,n.rowData[e],!1,!0))}}(e,t,s),b.value&&function(e,t,n){const i=`${t.name}_liability_count`,o=n.rowData.map(e=>e.length),s=e.columns.addNewInt(i);for(let e=0;e<o.length;e++)s.set(e,o[e])}(e,t,s),i.shell.info(`Liability scan: ${s.totalHits} hits found across ${s.annotations.length} rules`),e.fireValuesChanged()}catch(e){i.shell.error(`Liability scan failed: ${e.message??e}`),console.error(e)}});w.show()}},6839(e,t,n){"use strict";n.d(t,{showNumberingSchemeDialog:()=>u});var i=n(4328),o=n(7389),s=n(6082),r=n(2003),a=n(4517),l=n(3736);function c(e){const t=e.func.inputs.find(e=>"scheme"===e.name.toLowerCase()),n=t?.choices??[];return n.length>0?n.slice():["imgt"]}function u(){const e=i.shell.tv?.dataFrame;if(!e)return void i.shell.warning("No table open");const t=e.columns.bySemTypeAll(s.SEMTYPE.MACROMOLECULE);if(0===t.length)return void i.shell.warning("No macromolecule columns found");const n=function(){const e=[],t=s.Func.find({meta:{role:"antibodyNumbering"}});if(0===t.length)throw i.shell.error("No antibody numbering engines found. Make sure the Bio package is up to date."),new Error("No antibody numbering engines found.");for(const n of t){const t=n.package?.name??"";e.push({label:n.friendlyName||n.name,key:t?`${t}:${n.name}`:n.name,func:n})}return e}(),u=n.map(e=>e.label),m=o.input.table("Table",{value:e}),p=o.input.column("Sequence",{table:e,value:t[0],filter:e=>e.semType===s.SEMTYPE.MACROMOLECULE}),g=o.input.choice("Engine",{value:u[0],items:u}),f=c(n[0]),y=o.input.choice("Scheme",{value:f[0],items:f});g.onChanged.subscribe(()=>{const e=n.find(e=>e.label===g.value);if(!e)return;const t=c(e),i=y.value;y.items=t,y.value=t.includes(i??"")?i:t[0]});const b=o.dialog({title:"Apply Antibody Numbering"}).add(o.inputs([m,p,g,y])).onOK(async()=>{const t=p.value,o=y.value,c=g.value,u=n.find(e=>e.label===c)??n[0],m=s.TaskBarProgressIndicator.create(`Applying ${o} numbering...`);try{const n=await u.func.apply({df:e,seqCol:t,scheme:o});!function(e,t,n,o,c,u){if(!n||0===n.rowCount)return void i.shell.warning("No numbering results returned");const m=n.getCol("position_names"),p=n.getCol("chain_type"),g=n.getCol("annotations_json"),f=n.col("numbering_map");if(f)for(let e=0;e<n.rowCount;e++){const n=f.get(e);if(n)try{const i=JSON.parse(n),o=h(t.get(e)??""),s={};for(const[e,t]of Object.entries(i))t<o.length&&(s[e]=o[t]);f.set(e,JSON.stringify(s))}catch{}}let y=-1,b=-1;for(let e=0;e<n.rowCount;e++){const t=m.get(e);if(!t||0===t.length)continue;const n=g.get(e);let i=0;if(n)try{i=JSON.parse(n).length}catch{}i>b&&(b=i,y=e)}const w=y>=0?p.get(y)??"":"",v=y>=0?g.get(y)??"[]":"[]";if(y<0)return void i.shell.warning(`${u} could not number the sequences. Check that they are valid antibody variable region sequences.`);t.setTag(r.gp.numberingScheme,o);try{const e=JSON.parse(v),n=(0,l.Ln)(t).filter(e=>e.category!==a.eI.Structure);(0,l.fh)(t,[...n,...e])}catch(e){console.warn("Failed to set annotation definitions on original column:",e)}if(f)try{const i=(0,l.Lz)(e,t);for(let e=0;e<n.rowCount;e++){const t=f.get(e),n=g.get(e);if(!t||!n)continue;const o=JSON.parse(t),s=JSON.parse(n),r=[];for(const e of s){if(null==e.start||null==e.end)continue;const t=o[e.start],n=o[e.end];null!=t&&null!=n&&r.push({annotationId:e.id,positionIndex:t,endPositionIndex:n,positionName:e.start,matchedMonomers:""})}const a=(0,l.JG)(i,e)??[];(0,l.z5)(i,e,(0,l.bq)(a,r,!0,!1))}}catch(e){console.warn("Failed to store per-row region data on original column:",e)}const C=function(e,t,n){const i=n.col("numbering_map");if(!i)return null;const o=new Set,a=[],l=[],c=[];for(let e=0;e<n.rowCount;e++){const n=i.get(e),s=t.get(e)??"";if(n)try{const e=JSON.parse(n);a.push(e);for(const t of Object.keys(e))o.add(t);const t=Object.values(e),i=Math.min(...t),r=Math.max(...t);l.push(i),c.push(Math.max(0,s.length-r-1))}catch{a.push(null),l.push(0),c.push(0)}else a.push(null),l.push(0),c.push(0)}if(0===o.size)return null;const u=Math.max(0,...l),h=Math.max(0,...c),m=Array.from(o).slice().sort((e,t)=>{const[n,i]=d(e),[o,s]=d(t);return n!==o?n-o:i.localeCompare(s)}),p=[];for(let e=u;e>0;e--)p.push(`N-${e}`);const g=[];for(let e=1;e<=h;e++)g.push(`C+${e}`);const f=[...p,...m,...g],y=f.length,b=u,w=new Map;for(let e=0;e<m.length;e++)w.set(m[e],b+e);const v=e.columns.getUnusedName(`${t.name} (aligned)`),C=s.Column.fromType(s.COLUMN_TYPE.STRING,v,e.rowCount);for(let n=0;n<e.rowCount;n++){const e=n<a.length?a[n]:null,i=t.get(n)??"";if(!e){C.set(n,"-".repeat(y));continue}const o=new Array(y).fill("-");for(const[t,n]of Object.entries(e)){const e=w.get(t);null!=e&&n<i.length&&(o[e]=i[n])}const s=l[n],r=Object.values(e),u=Math.min(...r);for(let e=0;e<s;e++)o[b-s+e]=i[u-s+e];const h=c[n],d=Math.max(...r),p=b+m.length;for(let e=0;e<h;e++)o[p+e]=i[d+1+e];C.set(n,o.join(""))}return C.semType=s.SEMTYPE.MACROMOLECULE,C.setTag(r.gp.aligned,"SEQ.MSA"),C.setTag(r.gp.alphabet,r.YI.PT),C.meta.units=r.Hi.FASTA,C.setTag(s.Tags.CellRenderer,"sequence"),C.setTag(r.gp.positionNames,f.join(", ")),{alignedCol:C,unifiedPositions:f,preOffset:b}}(e,t,n);if(C&&(e.columns.insert(C.alignedCol,e.columns.toList().indexOf(t)+1),i.shell.tv?.dataFrame===e&&i.shell.tv.grid.scrollToCell(t,0),C.alignedCol.setTag(r.gp.numberingScheme,o),c))try{const e=JSON.parse(v),t=(0,l.Ln)(C.alignedCol).filter(e=>e.category!==a.eI.Structure);(0,l.fh)(C.alignedCol,[...t,...e])}catch(e){console.warn("Failed to set column-level annotations on aligned column:",e)}e.fireValuesChanged(),i.shell.info(`Numbering applied: ${o}, chain type: ${w}`)}(e,t,n,o,!0,u.label)}catch(e){i.shell.error(`Numbering failed: ${e.message??e}`),console.error(e)}finally{m.close()}});b.show()}function h(e){const t=[];for(let n=0;n<e.length;n++)"-"!==e[n]&&"."!==e[n]&&t.push(n);return t}function d(e){const t=e.match(/^(\d+)([A-Z]?)$/);return t?[parseInt(t[1],10),t[2]]:[1/0,e]}},417(e,t,n){"use strict";async function i(e,t,i,o){const s=new Worker(new URL(n.p+n.u(909),n.b));try{const n=await function(e,t){return new Promise((n,i)=>{const o=new MessageChannel;o.port1.onmessage=({data:e})=>{o.port1.close(),n(e)},o.port1.onmessageerror=e=>{o.port1.close(),i(e)},e.postMessage({req:t},[o.port2])})}(s,{op:"number",sequences:e,scheme:t,chains:i,minConfidence:o});if(!n.ok)throw new Error(n.error);return n.rows??[]}finally{s.terminate()}}n.d(t,{m:()=>i})},9036(e,t,n){"use strict";n.d(t,{C:()=>m});var i,o,s=n(6082);!function(e){e.IMGT="IMGT",e.Kabat="Kabat",e.Chothia="Chothia",e.AHo="AHo"}(i||(i={})),function(e){e.Heavy="Heavy",e.Light_Kappa="Light_Kappa",e.Light_Lambda="Light_Lambda"}(o||(o={}));const r={[o.Heavy]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"26",chainType:o.Heavy},{name:"CDR1",type:"CDR",startPosition:"27",endPosition:"38",chainType:o.Heavy},{name:"FR2",type:"FR",startPosition:"39",endPosition:"55",chainType:o.Heavy},{name:"CDR2",type:"CDR",startPosition:"56",endPosition:"65",chainType:o.Heavy},{name:"FR3",type:"FR",startPosition:"66",endPosition:"104",chainType:o.Heavy},{name:"CDR3",type:"CDR",startPosition:"105",endPosition:"117",chainType:o.Heavy},{name:"FR4",type:"FR",startPosition:"118",endPosition:"128",chainType:o.Heavy}],[o.Light_Kappa]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"26",chainType:o.Light_Kappa},{name:"CDR1",type:"CDR",startPosition:"27",endPosition:"38",chainType:o.Light_Kappa},{name:"FR2",type:"FR",startPosition:"39",endPosition:"55",chainType:o.Light_Kappa},{name:"CDR2",type:"CDR",startPosition:"56",endPosition:"65",chainType:o.Light_Kappa},{name:"FR3",type:"FR",startPosition:"66",endPosition:"104",chainType:o.Light_Kappa},{name:"CDR3",type:"CDR",startPosition:"105",endPosition:"117",chainType:o.Light_Kappa},{name:"FR4",type:"FR",startPosition:"118",endPosition:"127",chainType:o.Light_Kappa}],[o.Light_Lambda]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"26",chainType:o.Light_Lambda},{name:"CDR1",type:"CDR",startPosition:"27",endPosition:"38",chainType:o.Light_Lambda},{name:"FR2",type:"FR",startPosition:"39",endPosition:"55",chainType:o.Light_Lambda},{name:"CDR2",type:"CDR",startPosition:"56",endPosition:"65",chainType:o.Light_Lambda},{name:"FR3",type:"FR",startPosition:"66",endPosition:"104",chainType:o.Light_Lambda},{name:"CDR3",type:"CDR",startPosition:"105",endPosition:"117",chainType:o.Light_Lambda},{name:"FR4",type:"FR",startPosition:"118",endPosition:"127",chainType:o.Light_Lambda}]},a={[o.Heavy]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"30",chainType:o.Heavy},{name:"CDR1",type:"CDR",startPosition:"31",endPosition:"35",chainType:o.Heavy},{name:"FR2",type:"FR",startPosition:"36",endPosition:"49",chainType:o.Heavy},{name:"CDR2",type:"CDR",startPosition:"50",endPosition:"65",chainType:o.Heavy},{name:"FR3",type:"FR",startPosition:"66",endPosition:"94",chainType:o.Heavy},{name:"CDR3",type:"CDR",startPosition:"95",endPosition:"102",chainType:o.Heavy},{name:"FR4",type:"FR",startPosition:"103",endPosition:"113",chainType:o.Heavy}],[o.Light_Kappa]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"23",chainType:o.Light_Kappa},{name:"CDR1",type:"CDR",startPosition:"24",endPosition:"34",chainType:o.Light_Kappa},{name:"FR2",type:"FR",startPosition:"35",endPosition:"49",chainType:o.Light_Kappa},{name:"CDR2",type:"CDR",startPosition:"50",endPosition:"56",chainType:o.Light_Kappa},{name:"FR3",type:"FR",startPosition:"57",endPosition:"88",chainType:o.Light_Kappa},{name:"CDR3",type:"CDR",startPosition:"89",endPosition:"97",chainType:o.Light_Kappa},{name:"FR4",type:"FR",startPosition:"98",endPosition:"107",chainType:o.Light_Kappa}],[o.Light_Lambda]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"23",chainType:o.Light_Lambda},{name:"CDR1",type:"CDR",startPosition:"24",endPosition:"34",chainType:o.Light_Lambda},{name:"FR2",type:"FR",startPosition:"35",endPosition:"49",chainType:o.Light_Lambda},{name:"CDR2",type:"CDR",startPosition:"50",endPosition:"56",chainType:o.Light_Lambda},{name:"FR3",type:"FR",startPosition:"57",endPosition:"88",chainType:o.Light_Lambda},{name:"CDR3",type:"CDR",startPosition:"89",endPosition:"97",chainType:o.Light_Lambda},{name:"FR4",type:"FR",startPosition:"98",endPosition:"107",chainType:o.Light_Lambda}]},l={[o.Heavy]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"25",chainType:o.Heavy},{name:"CDR1",type:"CDR",startPosition:"26",endPosition:"32",chainType:o.Heavy},{name:"FR2",type:"FR",startPosition:"33",endPosition:"51",chainType:o.Heavy},{name:"CDR2",type:"CDR",startPosition:"52",endPosition:"56",chainType:o.Heavy},{name:"FR3",type:"FR",startPosition:"57",endPosition:"94",chainType:o.Heavy},{name:"CDR3",type:"CDR",startPosition:"95",endPosition:"102",chainType:o.Heavy},{name:"FR4",type:"FR",startPosition:"103",endPosition:"113",chainType:o.Heavy}],[o.Light_Kappa]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"25",chainType:o.Light_Kappa},{name:"CDR1",type:"CDR",startPosition:"26",endPosition:"32",chainType:o.Light_Kappa},{name:"FR2",type:"FR",startPosition:"33",endPosition:"49",chainType:o.Light_Kappa},{name:"CDR2",type:"CDR",startPosition:"50",endPosition:"52",chainType:o.Light_Kappa},{name:"FR3",type:"FR",startPosition:"53",endPosition:"90",chainType:o.Light_Kappa},{name:"CDR3",type:"CDR",startPosition:"91",endPosition:"96",chainType:o.Light_Kappa},{name:"FR4",type:"FR",startPosition:"97",endPosition:"107",chainType:o.Light_Kappa}],[o.Light_Lambda]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"25",chainType:o.Light_Lambda},{name:"CDR1",type:"CDR",startPosition:"26",endPosition:"32",chainType:o.Light_Lambda},{name:"FR2",type:"FR",startPosition:"33",endPosition:"49",chainType:o.Light_Lambda},{name:"CDR2",type:"CDR",startPosition:"50",endPosition:"52",chainType:o.Light_Lambda},{name:"FR3",type:"FR",startPosition:"53",endPosition:"90",chainType:o.Light_Lambda},{name:"CDR3",type:"CDR",startPosition:"91",endPosition:"96",chainType:o.Light_Lambda},{name:"FR4",type:"FR",startPosition:"97",endPosition:"107",chainType:o.Light_Lambda}]},c={[o.Heavy]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"24",chainType:o.Heavy},{name:"CDR1",type:"CDR",startPosition:"25",endPosition:"40",chainType:o.Heavy},{name:"FR2",type:"FR",startPosition:"41",endPosition:"55",chainType:o.Heavy},{name:"CDR2",type:"CDR",startPosition:"56",endPosition:"78",chainType:o.Heavy},{name:"FR3",type:"FR",startPosition:"79",endPosition:"108",chainType:o.Heavy},{name:"CDR3",type:"CDR",startPosition:"109",endPosition:"138",chainType:o.Heavy},{name:"FR4",type:"FR",startPosition:"139",endPosition:"149",chainType:o.Heavy}],[o.Light_Kappa]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"24",chainType:o.Light_Kappa},{name:"CDR1",type:"CDR",startPosition:"25",endPosition:"40",chainType:o.Light_Kappa},{name:"FR2",type:"FR",startPosition:"41",endPosition:"55",chainType:o.Light_Kappa},{name:"CDR2",type:"CDR",startPosition:"56",endPosition:"78",chainType:o.Light_Kappa},{name:"FR3",type:"FR",startPosition:"79",endPosition:"108",chainType:o.Light_Kappa},{name:"CDR3",type:"CDR",startPosition:"109",endPosition:"138",chainType:o.Light_Kappa},{name:"FR4",type:"FR",startPosition:"139",endPosition:"149",chainType:o.Light_Kappa}],[o.Light_Lambda]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"24",chainType:o.Light_Lambda},{name:"CDR1",type:"CDR",startPosition:"25",endPosition:"40",chainType:o.Light_Lambda},{name:"FR2",type:"FR",startPosition:"41",endPosition:"55",chainType:o.Light_Lambda},{name:"CDR2",type:"CDR",startPosition:"56",endPosition:"78",chainType:o.Light_Lambda},{name:"FR3",type:"FR",startPosition:"79",endPosition:"108",chainType:o.Light_Lambda},{name:"CDR3",type:"CDR",startPosition:"109",endPosition:"138",chainType:o.Light_Lambda},{name:"FR4",type:"FR",startPosition:"139",endPosition:"149",chainType:o.Light_Lambda}]},u={[i.IMGT]:r,[i.Kabat]:a,[i.Chothia]:l,[i.AHo]:c};var h=n(417);function d(e,t,n){if(!t)return[];const s="kabat"===(e||"").toLowerCase()?i.Kabat:i.IMGT,r=u[s],a=function(e,t){return"Light"===e?"L"===t?o.Light_Lambda:o.Light_Kappa:o.Heavy}(t,n),l=r?.[a];if(!l)return[];const c=e.toLowerCase();return l.map(n=>({id:`${c}-${t}-${n.name}`.toLowerCase(),name:n.name,description:`${n.name} (${e.toUpperCase()} ${n.startPosition}-${n.endPosition})`,start:n.startPosition,end:n.endPosition,visualType:"region",category:"structure",sourceScheme:e.toUpperCase(),autoGenerated:!0}))}async function m(e,t){const n=e.length,i=new Array(n);for(let t=0;t<n;t++)i[t]=e.get(t)??"";const o=function(e){return"kabat"===(e||"").toLowerCase()?"kabat":"imgt"}(t),r=await(0,h.m)(i,o),a=s.Column.fromType(s.COLUMN_TYPE.STRING,"position_names",n),l=s.Column.fromType(s.COLUMN_TYPE.STRING,"chain_type",n),c=s.Column.fromType(s.COLUMN_TYPE.STRING,"annotations_json",n),u=s.Column.fromType(s.COLUMN_TYPE.STRING,"numbering_detail",n),m=s.Column.fromType(s.COLUMN_TYPE.STRING,"numbering_map",n);for(let e=0;e<n;e++){const n=r[e];n&&!n.error&&n.positionNames?(a.set(e,n.positionNames),l.set(e,n.chainType),c.set(e,JSON.stringify(d(t,n.chainType,n.chainCode))),u.set(e,JSON.stringify(n.numberingDetail)),m.set(e,JSON.stringify(n.numberingMap))):(a.set(e,""),l.set(e,""),c.set(e,"[]"),u.set(e,""),m.set(e,""))}return s.DataFrame.fromColumns([a,l,c,u,m])}},966(e,t,n){"use strict";n.d(t,{V:()=>r,l:()=>a});var i=n(4328),o=n(6082),s=n(3328);function r(e,t,n=[],o=[],r=!0){const l=s._package.seqHelper,[c,u]=a(e,t,l,n,o);return r&&!c&&i.shell.warning(u),c}function a(e,t,n,s=[],r=[]){let a=!0,l="";if(e.semType!==o.SEMTYPE.MACROMOLECULE)i.shell.warning(t+" analysis is allowed for Macromolecules semantic type"),a=!1;else{const i=n.getSeqHandler(e),o=i.notation;if(s.length>0&&!s.some(e=>o.toUpperCase()==e.toUpperCase()))l=`${t} + ' analysis is allowed for Macromolecules with notation ${0==s.length?"any notation":`notation${s.length>1?"s":""} ${s.map(e=>`"${e}"`).join(", ")} `}.`,a=!1;else if(!i.isHelm()){const e=i.alphabet;r.length>0&&!r.some(t=>e.toUpperCase()==t.toUpperCase())&&(l=`${t} + ' analysis is allowed for Macromolecules with alphabet ${0==r.length?"any alphabet":`alphabet${r.length>1?"s":""} ${r.map(e=>`"${e}"`).join(", ")}.`}.`,a=!1)}}return[a,l]}},4139(e,t,n){"use strict";var i,o,s;n.d(t,{J:()=>l,W_:()=>u,b9:()=>c,gN:()=>r,uF:()=>s}),function(e){e.SPLIT_COL="~split",e.ACTIVITY="~activity",e.ACTIVITY_SCALED="activity_scaled",e.ALIGNED_SEQUENCE="~aligned_sequence",e.AMINO_ACID_RESIDUE="AAR",e.POSITION="Pos",e.P_VALUE="pValue",e.MEAN_DIFFERENCE="Mean difference"}(i||(i={})),function(e){e.AAR="AAR",e.POSITION="Pos",e.SELECTION="selection"}(o||(o={})),function(e){e.MONOMER="Monomer",e.MACROMOLECULE_DIFFERENCE="MacromoleculeDifference",e.ACTIVITY="activity",e.ACTIVITY_SCALED="activityScaled"}(s||(s={}));const r="MSA";var a,l;!function(e){e.CELL_CHANGING="isCellChanging"}(a||(a={})),function(e){e.SEPARATOR="."}(l||(l={}));const c="3.3.1",u="sequenceMSA"},5433(e,t,n){"use strict";n.d(t,{C:()=>d,r:()=>m});var i=n(6082),o=n(7389),s=n(4328),r=n(1757),a=n.n(r),l=n(2003),c=n(2738);let u=null,h=[];async function d(e,t){let n=e??s.shell.t.columns.bySemType("Macromolecule");if(!n)throw new Error("No column with Macromolecule semantic type found");let r=t.getSeqHandler(n),d=r.notation;const p=o.divText("Current notation: "+d,{style:{"text-align":"center","font-weight":"bold","font-size":"14px",padding:"5px"}}),g=[l.Hi.FASTA,l.Hi.SEPARATOR,l.Hi.HELM,l.Hi.BILN],f=await c.$G.getProviderConstructors(),y=o.input.column("Column",{table:s.shell.t,value:n,filter:e=>e.semType===i.SEMTYPE.MACROMOLECULE,nullable:!1,onValueChanged:e=>(n=e,r=t.getSeqHandler(n),d=r.notation,d===l.Hi.HELM&&(v.value="/"),p.textContent="Current notation: "+d,w=g.filter(e=>e!==d),d===l.Hi.CUSTOM&&(w=[l.Hi.HELM]),d===l.Hi.HELM&&f.forEach(e=>{e.implementsFromHelm&&w.unshift(e.notationName)}),A=o.input.choice("Convert to",{value:w[0],items:w,onValueChanged:C}),C(),u?.clear(),void u?.add(o.div([p,y.root,A.root,v.root])))}),b=["-",".","/"];let w=g.filter(e=>e!==d);d===l.Hi.CUSTOM&&(w=[l.Hi.HELM]),d===l.Hi.HELM&&f.forEach(e=>{e.implementsFromHelm&&w.unshift(e.notationName)});const v=o.input.choice("Separator",{value:b[0],items:b}),C=()=>{A.value!==l.Hi.SEPARATOR?a()(v.root).hide():a()(v.root).show()};let A=o.input.choice("Convert to",{value:w[0],items:w,onValueChanged:C});C(),A.onChanged.subscribe(()=>{C()}),null==u&&(u=o.dialog("Convert Sequence Notation").add(o.div([p,y.root,A.root,v.root])).onOK(async()=>{const e=A.value,i=e===l.Hi.SEPARATOR?v.value:void 0;let o;!g.includes(e)&&f.find(t=>t.notationName===e)&&(o=f.find(t=>t.notationName===e)),await m(n,t,e,i,o)}).show({x:350,y:100}),h.push(u.onClose.subscribe(e=>{h.forEach(e=>{e.unsubscribe()}),h=[],u=null})))}async function m(e,t,n,o,r){if(r){const t=e.dataFrame.columns.getUnusedName(`${r.notationName}(${e.name})`),n=i.Column.string(t,e.length);return n.init(t=>{const n=e.get(t);try{return r.convertFromHelm(n,{})}catch(e){return console.error(`Error converting sequence at row ${t}: ${e instanceof Error?e.message:e}`),""}}),n.semType=i.SEMTYPE.MACROMOLECULE,n.meta.units=l.Hi.CUSTOM,n.setTag("separator","-"),n.setTag("aligned","SEQ"),n.setTag("alphabet","UN"),n.setTag(".alphabetIsMultichar","true"),e.dataFrame.columns.add(n),await s.data.detectSemanticTypes(e.dataFrame),n}{const i=t.getSeqHandler(e).convert(n,o);e.dataFrame.columns.add(i);const r=await s.functions.call("Bio:detectMacromolecule",{col:i});return r&&(i.semType=r),await s.data.detectSemanticTypes(e.dataFrame),i}}},6956(e,t,n){"use strict";n.d(t,{m:()=>o,x:()=>i});const i="|",o="H"},2582(e,t,n){"use strict";n.d(t,{f:()=>a});var i=n(6956);class o{constructor(e){const t=e.split(i.x).filter(e=>e);t.forEach(e=>this.validateConnectionItem(e)),this.connectionItems=t}connectionItems;validateConnectionItem(e){const t="(PEPTIDE|RNA|CHEM|BLOB)",n=new RegExp(`${t}[0-9]+,${t}[0-9]+,[0-9]+:R[0-9]+-[0-9]+:R[0-9]+`,"g");if(!e.match(n))throw new Error(`Cannot parse connection item from ${e}`)}getConnectionData(){const e=[];return this.connectionItems.forEach(t=>{const n=[],i=t.split(",");i[2].split("-").forEach((e,t)=>{const o=i[t],s=e.split(":"),r={monomerIdx:parseInt(s[0])-1,rGroupId:parseInt(s[1].slice(1))};n.push({polymerId:o,bond:r})}),e.push(n)}),e}}var s=n(8438);class r{simplePolymer;isNucleotideSequence=!1;constructor(e){this.simplePolymer=e,this.polymerType=this.getPolymerType(),this.isNucleotideSequence="RNA"===this.polymerType,this.idx=this.getIdx();const{monomers:t,monomerTypes:n}=this.getMonomerSymbolsAndTypes();this.monomers=t,this.monomerTypes=n}polymerType;monomers;idx;monomerTypes;get id(){return this.polymerType+this.idx.toString()}getPolymerType(){const e=new RegExp("(PEPTIDE|RNA|CHEM|BLOB)[0-9]+{"),t=this.simplePolymer.match(e);if(!t)throw new Error(`Unsupported polymer type in ${this.simplePolymer}`);return t[1]}getIdx(){const e=new RegExp(`${this.polymerType}([0-9]+){`),t=this.simplePolymer.match(e);if(!t)throw new Error(`Cannot parse simple polymer id from ${this.simplePolymer}`);return parseInt(t[1])}getMonomerSymbolsAndTypes(){const e=new RegExp(`${this.polymerType}${this.idx}{|}`,"g"),t=this.simplePolymer.replace(e,"").split("."),n=[],i=[];return t.forEach(e=>{if(this.isNucleotideSequence){const t=e.split(/\(|\)/).filter(e=>!!e).map(e=>(0,s.D)(e));n.push(...t),t.forEach((e,t)=>i.push(t%3==1?"Branch":"Backbone"))}else n.push((0,s.D)(e)),i.push("Backbone")}),{monomers:n,monomerTypes:i}}getBondData(){const e=[],t=this.monomerTypes.map((e,t)=>{if("Backbone"===e)return t}).filter(e=>void 0!==e),n=this.monomerTypes.map((e,t)=>{if("Branch"===e)return t}).filter(e=>void 0!==e);for(let n=0;n<t.length-1;n++){const i=t[n],o=t[n+1];e.push([{monomerIdx:i,rGroupId:2},{monomerIdx:o,rGroupId:1}])}for(let t=0;t<n.length;t++){const i=n[t],o=i-1;e.push([{monomerIdx:o,rGroupId:3},{monomerIdx:i,rGroupId:1}])}return e}}class a{helmString;constructor(e){this.helmString=e;const t=e.indexOf("}$"),n=e.substring(0,t+1),i=e.indexOf("$",t+2),s=e.substring(t+2,i),a=n.split("}|");for(let e=0;e<a.length-1;e++)a[e]=a[e]+"}";this.simplePolymers=a.map(e=>new r(e)),this.connectionList=new o(s),this.bondData=this.getBondData(),this.bondedRGroupsMap=this.getBondedRGroupsMap()}bondData;simplePolymers;connectionList;bondedRGroupsMap;getBondedRGroupsMap(){const e=this.simplePolymers.map(e=>e.monomers.length).reduce((e,t)=>e+t,0),t=Array.from({length:e},()=>[]);return this.bondData.forEach(e=>{e.forEach(e=>{const n=e.monomerIdx,i=e.rGroupId;t[n].push(i)})}),t}toString(){return this.helmString}getPolymerTypeByMonomerIdx(e){return this.getSimplePolymerByMonomerIdx(e).polymerType}getSimplePolymerByMonomerIdx(e){const t=this.getMonomerIdxShifts(),n=Object.values(t).sort((e,t)=>t-e).find(t=>e>=t);if(null==n)throw new Error(`Cannot find simple polymer for monomer ${e}`);const i=Object.keys(t).find(e=>t[e]===n);return this.simplePolymers.find(e=>e.id===i)}shiftBondMonomerIds(e,t){t.forEach(t=>{t.forEach(t=>{t.monomerIdx+=e})})}getMonomerIdxShifts(){const e={};let t=0;return this.simplePolymers.forEach(n=>{e[n.id]=t,t+=n.monomers.length}),e}getBondData(){const e=this.getMonomerIdxShifts(),t=[];return this.simplePolymers.forEach(n=>{const i=n.getBondData(),o=e[n.id];this.shiftBondMonomerIds(o,i),t.push(...i)}),this.connectionList.getConnectionData().forEach(n=>{const i=[];n.forEach(t=>{const n=e[t.polymerId],o=t.bond;o.monomerIdx+=n,i.push(o)}),t.push(i)}),t}}},8604(e,t,n){"use strict";n.d(t,{G:()=>i,V:()=>o});const i={explicit:["HELMCoreLibrary.json","polytool-lib.json"],exclude:[],duplicateMonomerPreferences:{}},o={PEPTIDE:334,RNA:390,CHEM:0}},1619(e,t,n){"use strict";n.d(t,{D:()=>x});var i=n(4328),o=n(6082),s=n(7389),r=n(2003),a=n(4025),l=n(608),c=n(966),u=n(4139),h=n(3328),d=n(5072),m=n.n(d),p=n(7825),g=n.n(p),f=n(7659),y=n.n(f),b=n(5056),w=n.n(b),v=n(540),C=n.n(v),A=n(1113),T=n.n(A),E=n(6369),S={};S.styleTagTransform=T(),S.setAttributes=w(),S.insert=y().bind(null,"head"),S.domAPI=g(),S.insertStyleElement=C(),m()(E.A,S),E.A&&E.A.locals&&E.A.locals;class M{mode="kalign";currentFunc=null;currentFuncCall=null}async function x(e,t){return new Promise(async(n,d)=>{try{const m=e.col?.dataFrame??i.shell.t;if(!m)return void d(new l.Ap(s.divText("MSA requires a dataset with a macromolecule column.")));const p=e.col??m.columns.bySemType(o.SEMTYPE.MACROMOLECULE);if(!p)return void d(new l.Ap(s.divText("MSA requires a dataset with a macromolecule column.")));const g=new M;let f=p;const y=s.input.column("Sequence",{table:m,value:p,onValueChanged:async e=>{if(!e||e.semType!==o.SEMTYPE.MACROMOLECULE)return q.disabled=!0,await o.delay(0),void(y.value=f);f=e,q.disabled=!1,await F(e)},filter:e=>e.semType===o.SEMTYPE.MACROMOLECULE});y.setTooltip("Sequences column to use for alignment");const b=s.input.column("Clusters",{table:m,value:e.clustersCol});b.nullable=!0;const w=s.input.bool("Selected Rows Only",{value:!1}),v=s.input.float("Gap open",{value:e?.kalign?.gapOpen});v.setTooltip("Gap opening penalty at group-to-group alignment");const C=s.input.float("Gap extend",{value:e?.kalign?.gapExtend});C.setTooltip("Gap extension penalty to skip the alignment");const A=s.input.float("Terminal gap",{value:e?.kalign?.terminalGap});A.setTooltip("Penalty for opening a gap at the beginning or end of the sequence");const T=s.p(`Kalign version: ${u.b9}`,"kalign-version"),E=s.inputs([v,C,A]);E.hidden=!0;const S=s.button("Alignment parameters",()=>{E.hidden=!E.hidden,[v,C,A].forEach(e=>{e.root.style.removeProperty("max-width"),e.captionLabel.style.removeProperty("max-width")})},"Adjust alignment parameters such as penalties for opening and extending gaps");S.classList.add("msa-params-button"),S.prepend(s.icons.settings(()=>null,"Settings"));const x=[E,S,T],L=o.Func.find({meta:{role:u.W_}});L.sort((e,t)=>{const n="true"===e.options.defaultAlignment?1:0;return("true"===t.options.defaultAlignment?1:0)-n});const I=s.input.choice("Engine",{value:L.length>0?L[0].friendlyName:"",items:L.map(e=>e.friendlyName)}),_=s.div("",{style:{fontSize:"12px",opacity:"0.7",marginBottom:"6px"}}),N=s.div(),R=s.button("Alignment parameters",()=>{N.hidden=!N.hidden},"Adjust engine-specific alignment parameters");R.classList.add("msa-params-button"),R.prepend(s.icons.settings(()=>null,"Settings"));const $=s.input.bool("Include HELM",{value:!0});$.setTooltip("Also add the aligned HELM column alongside the converted notation"),$.root.style.display="none";const O=[I.root,_,R,N,$.root];async function H(){N.innerHTML="",g.currentFuncCall=null;const e=I.value;if(g.currentFunc=L.find(t=>t.friendlyName===e)??null,_.textContent=g.currentFunc?.description??"",!g.currentFunc)return;g.currentFuncCall=g.currentFunc.prepare({});const t=await g.currentFuncCall.buildEditor(N);t.length>0&&"column"===t[0].inputType&&(t[0].root.style.display="none")}function D(e){g.mode=e;for(const t of x)t.style.display="kalign"===e?"":"none";for(const t of O)t.style.display="engine"===e?"":"none"}async function F(e){try{if(e.semType!==o.SEMTYPE.MACROMOLECULE)return;const n=(0,c.l)(e,e.name,t,[r.Hi.FASTA,r.Hi.SEPARATOR],[r.YI.DNA,r.YI.RNA,r.YI.PT])[0],s=(0,c.l)(e,e.name,t,[r.Hi.HELM],[])[0],l=(0,c.l)(e,e.name,t,[r.Hi.SEPARATOR,r.Hi.CUSTOM,r.Hi.BILN],[r.YI.UN])[0];if(n)D("kalign"),v.value=null,C.value=null,A.value=null;else if(s||l){if(0===L.length)return i.shell.warning("No MSA engines found for non-canonical sequences."),void D("kalign");D("engine"),await H();const t=e.temp?.[a.j.notationProvider],n=t?t.constructor:null,o=!0===n?.implementsFromHelm;$.root.style.display=o?"":"none"}else D("kalign")}catch(e){const t=e instanceof Error?e.message:e.toString();i.shell.error(t),h._package.logger.error(t)}}async function k(){const e=y.value;if(!e||e.semType!==o.SEMTYPE.MACROMOLECULE)throw new Error("Chosen column must be of Macromolecule semantic type");return"kalign"===g.mode?G(e,m):B(e,m)}async function G(e,n){const i=n.columns.getUnusedName(`msa(${e.name})`),o=t.getSeqHandler(e),s=o.isFasta()?e:o.convert(r.Hi.FASTA);return(0,l.eE)(n,s,!1,i,b.value,v.value??void 0,C.value??void 0,A.value??void 0,w.value)}async function B(e,n){if(!g.currentFunc||!g.currentFuncCall)throw new Error("No MSA engine selected");const i=t.getSeqHandler(e);let s;s=i.isHelm()?e:(i.isSeparator()&&(i.alphabet,r.YI.UN),i.convert(r.Hi.HELM));const c=g.currentFunc,u=c.inputs[0].name,h={};for(let e=1;e<c.inputs.length;e++){const t=c.inputs[e].name;h[t]=g.currentFuncCall.inputs[t]}const d=await async function(e,t,n,i,s,a,c){const u=i.length;s??=o.Column.string("Clusters",u).init("0"),s.type!==o.COLUMN_TYPE.STRING&&(s=s.convertTo(o.TYPE.STRING));const h=s.categories,d=s.getRawData(),m=new Array(h.length);if(a){const e=c.selection;if(0===e.trueCount)throw new Error("No selected rows in the table.");for(let t=-1;-1!==(t=e.findNext(t,!0));)(m[d[t]]??=[]).push(t)}else for(let e=0;e<u;e++)(m[d[e]]??=[]).push(e);(0,l.aZ)(m,h);const p=c.columns.getUnusedName(`msa(${i.name})`),g=new Array(u).fill("");let f=null;for(const s of m){if(!s||0===s.length)continue;const r=s.map(e=>i.get(e)),a=o.Column.fromStrings("seq",r);P(i,a),o.DataFrame.fromColumns([a]);const l=e.prepare({[t]:a,...n});await l.call();const c=l.getOutputParamValue();f=c;for(let e=0;e<s.length;e++)g[s[e]]=c.get(e)??""}const y=o.Column.fromStrings(p,g);if(f){y.meta.units=f.meta.units,y.semType=f.semType;for(const e of[r.gp.alphabet,r.gp.separator,r.gp.alphabetIsMultichar]){const t=f.getTag(e);t&&y.setTag(e,t)}}return y}(c,u,h,s,b.value,w.value,n),m=e.temp?.[a.j.notationProvider],p=m?m.constructor:null;if(p?.implementsFromHelm){const t=n.columns.getUnusedName(`msa(${e.name})`),i=o.Column.string(t,d.length);return i.init(e=>{const t=d.get(e);if(!t)return"";try{return p.convertFromHelm(t,{})}catch{return""}}),i.semType=o.SEMTYPE.MACROMOLECULE,i.meta.units=r.Hi.CUSTOM,i.setTag(r.gp.aligned,"SEQ.MSA"),i.setTag(r.gp.alphabet,r.YI.UN),$.value&&n.columns.add(d),i}return d}async function V(){if(!e.engine||"engine"!==g.mode)return;const t=L.find(t=>t.name===e.engine||t.friendlyName===e.engine);if(t&&(I.value=t.friendlyName,await H(),e.engineParams&&g.currentFuncCall))for(const[t,n]of Object.entries(e.engineParams))g.currentFuncCall.inputs[t]=n}I.onChanged.subscribe(()=>H());const U=s.dialog("MSA").add(y).add(b).add(I).add(_).add(R).add(N).add($).add(E).add(S).add(T).add(w).onOK(async()=>{const e=o.TaskBarProgressIndicator.create("Performing MSA...");try{const e=await k();m.columns.add(e),await i.data.detectSemanticTypes(m),e.meta.units!==r.Hi.HELM&&e.setTag(r.gp.aligned,"SEQ.MSA"),n(e)}catch(e){d(e)}finally{e.close()}}),q=U.getButton("OK");if(D("kalign"),y.fireChanged(),e.col){await F(e.col),await V();const W=o.TaskBarProgressIndicator.create("Performing MSA...");try{const Y=await k();m.columns.add(Y),await i.data.detectSemanticTypes(m),Y.meta.units!==r.Hi.HELM&&Y.setTag(r.gp.aligned,"SEQ.MSA"),n(Y)}catch(j){d(j)}finally{W.close()}return}U.show()}catch(K){d(K)}})}function P(e,t){t.semType=e.semType,t.meta.units=e.meta.units;for(const n of[r.gp.alphabet,r.gp.separator,r.gp.alphabetIsMultichar]){const i=e.getTag(n);i&&t.setTag(n,i)}}},608(e,t,n){"use strict";n.d(t,{Ap:()=>D,aZ:()=>B,eE:()=>k});var i=n(7389),o=n(6082),s=n(1991),r=n.n(s),a=n(3516),l=n(2003);const c=Symbol("Comlink.proxy"),u=Symbol("Comlink.endpoint"),h=Symbol("Comlink.releaseProxy"),d=Symbol("Comlink.thrown"),m=e=>"object"==typeof e&&null!==e||"function"==typeof e,p=new Map([["proxy",{canHandle:e=>m(e)&&e[c],serialize(e){const{port1:t,port2:n}=new MessageChannel;return g(e,t),[n,[n]]},deserialize:e=>(e.start(),y(e))}],["throw",{canHandle:e=>m(e)&&d in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}}]]);function g(e,t=self){t.addEventListener("message",function n(i){if(!i||!i.data)return;const{id:o,type:s,path:r}=Object.assign({path:[]},i.data),a=(i.data.argumentList||[]).map(E);let l;try{const t=r.slice(0,-1).reduce((e,t)=>e[t],e),n=r.reduce((e,t)=>e[t],e);switch(s){case"GET":l=n;break;case"SET":t[r.slice(-1)[0]]=E(i.data.value),l=!0;break;case"APPLY":l=n.apply(t,a);break;case"CONSTRUCT":l=function(e){return Object.assign(e,{[c]:!0})}(new n(...a));break;case"ENDPOINT":{const{port1:t,port2:n}=new MessageChannel;g(e,n),l=function(e,t){return A.set(e,t),e}(t,[t])}break;case"RELEASE":l=void 0;break;default:return}}catch(e){l={value:e,[d]:0}}Promise.resolve(l).catch(e=>({value:e,[d]:0})).then(e=>{const[i,r]=T(e);t.postMessage(Object.assign(Object.assign({},i),{id:o}),r),"RELEASE"===s&&(t.removeEventListener("message",n),f(t))})}),t.start&&t.start()}function f(e){(function(e){return"MessagePort"===e.constructor.name})(e)&&e.close()}function y(e,t){return w(e,[],t)}function b(e){if(e)throw new Error("Proxy has been released and is not useable")}function w(e,t=[],n=function(){}){let i=!1;const o=new Proxy(n,{get(n,s){if(b(i),s===h)return()=>S(e,{type:"RELEASE",path:t.map(e=>e.toString())}).then(()=>{f(e),i=!0});if("then"===s){if(0===t.length)return{then:()=>o};const n=S(e,{type:"GET",path:t.map(e=>e.toString())}).then(E);return n.then.bind(n)}return w(e,[...t,s])},set(n,o,s){b(i);const[r,a]=T(s);return S(e,{type:"SET",path:[...t,o].map(e=>e.toString()),value:r},a).then(E)},apply(n,o,s){b(i);const r=t[t.length-1];if(r===u)return S(e,{type:"ENDPOINT"}).then(E);if("bind"===r)return w(e,t.slice(0,-1));const[a,l]=C(s);return S(e,{type:"APPLY",path:t.map(e=>e.toString()),argumentList:a},l).then(E)},construct(n,o){b(i);const[s,r]=C(o);return S(e,{type:"CONSTRUCT",path:t.map(e=>e.toString()),argumentList:s},r).then(E)}});return o}function v(e){return Array.prototype.concat.apply([],e)}function C(e){const t=e.map(T);return[t.map(e=>e[0]),v(t.map(e=>e[1]))]}const A=new WeakMap;function T(e){for(const[t,n]of p)if(n.canHandle(e)){const[i,o]=n.serialize(e);return[{type:"HANDLER",name:t,value:i},o]}return[{type:"RAW",value:e},A.get(e)||[]]}function E(e){switch(e.type){case"HANDLER":return p.get(e.name).deserialize(e.value);case"RAW":return e.value}}function S(e,t,n){return new Promise(i=>{const o=new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-");e.addEventListener("message",function t(n){!n.data||!n.data.id||n.data.id!==o||(e.removeEventListener("message",t),i(n.data))}),e.start&&e.start(),e.postMessage(Object.assign({id:o},t),n)})}const M="KGZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO2NvbnN0ICQ9U3ltYm9sKCJDb21saW5rLnByb3h5IiksQT1TeW1ib2woIkNvbWxpbmsuZW5kcG9pbnQiKSxSPVN5bWJvbCgiQ29tbGluay5yZWxlYXNlUHJveHkiKSx5PVN5bWJvbCgiQ29tbGluay50aHJvd24iKSxfPWU9PnR5cGVvZiBlPT0ib2JqZWN0IiYmZSE9PW51bGx8fHR5cGVvZiBlPT0iZnVuY3Rpb24iLEw9e2NhbkhhbmRsZTplPT5fKGUpJiZlWyRdLHNlcmlhbGl6ZShlKXtjb25zdHtwb3J0MTpyLHBvcnQyOml9PW5ldyBNZXNzYWdlQ2hhbm5lbDtyZXR1cm4gdyhlLHIpLFtpLFtpXV19LGRlc2VyaWFsaXplKGUpe3JldHVybiBlLnN0YXJ0KCksQyhlKX19LE89e2NhbkhhbmRsZTplPT5fKGUpJiZ5IGluIGUsc2VyaWFsaXplKHt2YWx1ZTplfSl7bGV0IHI7cmV0dXJuIGUgaW5zdGFuY2VvZiBFcnJvcj9yPXtpc0Vycm9yOiEwLHZhbHVlOnttZXNzYWdlOmUubWVzc2FnZSxuYW1lOmUubmFtZSxzdGFjazplLnN0YWNrfX06cj17aXNFcnJvcjohMSx2YWx1ZTplfSxbcixbXV19LGRlc2VyaWFsaXplKGUpe3Rocm93IGUuaXNFcnJvcj9PYmplY3QuYXNzaWduKG5ldyBFcnJvcihlLnZhbHVlLm1lc3NhZ2UpLGUudmFsdWUpOmUudmFsdWV9fSxFPW5ldyBNYXAoW1sicHJveHkiLExdLFsidGhyb3ciLE9dXSk7ZnVuY3Rpb24gdyhlLHI9c2VsZil7ci5hZGRFdmVudExpc3RlbmVyKCJtZXNzYWdlIixmdW5jdGlvbiBpKHMpe2lmKCFzfHwhcy5kYXRhKXJldHVybjtjb25zdHtpZDpvLHR5cGU6YSxwYXRoOm59PU9iamVjdC5hc3NpZ24oe3BhdGg6W119LHMuZGF0YSksYz0ocy5kYXRhLmFyZ3VtZW50TGlzdHx8W10pLm1hcChtKTtsZXQgbDt0cnl7Y29uc3QgdT1uLnNsaWNlKDAsLTEpLnJlZHVjZSgoZCxwKT0+ZFtwXSxlKSxmPW4ucmVkdWNlKChkLHApPT5kW3BdLGUpO3N3aXRjaChhKXtjYXNlIkdFVCI6bD1mO2JyZWFrO2Nhc2UiU0VUIjp1W24uc2xpY2UoLTEpWzBdXT1tKHMuZGF0YS52YWx1ZSksbD0hMDticmVhaztjYXNlIkFQUExZIjpsPWYuYXBwbHkodSxjKTticmVhaztjYXNlIkNPTlNUUlVDVCI6e2NvbnN0IGQ9bmV3IGYoLi4uYyk7bD16KGQpfWJyZWFrO2Nhc2UiRU5EUE9JTlQiOntjb25zdHtwb3J0MTpkLHBvcnQyOnB9PW5ldyBNZXNzYWdlQ2hhbm5lbDt3KGUscCksbD1OKGQsW2RdKX1icmVhaztjYXNlIlJFTEVBU0UiOmw9dm9pZCAwO2JyZWFrO2RlZmF1bHQ6cmV0dXJufX1jYXRjaCh1KXtsPXt2YWx1ZTp1LFt5XTowfX1Qcm9taXNlLnJlc29sdmUobCkuY2F0Y2godT0+KHt2YWx1ZTp1LFt5XTowfSkpLnRoZW4odT0+e2NvbnN0W2YsZF09Uyh1KTtyLnBvc3RNZXNzYWdlKE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxmKSx7aWQ6b30pLGQpLGE9PT0iUkVMRUFTRSImJihyLnJlbW92ZUV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLGkpLE0ocikpfSl9KSxyLnN0YXJ0JiZyLnN0YXJ0KCl9ZnVuY3Rpb24gVChlKXtyZXR1cm4gZS5jb25zdHJ1Y3Rvci5uYW1lPT09Ik1lc3NhZ2VQb3J0In1mdW5jdGlvbiBNKGUpe1QoZSkmJmUuY2xvc2UoKX1mdW5jdGlvbiBDKGUscil7cmV0dXJuIGIoZSxbXSxyKX1mdW5jdGlvbiBoKGUpe2lmKGUpdGhyb3cgbmV3IEVycm9yKCJQcm94eSBoYXMgYmVlbiByZWxlYXNlZCBhbmQgaXMgbm90IHVzZWFibGUiKX1mdW5jdGlvbiBiKGUscj1bXSxpPWZ1bmN0aW9uKCl7fSl7bGV0IHM9ITE7Y29uc3Qgbz1uZXcgUHJveHkoaSx7Z2V0KGEsbil7aWYoaChzKSxuPT09UilyZXR1cm4oKT0+ZyhlLHt0eXBlOiJSRUxFQVNFIixwYXRoOnIubWFwKGM9PmMudG9TdHJpbmcoKSl9KS50aGVuKCgpPT57TShlKSxzPSEwfSk7aWYobj09PSJ0aGVuIil7aWYoci5sZW5ndGg9PT0wKXJldHVybnt0aGVuOigpPT5vfTtjb25zdCBjPWcoZSx7dHlwZToiR0VUIixwYXRoOnIubWFwKGw9PmwudG9TdHJpbmcoKSl9KS50aGVuKG0pO3JldHVybiBjLnRoZW4uYmluZChjKX1yZXR1cm4gYihlLFsuLi5yLG5dKX0sc2V0KGEsbixjKXtoKHMpO2NvbnN0W2wsdV09UyhjKTtyZXR1cm4gZyhlLHt0eXBlOiJTRVQiLHBhdGg6Wy4uLnIsbl0ubWFwKGY9PmYudG9TdHJpbmcoKSksdmFsdWU6bH0sdSkudGhlbihtKX0sYXBwbHkoYSxuLGMpe2gocyk7Y29uc3QgbD1yW3IubGVuZ3RoLTFdO2lmKGw9PT1BKXJldHVybiBnKGUse3R5cGU6IkVORFBPSU5UIn0pLnRoZW4obSk7aWYobD09PSJiaW5kIilyZXR1cm4gYihlLHIuc2xpY2UoMCwtMSkpO2NvbnN0W3UsZl09RihjKTtyZXR1cm4gZyhlLHt0eXBlOiJBUFBMWSIscGF0aDpyLm1hcChkPT5kLnRvU3RyaW5nKCkpLGFyZ3VtZW50TGlzdDp1fSxmKS50aGVuKG0pfSxjb25zdHJ1Y3QoYSxuKXtoKHMpO2NvbnN0W2MsbF09RihuKTtyZXR1cm4gZyhlLHt0eXBlOiJDT05TVFJVQ1QiLHBhdGg6ci5tYXAodT0+dS50b1N0cmluZygpKSxhcmd1bWVudExpc3Q6Y30sbCkudGhlbihtKX19KTtyZXR1cm4gb31mdW5jdGlvbiBEKGUpe3JldHVybiBBcnJheS5wcm90b3R5cGUuY29uY2F0LmFwcGx5KFtdLGUpfWZ1bmN0aW9uIEYoZSl7Y29uc3Qgcj1lLm1hcChTKTtyZXR1cm5bci5tYXAoaT0+aVswXSksRChyLm1hcChpPT5pWzFdKSldfWNvbnN0IFA9bmV3IFdlYWtNYXA7ZnVuY3Rpb24gTihlLHIpe3JldHVybiBQLnNldChlLHIpLGV9ZnVuY3Rpb24geihlKXtyZXR1cm4gT2JqZWN0LmFzc2lnbihlLHtbJF06ITB9KX1mdW5jdGlvbiBTKGUpe2Zvcihjb25zdFtyLGldb2YgRSlpZihpLmNhbkhhbmRsZShlKSl7Y29uc3RbcyxvXT1pLnNlcmlhbGl6ZShlKTtyZXR1cm5be3R5cGU6IkhBTkRMRVIiLG5hbWU6cix2YWx1ZTpzfSxvXX1yZXR1cm5be3R5cGU6IlJBVyIsdmFsdWU6ZX0sUC5nZXQoZSl8fFtdXX1mdW5jdGlvbiBtKGUpe3N3aXRjaChlLnR5cGUpe2Nhc2UiSEFORExFUiI6cmV0dXJuIEUuZ2V0KGUubmFtZSkuZGVzZXJpYWxpemUoZS52YWx1ZSk7Y2FzZSJSQVciOnJldHVybiBlLnZhbHVlfX1mdW5jdGlvbiBnKGUscixpKXtyZXR1cm4gbmV3IFByb21pc2Uocz0+e2NvbnN0IG89VSgpO2UuYWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsZnVuY3Rpb24gYShuKXshbi5kYXRhfHwhbi5kYXRhLmlkfHxuLmRhdGEuaWQhPT1vfHwoZS5yZW1vdmVFdmVudExpc3RlbmVyKCJtZXNzYWdlIixhKSxzKG4uZGF0YSkpfSksZS5zdGFydCYmZS5zdGFydCgpLGUucG9zdE1lc3NhZ2UoT2JqZWN0LmFzc2lnbih7aWQ6b30sciksaSl9KX1mdW5jdGlvbiBVKCl7cmV0dXJuIG5ldyBBcnJheSg0KS5maWxsKDApLm1hcCgoKT0+TWF0aC5mbG9vcihNYXRoLnJhbmRvbSgpKk51bWJlci5NQVhfU0FGRV9JTlRFR0VSKS50b1N0cmluZygxNikpLmpvaW4oIi0iKX1jb25zdCBXPWFzeW5jKCk9PldlYkFzc2VtYmx5LnZhbGlkYXRlKG5ldyBVaW50OEFycmF5KFswLDk3LDExNSwxMDksMSwwLDAsMCwxLDUsMSw5NiwwLDEsMTIzLDMsMiwxLDAsMTAsMTAsMSw4LDAsNjUsMCwyNTMsMTUsMjUzLDk4LDExXSkpLGs9ImVhZ2VyIix4PSJsYXp5IixqPXtzc3c6WyJzaW1kIl0sbWluaW1hcDI6WyJzaW1kIl19LHQ9e3Rvb2xzOltdLGNvbmZpZzp7fSxmaWxlczpbXSxiYXNlOnt9LGZzOnt9LGFzeW5jIGluaXQoKXtpZih0LnRvb2xzLmxlbmd0aD09PTApdGhyb3ciRXhwZWN0aW5nIGF0IGxlYXN0IDEgdG9vbC4iO2lmKG5ldyBTZXQodC50b29scy5tYXAocj0+YCR7ci50b29sfS8ke3IucHJvZ3JhbXx8ci50b29sfWApKS5zaXplIT09dC50b29scy5sZW5ndGgpdGhyb3ciRm91bmQgZHVwbGljYXRlIHRvb2xzOyBjYW4gb25seSBoYXZlIGVhY2ggdG9vbC9wcm9ncmFtIGNvbWJpbmF0aW9uIGF0IG1vc3Qgb25jZS4iO2lmKHQuYmFzZT10LnRvb2xzLmZpbmQocj0+ci5yZWluaXQhPT0hMCksIXQuYmFzZSl0aHJvdyJDb3VsZCBub3QgZmluZCBhIHRvb2wgd2l0aCBgcmVpbml0OiBmYWxzZWAgdG8gdXNlIGFzIHRoZSBiYXNlIG1vZHVsZS4gVG8gZml4IHRoaXMgaXNzdWUsIGluY2x1ZGUgdGhlIHRvb2wgYGJhc2UvMS4wLjBgIHdoZW4gaW5pdGlhbGl6aW5nIEFpb2xpLiI7cmV0dXJuIHQuYmFzZS5pc0Jhc2VNb2R1bGU9ITAsYXdhaXQgdGhpcy5fc2V0dXAodC5iYXNlKSxhd2FpdCB0aGlzLl9pbml0TW9kdWxlcygpLHQuX2xvZygiUmVhZHkiKSwhMH0sYXN5bmMgX2luaXRNb2R1bGVzKCl7YXdhaXQgUHJvbWlzZS5hbGwodC50b29scy5tYXAodGhpcy5fc2V0dXApKSxhd2FpdCB0aGlzLl9zZXR1cEZTKCl9LG1vdW50KGU9W10pe2NvbnN0IHI9YCR7dC5jb25maWcuZGlyU2hhcmVkfSR7dC5jb25maWcuZGlyRGF0YX1gLGk9YCR7dC5jb25maWcuZGlyU2hhcmVkfSR7dC5jb25maWcuZGlyTW91bnRlZH1gO2xldCBzPVtdLG89W10sYT1bXTshQXJyYXkuaXNBcnJheShlKSYmIShlIGluc3RhbmNlb2YgRmlsZUxpc3QpJiYoZT1bZV0pLHQuX2xvZyhgTW91bnRpbmcgJHtlLmxlbmd0aH0gZmlsZXNgKTtmb3IobGV0IG4gb2YgZSl7aWYobiBpbnN0YW5jZW9mIEZpbGV8fChuPT1udWxsP3ZvaWQgMDpuLmRhdGEpaW5zdGFuY2VvZiBCbG9iJiZuLm5hbWV8fHR5cGVvZihuPT1udWxsP3ZvaWQgMDpuLmRhdGEpPT0ic3RyaW5nIiYmbi5uYW1lKXR5cGVvZihuPT1udWxsP3ZvaWQgMDpuLmRhdGEpPT0ic3RyaW5nIiYmKG4uZGF0YT1uZXcgQmxvYihbbi5kYXRhXSx7dHlwZToidGV4dC9wbGFpbiJ9KSkscy5wdXNoKG4pO2Vsc2UgaWYobi5uYW1lJiZuLnVybClvLnB1c2gobik7ZWxzZSBpZih0eXBlb2Ygbj09InN0cmluZyImJm4uc3RhcnRzV2l0aCgiaHR0cCIpKW49e3VybDpuLG5hbWU6bi5zcGxpdCgiLy8iKS5wb3AoKS5yZXBsYWNlKC9cLy9nLCItIil9LG8ucHVzaChuKTtlbHNlIHRocm93J0Nhbm5vdCBtb3VudCBmaWxlKHMpIHNwZWNpZmllZC4gTXVzdCBiZSBhIEZpbGUsIEJsb2IsIGEgVVJMIHN0cmluZywgb3IgeyBuYW1lOiAiZmlsZS50eHQiLCBkYXRhOiAic3RyaW5nIiB9Lic7YS5wdXNoKG4ubmFtZSl9dHJ5e3QuZnMudW5tb3VudChpKX1jYXRjaHt9Zm9yKGxldCBuIG9mIG8pdC5mcy5jcmVhdGVMYXp5RmlsZShyLG4ubmFtZSxuLnVybCwhMCwhMCk7cmV0dXJuIHQuZmlsZXM9dC5maWxlcy5jb25jYXQocyksdC5iYXNlLm1vZHVsZS5GUy5tb3VudCh0LmJhc2UubW9kdWxlLldPUktFUkZTLHtmaWxlczp0LmZpbGVzLmZpbHRlcihuPT5uIGluc3RhbmNlb2YgRmlsZSksYmxvYnM6dC5maWxlcy5maWx0ZXIobj0+KG49PW51bGw/dm9pZCAwOm4uZGF0YSlpbnN0YW5jZW9mIEJsb2IpfSxpKSxzLm1hcChuPT57Y29uc3QgYz1gJHtpfS8ke24ubmFtZX1gLGw9YCR7cn0vJHtuLm5hbWV9YDt0cnl7dC5mcy51bmxpbmsobCl9Y2F0Y2h7fXQuX2xvZyhgQ3JlYXRpbmcgc3ltbGluazogJHtsfSAtLT4gJHtjfWApLHQuZnMuc3ltbGluayhjLGwpfSksYS5tYXAobj0+YCR7cn0vJHtufWApfSxhc3luYyBleGVjKGUscj1udWxsKXtpZih0Ll9sb2coYEV4ZWN1dGluZyAlYyR7ZX0lYyBhcmdzPSR7cn1gLCJjb2xvcjpkYXJrYmx1ZTsgZm9udC13ZWlnaHQ6Ym9sZCIsIiIpLCFlKXRocm93IkV4cGVjdGluZyBhIGNvbW1hbmQiO2xldCBpPWU7cj09bnVsbCYmKHI9ZS5zcGxpdCgiICIpLGk9ci5zaGlmdCgpKTtjb25zdCBzPXQudG9vbHMuZmluZChhPT57dmFyIGM7bGV0IG49aTtyZXR1cm4oKGM9YT09bnVsbD92b2lkIDA6YS5mZWF0dXJlcyk9PW51bGw/dm9pZCAwOmMuc2ltZCk9PT0hMCYmKG49YCR7bn0tc2ltZGApLGEucHJvZ3JhbT09bn0pO2lmKHM9PW51bGwpdGhyb3dgUHJvZ3JhbSAke2l9IG5vdCBmb3VuZC5gO3Muc3Rkb3V0PSIiLHMuc3RkZXJyPSIiLHMubG9hZGluZz09eCYmKHMubG9hZGluZz1rLGF3YWl0IHRoaXMuX2luaXRNb2R1bGVzKCkpO3RyeXtzLm1vZHVsZS5jYWxsTWFpbihyKX1jYXRjaChhKXtjb25zb2xlLmVycm9yKGEpfXRyeXtzLm1vZHVsZS5GUy5jbG9zZShzLm1vZHVsZS5GUy5zdHJlYW1zWzFdKSxzLm1vZHVsZS5GUy5jbG9zZShzLm1vZHVsZS5GUy5zdHJlYW1zWzJdKX1jYXRjaHt9cy5tb2R1bGUuRlMuc3RyZWFtc1sxXT1zLm1vZHVsZS5GUy5vcGVuKCIvZGV2L3N0ZG91dCIsInciKSxzLm1vZHVsZS5GUy5zdHJlYW1zWzJdPXMubW9kdWxlLkZTLm9wZW4oIi9kZXYvc3RkZXJyIiwidyIpO2xldCBvPXtzdGRvdXQ6cy5zdGRvdXQsc3RkZXJyOnMuc3RkZXJyfTtyZXR1cm4gdC5jb25maWcucHJpbnRJbnRlcmxlYXZlZCYmKG89cy5zdGRvdXQpLHMucmVpbml0PT09ITAmJmF3YWl0IHRoaXMucmVpbml0KHMudG9vbCksb30sY2F0KGUpe3JldHVybiB0Ll9maWxlb3AoImNhdCIsZSl9LGxzKGUpe3JldHVybiB0Ll9maWxlb3AoImxzIixlKX0sZG93bmxvYWQoZSl7cmV0dXJuIHQuX2ZpbGVvcCgiZG93bmxvYWQiLGUpfSxwd2QoKXtyZXR1cm4gdC5mcy5jd2QoKX0sY2QoZSl7Zm9yKGxldCByIG9mIHQudG9vbHMpIXIubW9kdWxlfHxyLm1vZHVsZS5GUy5jaGRpcihlKX0sbWtkaXIoZSl7cmV0dXJuIHQuZnMubWtkaXIoZSksITB9LHJlYWQoe3BhdGg6ZSxsZW5ndGg6cixmbGFnOmk9InIiLG9mZnNldDpzPTAscG9zaXRpb246bz0wfSl7Y29uc3QgYT10LmZzLm9wZW4oZSxpKSxuPW5ldyBVaW50OEFycmF5KHIpO3JldHVybiB0LmZzLnJlYWQoYSxuLHMscixvKSx0LmZzLmNsb3NlKGEpLG59LHdyaXRlKHtwYXRoOmUsYnVmZmVyOnIsZmxhZzppPSJ3KyIsb2Zmc2V0OnM9MCxwb3NpdGlvbjpvPTB9KXtjb25zdCBhPXQuZnMub3BlbihlLGkpO3QuZnMud3JpdGUoYSxyLHMsci5sZW5ndGgsbyksdC5mcy5jbG9zZShhKX0sYXN5bmMgcmVpbml0KGUpe2NvbnN0IHI9dC50b29scy5maW5kKHM9PnMudG9vbD09ZSksaT10LmJhc2UubW9kdWxlLkZTLmN3ZCgpO09iamVjdC5hc3NpZ24ocixyLmNvbmZpZyksci5yZWFkeT0hMSxhd2FpdCB0aGlzLmluaXQoKSxyLmlzQmFzZU1vZHVsZSYmdGhpcy5tb3VudCgpLHRoaXMuY2QoaSl9LF9zdGRpblR4dDoiIixfc3RkaW5QdHI6MCxnZXQgc3RkaW4oKXtyZXR1cm4gdC5fc3RkaW5UeHR9LHNldCBzdGRpbihlPSIiKXt0Ll9sb2coYFNldHRpbmcgc3RkaW4gdG8gJWMke2V9JWNgLCJjb2xvcjpkYXJrYmx1ZSIsIiIpLHQuX3N0ZGluVHh0PWUsdC5fc3RkaW5QdHI9MH0sYXN5bmMgX3NldHVwKGUpe2lmKGUucmVhZHkpcmV0dXJuO2lmKHQuX2xvZyhgU2V0dGluZyB1cCAke2UudG9vbH0gKGJhc2UgPSAke2UuaXNCYXNlTW9kdWxlPT09ITB9KS4uLmApLGUuY29uZmlnPU9iamVjdC5hc3NpZ24oe30sZSksZS51cmxQcmVmaXh8fChlLnVybFByZWZpeD1gJHt0LmNvbmZpZy51cmxDRE59LyR7ZS50b29sfS8ke2UudmVyc2lvbn1gKSxlLnByb2dyYW18fChlLnByb2dyYW09ZS50b29sKSxlLmZlYXR1cmVzfHwoZS5mZWF0dXJlcz17fSwoaltlLnByb2dyYW1dfHxbXSkuaW5jbHVkZXMoInNpbWQiKSYmKGF3YWl0IFcoKT8oZS5wcm9ncmFtKz0iLXNpbWQiLGUuZmVhdHVyZXMuc2ltZD0hMCk6dC5fbG9nKGBXZWJBc3NlbWJseSBTSU1EIGlzIG5vdCBzdXBwb3J0ZWQgaW4gdGhpcyBicm93c2VyOyB3aWxsIGxvYWQgbm9uLVNJTUQgdmVyc2lvbiBvZiAke2UucHJvZ3JhbX0uYCkpKSxlLmlzQmFzZU1vZHVsZSYmKGUubG9hZGluZz1rKSxlLmxvYWRpbmc9PT14KXt0Ll9sb2coYFdpbGwgbGF6eS1sb2FkICR7ZS50b29sfTsgc2tpcHBpbmcgaW5pdGlhbGl6YXRpb24uYCk7cmV0dXJufXNlbGYuaW1wb3J0U2NyaXB0cyhgJHtlLnVybFByZWZpeH0vJHtlLnByb2dyYW19LmpzYCksZS5tb2R1bGU9YXdhaXQgTW9kdWxlKHt0aGlzUHJvZ3JhbTplLnByb2dyYW0sbG9jYXRlRmlsZTooaSxzKT0+YCR7ZS51cmxQcmVmaXh9LyR7aX1gLHN0ZGluOigpPT50Ll9zdGRpblB0cjx0LnN0ZGluLmxlbmd0aD90LnN0ZGluLmNoYXJDb2RlQXQodC5fc3RkaW5QdHIrKyk6KHQuc3RkaW49IiIsbnVsbCkscHJpbnQ6aT0+e3QuY29uZmlnLnByaW50U3RyZWFtP3Bvc3RNZXNzYWdlKHt0eXBlOiJiaW93YXNtIix2YWx1ZTp7c3Rkb3V0Oml9fSk6ZS5zdGRvdXQrPWkrYApgfSxwcmludEVycjppPT57Y29uc3Qgcz10LmNvbmZpZy5wcmludEludGVybGVhdmVkPyJzdGRvdXQiOiJzdGRlcnIiO3QuY29uZmlnLnByaW50U3RyZWFtP3Bvc3RNZXNzYWdlKHt0eXBlOiJiaW93YXNtIix2YWx1ZTp7W3NdOml9fSk6ZVtzXSs9aStgCmB9fSk7Y29uc3Qgcj1lLm1vZHVsZS5GUztlLmlzQmFzZU1vZHVsZT8odC5fbG9nKGBTZXR0aW5nIHVwICR7ZS50b29sfSB3aXRoIGJhc2UgbW9kdWxlIGZpbGVzeXN0ZW0uLi5gKSxyLm1rZGlyKHQuY29uZmlnLmRpclNoYXJlZCw1MTEpLHIubWtkaXIoYCR7dC5jb25maWcuZGlyU2hhcmVkfS8ke3QuY29uZmlnLmRpckRhdGF9YCw1MTEpLHIubWtkaXIoYCR7dC5jb25maWcuZGlyU2hhcmVkfS8ke3QuY29uZmlnLmRpck1vdW50ZWR9YCw1MTEpLHIuY2hkaXIoYCR7dC5jb25maWcuZGlyU2hhcmVkfS8ke3QuY29uZmlnLmRpckRhdGF9YCksdC5mcz1yKToodC5fbG9nKGBTZXR0aW5nIHVwICR7ZS50b29sfSB3aXRoIGZpbGVzeXN0ZW0uLi5gKSxyLm1rZGlyKHQuY29uZmlnLmRpclNoYXJlZCksci5tb3VudChlLm1vZHVsZS5QUk9YWUZTLHtyb290OnQuY29uZmlnLmRpclNoYXJlZCxmczp0LmZzfSx0LmNvbmZpZy5kaXJTaGFyZWQpLHIuY2hkaXIodC5mcy5jd2QoKSkpLGUuc3Rkb3V0PSIiLGUuc3RkZXJyPSIiLGUucmVhZHk9ITB9LGFzeW5jIF9zZXR1cEZTKCl7Y29uc3QgZT10LmZzO2ZvcihsZXQgciBvZiB0LnRvb2xzKXtpZighci5yZWFkeSljb250aW51ZTtjb25zdCBpPXIubW9kdWxlLkZTLHM9YC8ke3IudG9vbH1gLG89YCR7dC5jb25maWcuZGlyU2hhcmVkfSR7c31gOyFpLmFuYWx5emVQYXRoKHMpLmV4aXN0c3x8ZS5hbmFseXplUGF0aChvKS5leGlzdHN8fCh0Ll9sb2coYE1vdW50aW5nICR7c30gb250byAke3QuYmFzZS50b29sfSBmaWxlc3lzdGVtIGF0ICR7b31gKSxlLm1rZGlyKG8pLGUubW91bnQodC5iYXNlLm1vZHVsZS5QUk9YWUZTLHtyb290OnMsZnM6aX0sbykpfX0sX2ZpbGVvcChlLHIpe3QuX2xvZyhgUnVubmluZyAke2V9ICR7cn1gKTtjb25zdCBpPXQuZnMuYW5hbHl6ZVBhdGgocik7aWYoIWkuZXhpc3RzKXJldHVybiB0Ll9sb2coYEZpbGUgJHtyfSBub3QgZm91bmQuYCksITE7c3dpdGNoKGUpe2Nhc2UiY2F0IjpyZXR1cm4gdC5mcy5yZWFkRmlsZShyLHtlbmNvZGluZzoidXRmOCJ9KTtjYXNlImxzIjpyZXR1cm4gdC5mcy5pc0ZpbGUoaS5vYmplY3QubW9kZSk/dC5mcy5zdGF0KHIpOnQuZnMucmVhZGRpcihyKTtjYXNlImRvd25sb2FkIjpjb25zdCBzPW5ldyBCbG9iKFt0aGlzLmNhdChyKV0pO3JldHVybiBVUkwuY3JlYXRlT2JqZWN0VVJMKHMpfXJldHVybiExfSxfbG9nKGUpe2lmKCF0LmNvbmZpZy5kZWJ1ZylyZXR1cm47bGV0IHI9Wy4uLmFyZ3VtZW50c107ci5zaGlmdCgpLGNvbnNvbGUubG9nKGAlY1tXZWJXb3JrZXJdJWMgJHtlfWAsImZvbnQtd2VpZ2h0OmJvbGQiLCIiLC4uLnIpfX07dyh0KX0pKCk7Cg==",x=typeof window<"u"&&window.Blob&&new Blob([atob(M)],{type:"text/javascript;charset=utf-8"});function P(){const e=x&&(window.URL||window.webkitURL).createObjectURL(x);try{return e?new Worker(e):new Worker("data:application/javascript;base64,"+M)}finally{e&&(window.URL||window.webkitURL).revokeObjectURL(e)}}const L={urlCDN:"https://biowasm.com/cdn/v3",urlCDNStg:"https://stg.biowasm.com/cdn/v3",dirShared:"/shared",dirMounted:"/mnt",dirData:"/data",printInterleaved:!0,printStream:!1,callback:null,debug:!1,env:"prd"};class I{constructor(e,t={}){if(null==e)throw"Expecting array of tools as input to Aioli constructor.";return Array.isArray(e)||(e=[e]),t=Object.assign({},L,t),e=e.map(this._parseTool),"stg"===t.env&&(t.urlCDN=t.urlCDNStg),this.tools=e,this.config=t,null!=this.config.callback&&(this.callback=this.config.callback),delete this.config.callback,this.init()}async init(){const e=new P;this.callback&&(e.onmessage=e=>{"biowasm"===e.data.type&&this.callback(e.data.value)});const t=y(e);return t.tools=this.tools,t.config=this.config,await t.init(),t}_parseTool(e){if("string"!=typeof e)return e;const t=e.split("/");if(2!=t.length&&3!=t.length)throw"Expecting '<tool>/<version>' or '<tool>/<program>/<version>'";return{tool:t[0],program:3==t.length?t[1]:t[0],version:t[t.length-1]}}}var _=n(3629);class N{static getAvailableScales(){return Object.entries(this.scales).map(([e,t])=>e)}static getScale(e){return(0,_.vA)(!(void 0===this.scales[e]),`Scale '${e}' was not found.`),this.scales[e]}}N.scales={WimleyWhite:{"-":0,A:.17,C:-.24,D:-.07,E:-.01,F:-1.13,G:.01,H:.17,I:-.31,K:.99,L:-.56,M:-.23,N:.42,P:.45,Q:.58,R:.81,S:.13,T:.14,V:.07,W:-1.85,Y:-.94},categorial:{"-":0,A:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,K:9,L:10,M:11,N:12,P:13,Q:14,R:15,S:16,T:17,V:18,W:19,Y:20}};class R{constructor(e="categorial"){this.aa2num=N.getScale(e),this.num2aa={},Object.entries(this.aa2num).forEach(([e,t])=>this.num2aa[t]=e)}static _truncateSequence(e){let t=0,n=e.length;const i=["NH2","COOH"];if(e.startsWith(i[0])){const n=i[0].length;(0,_.vA)("-"==e[n],`Wrong sequence format: ${i[0]} without following '-' in '${e}'.`),t=n}if(e.endsWith(i[1])){const t=i[1].length+1;(0,_.vA)("-"==e[n-t],`Wrong sequence format: ${i[1]} without '-' precending in '${e}'.`),n-=t}return e.substring(t,n)}static _dropDefises(e){return e.replace(/(-)([^-]+)/g,"$2")}static clean(e){return R._dropDefises(R._truncateSequence(e))}encode(e){const t=e.length,n=new Array(t).fill(0);for(let i=0;i<t;++i){const t=e[i];(0,_.vA)(t in this.aa2num,`Unknown char '${t}' found in sequence '${e}'`),n[i]=this.encodeLettter(t)}return n}encodeLettter(e){return this.aa2num[e]}decode(e){let t="";for(let n=0;n<e.length;++n){const i=e[n];(0,_.vA)(i in this.num2aa,`Unknown code '${i}' found in vector '${e}'`),t+=this.num2aa[i]}return t}}var $=n(4139);const O="input.fa",H="result.fasta";class D extends Error{element;constructor(e,t){super(e.innerText,t),this.element=e}}function F(e){return e.reduce((e,t,n)=>e+`>sample${n+1}\n${t}\n`,"")}async function k(e,t,n=!1,i="",s=null,r,c,u,h){let d=t.toList();n&&(d=d.map(e=>R.clean(e).replace(/\-/g,"")));const m=t.length;s??=o.Column.string("Clusters",m).init("0"),s.type!=o.COLUMN_TYPE.STRING&&(s=s.convertTo(o.TYPE.STRING)),s.compact();const p=s.categories,g=s.getRawData(),f=new Array(p.length),y=new Array(p.length);if(h){const t=e.selection;if(0===t.length)throw new Error("No selected rows in the table.");for(let e=-1;-1!==(e=t.findNext(e,!0));){const t=g[e];(f[t]??=[]).push(d[e]),(y[t]??=[]).push(e)}}else for(let e=0;e<m;++e){const t=g[e];(f[t]??=[]).push(d[e]),(y[t]??=[]).push(e)}B(y,p);const b=await new I(["base/1.0.0",{tool:"kalign",version:$.b9,reinit:!0}]),w=o.Column.string(i,m);for(let e=0;e<p.length;++e){const t=f[e];if(!t||0===t.length)continue;const n=F(t);await b.fs.writeFile(O,n);const i=`${void 0!==r?` --gpo ${r}`:""}${void 0!==c?` --gpe ${c}`:""}${void 0!==u?` --tgpe ${u}`:""}`,o=await b.exec(`kalign ${O} -f fasta -o ${H}${i}`);console.warn(o);const s=await b.cat(H);if(!s){const e=G(o,1);throw new Error(e)}const l=new a.m(s).sequencesArray,h=y[e];for(let e=0;e<l.length;++e)w.set(h[e],l[e])}const v=t.meta.units,C=t.getTag(l.gp.alphabet);return w.meta.units=v,w.setTag(l.gp.aligned,"SEQ.MSA"),w.setTag(l.gp.alphabet,C),w.semType=o.SEMTYPE.MACROMOLECULE,w}function G(e,t){const n=[],i=/^.+ERROR : (.+)$/gm;let o;for(;null!=(o=i.exec(e))&&(null==t||n.length<t);)n.push(o[1]);return n.join("\n")}function B(e,t){const n=e.map((e,t)=>[e,t]).filter(([e,t])=>1==e.length).map(([e,t])=>t);if(n.length>0){const e=i.div([i.divText(`MSA analysis is not available on single sequence clusters #${n.length}:`),...r()(n).take(3).map(e=>{let o=t[e];return o.length>25&&(o=o.slice(0,25)+"..."),i.divText(`"${o}"${e<n.length-1?", ":"."}`)}).toArray(),...n.length>3?[i.divText("...")]:[]]);throw new D(e)}}},8152(e,t,n){"use strict";n.d(t,{GD:()=>d,Gf:()=>h});var i=n(4328),o=n(6082),s=n(2003),r=n(608),a=n(4139),l=n(3328);const c=["AlignedSeq","AlignedSubpeptide","HELM","ID","PolymerID"],u=new class{dcName="bio";async getDockerContainer(){return await i.dapi.docker.dockerContainers.filter(this.dcName).first()}};async function h(e,t="mafft --auto",n=1.53,i=0){const o=await u.getDockerContainer(),s=e.length,r=[];for(let t=0;t<s;t++){const n=e.get(t);n&&r.push({ID:t.toString(),HELM:n})}const a=function(e,t){const n=new Array(t).fill(null);for(const t of e.Alignment)n[parseInt(t.ID)]=m(t);return n}(await g(o.id,r,t,n,i),s);return p(e.dataFrame?.columns?.getUnusedName(`msa(${e.name})`)??`msa(${e.name})`,a)}async function d(e,t,n,i="ginsi",s=1.53,a=0,l=null,c,h=!1){const d=await u.getDockerContainer(),f=t.length;l??=o.Column.int("Clusters",f).init(0),l.type!==o.COLUMN_TYPE.STRING&&(l=l.convertTo(o.TYPE.STRING));const y=l.categories,b=l.getRawData(),w=new Array(y.length),v=new Array(y.length),C=h?function*(e){for(let t=-1;-1!==(t=e.findNext(t,!0));)yield t}(e.selection):function*(e){for(let t=0;t<e;t++)yield t}(f);for(const e of C){const n=b[e];if(!y[n])continue;const i=t.get(e);i&&((w[n]??=[]).push({ID:e.toString(),HELM:i}),(v[n]??=[]).push(e))}(0,r.aZ)(v,y);const A=new Array(f).fill(null);for(const e of w){if(!e||0===e.length)continue;const t=await g(d.id,e,i,s,a,c);for(const e of t.Alignment)A[parseInt(e.ID)]=m(e)}return p(n,A)}function m(e){return Object.entries(e).filter(([e])=>!c.includes(e)).map(([,e])=>"-"!==e?e:"").join(a.J.SEPARATOR)}function p(e,t){const n=o.Column.fromStrings(e,t);return n.meta.units=s.Hi.SEPARATOR,n.setTag(s.gp.separator,a.J.SEPARATOR),n.setTag(s.gp.aligned,"SEQ.MSA"),n.setTag(s.gp.alphabet,s.YI.UN),n.setTag(s.gp.alphabetIsMultichar,"true"),n.semType=o.SEMTYPE.MACROMOLECULE,n}async function g(e,t,n,o,s,r){const a={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(t)},c=`/align?method=${n}&gap_open=${o}&gap_extend=${s}`,u=window.performance.now(),h=await i.dapi.docker.dockerContainers.fetchProxy(e,c,a),d=window.performance.now();l._package.logger.debug(`Bio: requestAlignedObjects() ET: ${d-u} ms`);const m="application/json"===h.headers.get("content-type");if(!h.ok){if(m){const e=await h.json();if(e["pepsea-error"])throw new Error(`PepSeA error: ${e["pepsea-error"]}`);if(e["datagrok-error"])throw new Error(`Datagrok error: ${e["datagrok-error"]}`);throw new Error(h.statusText)}const e=await h.text();throw new Error(`Error: ${e}`)}if(!m){const e=await h.text();throw new Error(`Error: PepSeA expected JSON response, got '${e}'.`)}const p=await h.json();return"pepsea-stderr"in p&&r?.warning(p["pepsea-stderr"]),p}},3890(e,t,n){"use strict";n.d(t,{TE:()=>c,aS:()=>h,wz:()=>u});var i=n(6082),o=n(7389),s=n(4328),r=n(1991),a=n.n(r),l=n(3328);function c(){const e=s.shell.tv.grid,t=e.dataFrame,n=a().count(0).take(t.columns.length).map(e=>t.columns.byIndex(e)).filter(e=>e.semType!==i.SEMTYPE.MACROMOLECULE).toArray().find(e=>-1!==e.name.toLowerCase().indexOf("id")),r=n?[n]:[],c=o.input.columns("Seq id columns",{table:t,value:r,filter:e=>e.semType!==i.SEMTYPE.MACROMOLECULE}),h=a().count(0).take(t.columns.length).map(e=>t.columns.byIndex(e)).filter(e=>!(!e||e.semType!==i.SEMTYPE.MACROMOLECULE)&&l._package.seqHelper.getSeqHandler(e).isFasta()).toArray(),d=h.length>0?h[0]:null,m=o.input.column("Seq column",{table:t,value:d,filter:e=>!(!e||e.semType!==i.SEMTYPE.MACROMOLECULE)&&l._package.seqHelper.getSeqHandler(e).isFasta()}),p=o.input.int("FASTA line width",{value:60});o.dialog({title:"Save as FASTA"}).add(o.inputs([c,m,p])).onOK(()=>{const t=c.value??[],n=m.value??null,i=p.value??60;n||s.shell.warning("Seq column is mandatory to save as FASTA.");const o=u(t,l._package.seqHelper.getSeqHandler(n),i),r=document.createElement("a");r.setAttribute("href",`data:text/plain;charset=utf-8,${encodeURIComponent(o)}`),r.setAttribute("download",`${e.dataFrame.name}.fasta`),r.click()}).show()}function u(e,t,n=60,i="\n"){const o=[];for(let s=0;s<t.length;s++){const r=e.map(e=>e.get(s).toString()).join("|"),a=h(t.getSplitted(s),n);o.push(`>${r}${i}`);for(const e of a)o.push(`${e}${i}`)}return"".concat(...o)}function h(e,t=60){let n=0;const i=e.length,o=[];for(;n<i;){const i=a().count(n).take(Math.min(e.length-n,t)).map(t=>e.getOriginal(t)).toArray(),s=i.map(e=>e.length>1?`[${e}]`:e).reduce((e,t)=>e+t,"");o.push(s),n+=i.length}return o}},8754(e,t,n){"use strict";n.d(t,{V:()=>u});var i=n(4328),o=n(6077),s=n(2003),r=n(8312),a=n(5553),l=n(966),c=n(330);async function u(e,t,n,u,h,d,m){let p;if(n){const n=await(0,r.Q)(),i=n.getSeqHandler(t);let o,a;i.isHelm()?o=t:(a=t.name,t.name=`__${a}`,o=i.convert(s.Hi.HELM),o.name=a,e.columns.add(o,!1));try{p=await n.helmToAtomicLevel(o,!0,!0,h)}finally{o!==t&&(e.columns.remove(o.name),t.name=a)}}else{if(!(0,l.l)(t,"To Atomic Level",d)[0])return{molCol:null,warnings:["Column is not suitable"]};p=await(0,o.C4)(e,t,h,d,m)}if(p.molCol){const o=(0,c.qj)(e,t.name);p.molCol.name=o,e.columns.add(p.molCol,!0),await(0,a.Qc)(t,p.molCol,h,d,m,n),p.molCol.setTag(".sequence-src-highlight-monomers",String(u)),await i.data.detectSemanticTypes(e)}return p}},4870(e,t,n){"use strict";n.d(t,{Kd:()=>a,Ku:()=>r,me:()=>s});var i=n(4328),o=n(6082);function s(){const e=i.shell.t.columns.bySemTypeAll(o.SEMTYPE.MACROMOLECULE);return null==e?(i.shell.error("Current table does not contain macromolecules"),[]):e}function r(e,t){e.innerHTML="",e.append(t)}function a(e,t,n,i,o){const s=()=>{const o=e.col(t);o&&(o.width=n),i&&(e.props.rowHeight=i)};if(o)return void s();const r=e.onAfterDrawOverlay.subscribe(()=>{r.unsubscribe(),setTimeout(()=>{s()})})}},250(e,t,n){"use strict";n.d(t,{VN:()=>P,n5:()=>C,Ue:()=>S,Tc:()=>E,oP:()=>L,eN:()=>I});var i=n(4328),o=n(7389),s=n(6082),r=n(1757),a=n.n(r),l=n(1991),c=n.n(l),u=n(1858),h=n(2003),d=n(4326);function m(e){var t;return"string"==typeof e||e instanceof String?e:("object"==typeof e||e instanceof Object)&&"$thrownJsError"in e?m(e.$thrownJsError):e instanceof Error?null!==(t=e.stack)&&void 0!==t?t:e.message:e.toString()}var p=n(8070),g=n(7602),f=n(439),y=n(819);var b=n(3328);function w(e,t,n){return Math.abs(e-t)<=n}var v,C,A=n(6307),T=n(6197);HTMLCanvasElement.prototype.getCursorPosition=function(e,t){const n=this.getBoundingClientRect();return new s.Point((e.clientX-n.left)*t,(e.clientY-n.top)*t)},s.Rect.prototype.contains=function(e,t){return this.left<=e&&e<=this.right&&this.top<=t&&t<=this.bottom};class E{rowCount;value;plotValue;valueList=null;valueIdx=0;bounds;constructor(e=0,t){this.value=this.rowCount=e,this.bounds=t}push(e){this.valueList||(this.valueList=new Array(this.rowCount),this.valueIdx=0),this.valueList[this.valueIdx]=e,++this.valueIdx}aggregate(e){this.value=e(this.valueList)??0,this.valueList=null}}class S{pos;name;_label;get label(){return this._label?this._label:this.name}_freqs;sumRowCount=0;sumPlotValue;sumPlotValueForHeight;constructor(e,t,n,i){this.pos=e,this.name=t,this._freqs=n??{},i?.sumRowCount&&(this.sumRowCount=i.sumRowCount),i?.sumValueForHeight&&(this.sumPlotValue=i.sumValueForHeight),i?.label&&(this._label=i.label)}getMonomers(){return Object.keys(this._freqs)}hasMonomer(e){return e in this._freqs}getFreq(e){let t=this._freqs[e];return t||(t=this._freqs[e]=new E),t}aggregate(e){const t=function(e){return t=>{const n=function(e){let t;const n="agg";return t=e instanceof Float32Array?s.Column.fromFloat32Array(n,e):e instanceof Int32Array?s.Column.fromInt32Array(n,e):s.Column.fromList(s.COLUMN_TYPE.FLOAT,n,e),t}(t);return n.aggregate(e)}}(e);for(const[e,n]of Object.entries(this._freqs))n.aggregate(t)}getMinValue(){return Math.min(...Object.values(this._freqs).map(e=>e.value))}calcPlotValue(e){for(const t of Object.values(this._freqs))t.plotValue=t.value-e}calcHeights(e){this.sumPlotValue=0;for(const e of Object.values(this._freqs))this.sumPlotValue+=e.plotValue;if(this.sumPlotValueForHeight=0,e===d.fH.Entropy){const e=Object.keys(this._freqs).length,t=.01*this.sumPlotValue,n=t/e;for(const e of Object.values(this._freqs)){const i=(e.plotValue+n)/(this.sumPlotValue+t);this.sumPlotValueForHeight+=-i*Math.log2(i)}}else if(e===d.fH.full)for(const[e,t]of Object.entries(this._freqs)){const e=t.plotValue/this.sumPlotValue;this.sumPlotValueForHeight+=e}}calcScreen(e,t,n,i,o,r,a,l,c){const u=i===d.fH.Entropy?n*(o-this.sumPlotValueForHeight)/o:n;let h=c*l+(n-u-1);const m=Object.entries(this._freqs).sort((e,t)=>e[0]!==f._S&&t[0]!==f._S?t[1].value-e[1].value:e[0]===f._S&&t[0]===f._S?0:e[0]===f._S?-1:1);for(const[n,i]of m){const n=u*i.plotValue/this.sumPlotValue;i.bounds=new s.Rect((e-t)*l*r,h,a*l,n),h+=n}}render(e,t,n,i,o,s,r){for(const[a,l]of Object.entries(this._freqs))if(a!==f._S){let c=a;const u=l.bounds,d=u.left;let p=y.S$;if(s)try{p=s.getMonomerTextColor(o,a);const e=s.getMonomer((0,T.Y)(o),a);e&&e.symbol!==a&&(c=e.symbol)}catch(e){m(e)}const g=(0,h.zS)(c,r);e.resetTransform(),e.strokeStyle="lightgray",e.lineWidth=1,e.rect(d,u.top,u.width,u.height),e.fillStyle=p,e.textAlign="left",e.font=t;const f=e.measureText(g);e.setTransform(u.width/f.width,0,0,u.height/i,d,u.top),e.fillText(g,0,-n)}}getMonomerAt(e,t){const n=Object.entries(this._freqs).find(([n,i])=>i.bounds.contains(e,t));return n?n[0]:void 0}buildCompositionTable(e,t){if("-"in this._freqs)throw new Error("Unexpected monomer symbol '-'.");return(0,A.F)(Object.assign({},...Object.entries(this._freqs).map(([e,t])=>({[e]:t.rowCount}))),e,t)}}!function(e){e.STYLE="Style",e.BEHAVIOR="Behavior",e.LAYOUT="Layout",e.DATA="Data"}(v||(v={})),function(e){e.sequenceColumnName="sequenceColumnName",e.valueAggrType="valueAggrType",e.valueColumnName="valueColumnName",e.startPositionName="startPositionName",e.endPositionName="endPositionName",e.skipEmptySequences="skipEmptySequences",e.skipEmptyPositions="skipEmptyPositions",e.shrinkEmptyTail="shrinkEmptyTail",e.backgroundColor="backgroundColor",e.positionHeight="positionHeight",e.positionWidth="positionWidth",e.verticalAlignment="verticalAlignment",e.horizontalAlignment="horizontalAlignment",e.fixWidth="fixWidth",e.fitArea="fitArea",e.minHeight="minHeight",e.maxHeight="maxHeight",e.maxMonomerLetters="maxMonomerLetters",e.showPositionLabels="showPositionLabels",e.positionMarginState="positionMarginState",e.positionMargin="positionMargin",e.filterSource="filterSource"}(C||(C={}));const M=d.Fo;var x;!function(e){e[e.None=0]="None",e[e.Render=1]="Render",e[e.Layout=1]="Layout",e[e.Freqs=2]="Freqs"}(x||(x={}));const P=new class{render=20};class L extends s.JsViewer{static residuesSet="nucleotides";viewed=!1;seqHelper;seqHandler;initialized=!1;monomerLib=null;host;msgHost;canvas;slider;textBaseline;seqCol=null;positions=[];visibleSlider=!1;allowResize=!0;turnOfResizeForOneSetValue=!1;sequenceColumnName;valueAggrType;valueColumnName;skipEmptySequences;skipEmptyPositions;positionWidth;_positionWidth;_positionWidthWithMargin;get positionWidthWithMargin(){return this._positionWidthWithMargin}minHeight;backgroundColor=4294967295;maxHeight;maxMonomerLetters;showPositionLabels;positionMarginState;positionMargin=0;_positionMargin;startPositionName;endPositionName;fixWidth;verticalAlignment;horizontalAlignment;fitArea;shrinkEmptyTail;positionHeight;filterSource;positionNames=[];positionLabels=void 0;startPosition=-1;endPosition=-1;error=null;get Length(){return this.skipEmptyPositions?this.positions.length:this.startPosition<=this.endPosition?this.endPosition-this.startPosition+1:0}get positionMarginValue(){return this.positionMarginState===d.mH.AUTO&&!0===this.seqHandler.getAlphabetIsMultichar()||this.positionMarginState===d.mH.ON?this.positionMargin:0}constructor(){super(),this.seqHelper=b._package.seqHelper,this.textBaseline="top",this.seqHandler=null,this.sequenceColumnName=this.string(C.sequenceColumnName,M.sequenceColumnName,{category:v.DATA,semType:s.SEMTYPE.MACROMOLECULE,description:"Column with sequences"});const e=[s.AGG.KEY,s.AGG.PIVOT,s.AGG.MISSING_VALUE_COUNT,s.AGG.SKEW,s.AGG.KURT,s.AGG.SELECTED_ROWS_COUNT],t=Object.values(s.AGG).filter(t=>!e.includes(t));this.valueColumnName=this.string(C.valueColumnName,M.valueColumnName,{category:v.DATA,columnTypeFilter:"numerical",description:"Column with values used in aggregation for position heights"}),this.valueAggrType=this.string(C.valueAggrType,M.valueAggrType,{category:v.DATA,choices:t,description:"Aggregation method for value column"}),this.startPositionName=this.string(C.startPositionName,M.startPositionName,{category:v.DATA,description:"Position or column name for start position. If column with given name is found, its values will be used as start position. If number is supplied, it will be used as start position of WebLogo."}),this.endPositionName=this.string(C.endPositionName,M.endPositionName,{category:v.DATA,description:"Position or column name for end position. If column with given name is found, its values will be used as end position. If number is supplied, it will be used as end position of WebLogo."}),this.skipEmptySequences=this.bool(C.skipEmptySequences,M.skipEmptySequences,{category:v.DATA,description:"Skip sequences which are empty in all positions"}),this.skipEmptyPositions=this.bool(C.skipEmptyPositions,M.skipEmptyPositions,{category:v.DATA,description:"Skip positions which are empty in all sequences"}),this.shrinkEmptyTail=this.bool(C.shrinkEmptyTail,M.shrinkEmptyTail,{category:v.DATA,description:"Skip empty tail (if found for all sequences within a subset) in WebLogo"}),this.backgroundColor=this.int(C.backgroundColor,M.backgroundColor,{category:v.STYLE,description:"Background color of WebLogo canvas"}),this.positionHeight=this.string(C.positionHeight,M.positionHeight,{category:v.STYLE,choices:Object.values(d.fH),description:"Monomer-Position height mode. Entropy of 100%(full height)"}),this._positionWidth=this.positionWidth=this.float(C.positionWidth,M.positionWidth,{category:v.LAYOUT,editor:"slider",min:4,max:100,description:'Width of position in WebLogo. If "Fit Area" is enabled, width will be calculated to fit horizontal space'}),this.verticalAlignment=this.string(C.verticalAlignment,M.verticalAlignment,{category:v.LAYOUT,choices:Object.values(d.Lp)}),this.horizontalAlignment=this.string(C.horizontalAlignment,M.horizontalAlignment,{category:v.LAYOUT,choices:Object.values(d.P4)}),this.fixWidth=this.bool(C.fixWidth,M.fixWidth,{category:v.LAYOUT,userEditable:!1}),this.fitArea=this.bool(C.fitArea,M.fitArea,{category:v.LAYOUT,description:"Fit WebLogo to the horizontal space. Calculates position width as maximum between provided width value and value needed to fit whole horizontal space."}),this.minHeight=this.int(C.minHeight,M.minHeight,{category:v.LAYOUT,editor:"slider",min:10,max:250,description:"Minimum height of WebLogo"}),this.maxHeight=this.int(C.maxHeight,M.maxHeight,{category:v.LAYOUT,editor:"slider",min:25,max:Math.max(window.innerHeight??0,1e3),nullable:!0,description:"Maximum height of WebLogo"}),this.maxMonomerLetters=this.int(C.maxMonomerLetters,M.maxMonomerLetters,{category:v.LAYOUT,editor:"slider",min:1,max:40,description:"Maximum monomer letters to display before shortening"}),this.showPositionLabels=this.bool(C.showPositionLabels,M.showPositionLabels,{category:v.LAYOUT,description:"Show position labels on top of the weblogo"}),this.positionMarginState=this.string(C.positionMarginState,M.positionMarginState,{category:v.LAYOUT,choices:Object.values(d.mH),description:"Calculate optimal margins between positions or turn it on/off"});let n=0;"auto"===this.positionMarginState&&(n=4),this.positionMargin=this.int(C.positionMargin,n,{category:v.LAYOUT,min:0,max:25,description:"Margin between positions in WebLogo"}),this.filterSource=this.string(C.filterSource,M.filterSource,{category:v.BEHAVIOR,choices:Object.values(d.lT),description:"Data source for weblogo. Selected or filtered rows."}),this.slider=o.rangeSlider(0,100,0,20,!1,{style:"barbell"}),this.canvas=o.canvas(),this.canvas.classList.value="bio-wl-canvas",this.canvas.style.width="100%",b.PackageFunctions.getMonomerLibHelper().then(e=>{this.monomerLib=e.getMonomerLib(),this.render(x.Render,"monomerLib"),this.subs.push(this.monomerLib.onChanged.subscribe(()=>{this.render(x.Render,"monomerLib changed")}))}),this.viewSyncer=new g.g(b._package.logger)}static viewerCounter=-1;viewerId=++L.viewerCounter;toLog(){return`WebLogoViewer<${this.viewerId}>`}setData(){const e=`${this.toLog()}.setData()`;b._package.logger.debug(`${e}, in`),this.viewSyncer.sync(`${e}`,async()=>{if(!this.setDataInProgress){this.setDataInProgress=!0;try{this.viewed&&(this.renderRequestSub.unsubscribe(),await this.destroyView(),this.viewed=!1),this.updateSeqCol(),this.updateEditors(),this.viewed||(await this.buildView(),this.viewed=!0)}finally{this.setDataInProgress=!1}}}),b._package.logger.debug(`${e}, out`)}viewSyncer;setDataInProgress=!1;viewSubs=[];async destroyView(){for(const e of this.viewSubs)e.unsubscribe();this.viewSubs=[];const e=this.dataFrame?"data":"null";b._package.logger.debug(`${this.toLog()}.destroyView( dataFrame = ${e} ) start`),this.host.remove(),this.msgHost=void 0,this.host=void 0,b._package.logger.debug(`${this.toLog()}.destroyView() end`)}async buildView(){const e=this.dataFrame?"data":"null";b._package.logger.debug(`${this.toLog()}.buildView( dataFrame = ${e} ) start`),window.devicePixelRatio,this.viewSubs.push(s.debounce(this.renderRequest,P.render).subscribe(this.renderRequestOnDebounce.bind(this))),this.helpUrl="/help/visualize/viewers/web-logo.md",this.msgHost=o.div("No message",{classes:"bio-wl-msg"}),this.msgHost.style.display="none",this.canvas=o.canvas(),this.canvas.style.width="100%",this.slider.root.style.position="absolute",this.slider.root.style.zIndex="999",this.slider.root.style.display="none",this.slider.root.style.height="0.7em",this.visibleSlider=!1,this.host=o.div([this.msgHost,this.canvas],{classes:"bio-wl-host",style:{display:"flex",flexDirection:"row",flexGrow:"0",flexWrap:"wrap"}}),this.root.append(this.host),this.root.append(this.slider.root),this.error&&(this.msgHost.innerText=this.error.message,o.tooltip.bind(this.msgHost,this.error.stack),this.msgHost.style.setProperty("display",null)),this.dataFrame&&(this.viewSubs.push(this.dataFrame.filter.onChanged.subscribe(this.dataFrameFilterOnChanged.bind(this))),this.viewSubs.push(this.dataFrame.selection.onChanged.subscribe(this.dataFrameSelectionOnChanged.bind(this)))),this.viewSubs.push(o.onSizeChanged(this.root).subscribe(this.rootOnSizeChanged.bind(this))),this.viewSubs.push(this.slider.onValuesChanged.subscribe(this.sliderOnValuesChanged.bind(this))),this.viewSubs.push((0,u.fromEvent)(this.canvas,"mousemove").subscribe(this.canvasOnMouseMove.bind(this))),this.viewSubs.push((0,u.fromEvent)(this.canvas,"mousedown").subscribe(this.canvasOnMouseDown.bind(this))),this.viewSubs.push((0,u.fromEvent)(this.canvas,"wheel").subscribe(this.canvasOnWheel.bind(this))),this.render(x.Freqs,"buildView"),b._package.logger.debug(`${this.toLog()}.buildView() end`)}lastSize={width:-1,height:-1};rootOnSizeChanged(e){const t={width:e.target.clientWidth,height:e.target.clientHeight};this.lastSize.width==t.width&&this.lastSize.height==t.height||(b._package.logger.debug(`${this.toLog()}.rootOnSizeChanged(), ${JSON.stringify(t)}, start `),this.render(x.Layout,"rootOnSizeChanged")),this.lastSize=t}updateEditors(){this.props.getProperty(C.valueColumnName).choices=c()(this.dataFrame.columns.numerical).map(e=>e.name).toArray()}updateSeqCol(){if(this.dataFrame&&(this.seqCol=this.sequenceColumnName?this.dataFrame.col(this.sequenceColumnName):null,null==this.seqCol&&(this.seqCol=(0,h.mn)(this.dataFrame),this.sequenceColumnName=this.seqCol?this.seqCol.name:null),this.seqCol)){try{this.seqHandler=this.seqHelper.getSeqHandler(this.seqCol),this.render(x.Freqs,"updateSeqCol()"),this.error=null}catch(e){throw this.seqCol=null,this.error=e instanceof Error?e:new Error(e.toString()),e}this.seqCol||(this.seqHandler=null,this.positionNames=[],this.positionLabels=[],this.startPosition=-1,this.endPosition=-1)}}getFilter(){let e;switch(this.filterSource){case d.lT.Filtered:e=this.dataFrame.filter;break;case d.lT.Selected:e=0===this.dataFrame.selection.trueCount?this.dataFrame.filter:this.dataFrame.selection}return e}setSliderVisibility(e){e?(this.slider.root.style.display="inherit",this.visibleSlider=!0):(this.slider.root.style.display="none",this.visibleSlider=!1)}calcLayout(e){this.host&&this.canvas&&this.slider&&(this.host.classList.remove("bio-wl-fixWidth","bio-wl-fitArea"),this.canvas.classList.remove("bio-wl-fixWidth","bio-wl-fitArea"),this._positionWidth=this.positionWidth,this._positionMargin=this.positionMargin,this._positionWidthWithMargin=this._positionWidth+this.positionMarginValue,this.fixWidth?this.calcLayoutFixWidth(e):this.calcLayoutNoFitArea(e),this.slider.root.style.width=`${this.host.clientWidth}px`)}calcLayoutFixWidth(e){if(!this.host||!this.canvas||!this.slider)return;this.host.classList.add("bio-wl-fixWidth"),this.canvas.classList.add("bio-wl-fitArea");const t=this._positionWidthWithMargin*this.Length,n=Math.min(Math.max(this.minHeight,this.root.clientHeight),this.maxHeight??this.root.clientHeight);this.host.style.justifyContent=d.P4.LEFT,this.host.style.removeProperty("margin-left"),this.host.style.removeProperty("margin-top"),this.host.style.width=this.canvas.style.width=`${t}px`,this.host.style.height=this.canvas.style.height=`${n}px`,this.host.style.left=this.canvas.style.left="0",this.host.style.top=this.canvas.style.top="0",this.host.style.setProperty("overflow","hidden","important"),this.slider.root.style.display="none",this.slider.setValues(0,Math.max(0,this.Length-1),0,Math.max(0,this.Length-1)),this.canvas.width=t*e,this.canvas.height=n*e}calcLayoutNoFitArea(e){if(!this.host||!this.canvas||!this.slider)return;let t=this._positionWidthWithMargin*this.Length,n=Math.min(this.root.clientWidth,t);this.fitArea&&t<this.root.clientWidth&&(this._positionWidth=Math.floor(this._positionWidth*this.root.clientWidth/t),this._positionWidthWithMargin=this._positionWidth+this.positionMarginValue,t=this._positionWidthWithMargin*this.Length,n=Math.min(this.root.clientWidth,t));const i=Math.min(Math.max(this.minHeight,this.root.clientHeight),this.maxHeight??this.root.clientHeight);this.canvas.style.width=`${n}px`,this.canvas.style.height=`${i}px`,this.host.style.width=`${this.root.clientWidth}px`,this.host.style.height=`${this.root.clientHeight}px`,this.host.style.justifyContent=this.horizontalAlignment,this.host.style.alignContent=this.verticalAlignment===d.Lp.TOP?"start":this.verticalAlignment===d.Lp.MIDDLE?"center":this.verticalAlignment===d.Lp.BOTTOM?"end":"inherit",this.root.clientHeight<this.minHeight&&(this.host.style.alignContent="start",this.host.style.width=`${n+8}px`);const o=t>n;if(this.setSliderVisibility(o),o){this.slider.root.style.removeProperty("display"),this.host.style.justifyContent="left",this.host.style.height=this.root.clientHeight-this.slider.root.offsetHeight+"px",this.canvas.style.height=i-this.slider.root.offsetHeight+"px",this.slider.root.style.top=`${this.host.offsetHeight}px`;let e=Math.min(Math.max(0,this.slider.min),this.Length-.001),t=Math.min(Math.max(0,this.slider.max),this.Length-.001);const n=this.canvas.clientWidth/this._positionWidthWithMargin;t=Math.min(Math.max(e,0)+n,this.Length-.001),e=Math.max(0,Math.min(t,this.Length-.001)-n),this.safeUpdateSlider(0,Math.max(this.Length-.001),e,t)}else this.safeUpdateSlider(0,Math.max(0,this.Length-.001),0,Math.max(0,this.Length-.001));this.canvas.width=n*e,this.canvas.height=i*e}calcLayoutFitArea(e){if(!this.host||!this.canvas||!this.slider)return;const t=this._positionWidth*this.Length,n=Math.min(Math.max(this.minHeight,this.root.clientHeight),this.maxHeight??this.root.clientHeight),i=t>0?(this.root.clientWidth-this.positionMarginValue*this.Length)/t:0,o=this.root.clientHeight/n,s=Math.max(1,Math.min(i,o));this._positionWidth=this.positionWidth*s,this._positionWidthWithMargin=this._positionWidth+this.positionMarginValue;const r=(this._positionWidth+this.positionMarginValue)*this.Length,a=s*n,l=Math.min(this.root.clientWidth,r);this.canvas.style.width=`${l}px`,this.canvas.style.height=`${a}px`,this.host.style.width=`${l}px`,this.host.style.height=`${this.root.clientHeight}px`,this.host.style.justifyContent=this.horizontalAlignment,this.host.style.alignContent=this.verticalAlignment===d.Lp.TOP?"start":this.verticalAlignment===d.Lp.MIDDLE?"center":this.verticalAlignment===d.Lp.BOTTOM?"end":"inherit",this.root.clientHeight<this.minHeight&&(this.host.style.alignContent="start",this.host.style.width=`${l+6}px`),this.host.style.width=`${this.host}px`;const c=r>l;if(this.setSliderVisibility(c),c){this.slider.root.style.removeProperty("display"),this.host.style.justifyContent="left",this.host.style.height=this.root.clientHeight-this.slider.root.offsetHeight+"px",this.slider.root.style.top=`${this.host.offsetHeight}px`;let e=Math.min(Math.max(0,this.slider.min),this.Length-.001),t=Math.min(Math.max(0,this.slider.max),this.Length-.001);const n=this.root.clientWidth/this._positionWidthWithMargin;t=Math.min(Math.max(e,0)+n,this.Length-.001),e=Math.max(0,Math.min(t,this.Length-.001)-n),this.safeUpdateSlider(0,Math.max(0,this.Length-.001),e,t)}else this.safeUpdateSlider(0,Math.max(0,this.Length-.001),0,Math.max(0,this.Length-.001));this.canvas.width=l*e,this.canvas.height=a*e}safeUpdateSlider(e,t,n,i){w(e,this.slider.minRange,.1)&&w(t,this.slider.maxRange,.1)&&w(n,this.slider.min,.1)&&w(i,this.slider.max,.1)||this.slider.setValues(e,t,n,i)}onPropertyChanged(e){switch(super.onPropertyChanged(e),e.name){case C.sequenceColumnName:this.updateSeqCol();break;case C.sequenceColumnName:case C.startPositionName:case C.endPositionName:case C.filterSource:case C.shrinkEmptyTail:case C.skipEmptyPositions:case C.positionHeight:case C.valueColumnName:case C.valueAggrType:this.render(x.Freqs,`onPropertyChanged( ${e.name} )`);break;case C.minHeight:case C.maxHeight:case C.maxMonomerLetters:case C.positionWidth:case C.showPositionLabels:case C.fixWidth:case C.fitArea:case C.horizontalAlignment:case C.verticalAlignment:case C.positionMargin:case C.positionMarginState:this.render(x.Layout,`onPropertyChanged(${e.name})`);break;case C.backgroundColor:this.render(x.Render,`onPropertyChanged(${e.name})`)}}onTableAttached(){b._package.logger.debug(`${this.toLog()}.onTableAttached(), `),super.onTableAttached(),this.setData()}detach(){const e=`${this.toLog()}.detach()`;b._package.logger.debug(`${e}, in`);const t=super.detach.bind(this);this.viewSyncer.sync(`${e}`,async()=>{this.setDataInProgress||(this.viewed&&(await this.destroyView(),this.viewed=!1),t())}),b._package.logger.debug(`${e}, out`)}_onSizeChanged=new u.Subject;get onSizeChanged(){return this._onSizeChanged}_onFreqsCalculated=new u.Subject;get onFreqsCalculated(){return this._onFreqsCalculated}_onLayoutCalculated=new u.Subject;get onLayoutCalculated(){return this._onLayoutCalculated}getMonomer(e,t){const n=e.x,i=Math.floor(e.x/(this._positionWidthWithMargin*t)+Math.floor(this.slider.min)),o=this.positions[i];if(!o)return[null,null,null];const s=o.getMonomerAt(n,e.y);return null==s?[o,null,null]:[o,s,o.getFreq(s)]}_nullSequence(e="X"){return this.skipEmptySequences?"":new Array(this.Length).fill(e).join("")}_removeEmptyPositions(){this.skipEmptyPositions&&(this.positions=c()(this.positions).filter(e=>!e.hasMonomer(f._S)||e.getFreq(f._S).rowCount!==e.sumRowCount).toArray())}requestedRenderLevel=x.Freqs;renderRequest=new u.Subject;renderRequestSub;render(e,t){b._package.logger.debug(`${this.toLog()}.render( recalcLevelVal=${e}, reason='${t}' )`),this.requestedRenderLevel=Math.max(this.requestedRenderLevel,e),this.renderRequest.next(this.requestedRenderLevel)}async renderInt(e){if(b._package.logger.debug(`${this.toLog()}.render.renderInt( renderLevel=${e} ), start `),this.msgHost&&(this.msgHost.style.display="none"),!this.seqCol||!this.dataFrame||null==this.host||null==this.slider)return;const t=window.devicePixelRatio,n=this.showPositionLabels?12:0;if(e>=x.Freqs&&(()=>{if(b._package.logger.debug(`${this.toLog()}.render.calculateFreqsInt(), start `),!this.host||!this.seqCol||!this.dataFrame)return;const e=this.seqCol.getTag(h.gp.positionNames),t=this.seqCol.getTag(h.gp.positionLabels);let n;!e&&this.endPositionName&&/\d+/.test(this.endPositionName)?n=Number(this.endPositionName):e&&this.endPositionName&&(n=e.split(h.z1).indexOf(this.endPositionName),n=-1!==n?n:void 0);const i=this.getFilter(),o=0===i.trueCount?this.seqHandler.maxLength:c().count(0).take(this.seqHandler.length).map(e=>{const t=this.seqHandler.getSplitted(e,n);return i.get(e)&&t?t.length:0}).reduce((e,t)=>Math.max(e,t),0);this.positionNames=e?e.split(h.z1).map(e=>e.trim()):[...Array(o).keys()].map(e=>`${e+1}`),this.positionLabels=t?t.split(h.z1).map(e=>e.trim()):void 0,this.startPosition=this.startPositionName&&this.positionNames&&this.positionNames.includes(this.startPositionName)?this.positionNames.indexOf(this.startPositionName):0,this.endPosition=this.endPositionName&&this.positionNames&&this.positionNames.includes(this.endPositionName)?this.positionNames.indexOf(this.endPositionName):o-1;const r=this.startPosition<=this.endPosition?this.endPosition-this.startPosition+1:0;this.seqHandler=this.seqHelper.getSeqHandler(this.seqCol);const a=this.startPosition<=this.endPosition?this.endPosition-this.startPosition+1:0;this.positions=new Array(a);for(let e=0;e<r;e++){const t=this.positionNames[this.startPosition+e],n=this.positionLabels?this.positionLabels[this.startPosition+e]:void 0;this.positions[e]=new S(this.startPosition+e,t,{},{label:n})}this.dataFrame.rowCount;const l=i.getSelectedIndexes();for(let e=0;e<r;++e){for(const t of l){const n=this.seqHandler.getSplitted(t),i=e+this.startPosition<n.length?n.getCanonical(this.startPosition+e):this.seqHandler.defaultGapOriginal,o=this.seqHandler.defaultGapOriginal===i?f._S:i,s=this.positions[e],r=s.getFreq(o);++s.sumRowCount,r.value=++r.rowCount}if(this.valueAggrType===s.AGG.TOTAL_COUNT)continue;let t=null;try{t=this.dataFrame.getCol(this.valueColumnName),t.matches("numerical")||(t=null)}catch{t=null}if(t){for(const n of l){const i=this.seqHandler.getSplitted(n),o=e+this.startPosition<i.length?i.getCanonical(this.startPosition+e):this.seqHandler.defaultGapOriginal,s=this.seqHandler.defaultGapOriginal===o?f._S:o,r=t.get(n);this.positions[e].getFreq(s).push(r)}this.positions[e].aggregate(this.valueAggrType)}}const u=this.valueAggrType===s.AGG.TOTAL_COUNT?0:Math.min(0,Math.min(...this.positions.map(e=>e.getMinValue())));for(let e=0;e<r;++e)this.positions[e].calcPlotValue(u),this.positions[e].calcHeights(this.positionHeight);this._removeEmptyPositions(),this._onFreqsCalculated.next()})(),this.calcLayout(t),-1===this.startPosition)return;const o=Math.max(Math.floor(this.slider.min),0),r=Math.min(this.positions.length-1,Math.floor(this.slider.max));e>=x.Layout&&((e,t,n,o)=>{b._package.logger.debug(`${this.toLog()}.render.calculateLayoutInt(), start `);const r=this.canvas.height-o*n;let a;if(this.valueAggrType===s.AGG.TOTAL_COUNT){const e=this.seqHandler.getAlphabetSize();this.positionHeight==d.fH.Entropy&&null==e&&i.shell.error("WebLogo: alphabet is undefined."),a=Math.log2(e)}else a=Math.max(...c().count(e).takeWhile(e=>e<=t).map(e=>this.positions[e].sumPlotValueForHeight));for(let i=e;i<=t;++i)i in this.positions?this.positions[i].calcScreen(i,this.slider.min,r,this.positionHeight,a,this._positionWidthWithMargin,this._positionWidth,n,o):b._package.logger.warning(`${this.toLog()}.render.calculateLayoutInt() this.positions.length = ${this.positions.length}, jPos = ${i}`);b._package.logger.debug(`${this.toLog()}.render.calculateLayoutInt(), end `),this._onLayoutCalculated.next()})(o,r,window.devicePixelRatio,n);const a=this.canvas.getContext("2d");if(a){a.save();try{this.Length,a.resetTransform(),a.fillStyle=function(e){const t=s.Color.a(e);return`#${(16777215&e).toString(16).padStart(6,"0")}`+t.toString(16).padStart(2,"0")}(this.backgroundColor),a.fillRect(0,0,this.canvas.width,this.canvas.height),a.textBaseline=this.textBaseline;const e=10*t;a.resetTransform(),a.fillStyle="black",a.textAlign="center",a.font=`${e.toFixed(1)}px Roboto, Roboto Local, sans-serif`,n>0&&this.positions.length>0&&function(e,t,n,i,o,s,r,a){e.save();try{e.textAlign="center";let l=null,c=null;for(let t=Math.floor(r);t<=Math.floor(a);t++){const n=s[t],i=e.measureText(n.name),o=i.actualBoundingBoxDescent-i.actualBoundingBoxAscent;l=null==l?i.width:Math.max(l,i.width),c=null==c?o:Math.max(c,o)}const u=l<i*t-2?1:(i*t-2)/l;for(let l=Math.floor(r);l<=Math.floor(a);l++){const a=s[l],h=(l-r)*n*t+i*t/2,d=(o*t-c)/2;e.setTransform(u,0,0,1,h,d),e.measureText(a.label),e.fillText(a.label,0,0)}}finally{e.restore()}}(a,t,this._positionWidthWithMargin,this._positionWidth,n,this.positions,this.slider.min,this.slider.max);const i="16px Roboto, Roboto Local, sans-serif",l=.25,c=12.2,u=this.seqHandler.defaultBiotype;for(let e=o;e<=r;e++)this.positions[e].render(a,i,l,c,u,this.monomerLib,this.maxMonomerLetters)}finally{a.restore()}b._package.logger.debug(`${this.toLog()}.render.renderInt( recalcLevel=${e} ), end`)}}renderRequestOnDebounce(e){const t=`${this.toLog()}.renderRequestOnDebounce()`;"HTML"!==a()(this.root).offsetParent().get()[0]?.tagName?(this.requestedRenderLevel=x.None,this.viewSyncer.sync(t,async()=>{await this.renderInt(e)})):b._package.logger.warning(`${t}, $(this.root).offsetParent() is the 'HTML' tag.`)}_lastWidth;_lastHeight;sliderOnValuesChanged(e){try{const e={minRange:this.slider.minRange,min:this.slider.min,max:this.slider.max,maxRange:this.slider.maxRange};if(this.canvas&&this.canvas.offsetWidth>0&&(this._positionWidthWithMargin??0)>0){const t=e.max-e.min,n=this.canvas.offsetWidth/t-this.positionMarginValue;w(n,this.positionWidth,.1)?this.render(x.Layout,"sliderOnValuesChanged"):this.getProperty(C.positionWidth)?.set(this,n)}}catch(e){const t=m(e);b._package.logger.error(`${this.toLog()}.sliderOnValuesChanged() error:\n`+t)}}dataFrameFilterOnChanged(e){b._package.logger.debug(`${this.toLog()}.dataFrameFilterChanged()`);try{this.filterSource===d.lT.Filtered&&this.render(x.Freqs,"dataFrameFilterOnChanged")}catch(e){const t=m(e);b._package.logger.error(`${this.toLog()}.dataFrameFilterOnChanged() error:\n`+t)}}dataFrameSelectionOnChanged(e){b._package.logger.debug(`${this.toLog()}.dataFrameSelectionOnChanged()`);try{this.filterSource===d.lT.Selected&&this.render(x.Freqs,"dataFrameSelectionOnChanged")}catch(e){const t=m(e);b._package.logger.error(`${this.toLog()}.dataFrameSelectionOnChanged() error:\n`+t)}}canvasOnMouseMove(e){if(!this.monomerLib||!this.seqHandler)return;const t=window.devicePixelRatio;try{const n=e,i=this.canvas.getCursorPosition(n,t),[r,a]=this.getMonomer(i,t),l=this.showPositionLabels?12*t:0;if(null!==r&&null==a&&0<=i.y&&i.y<=l){const e=[o.divText(`Position ${r.label}`)];if(this.valueAggrType===s.AGG.TOTAL_COUNT){const t=this.seqHandler.defaultBiotype;e.push(r.buildCompositionTable(t,this.monomerLib))}const t=o.divV(e);t.style.maxHeight="80vh",o.tooltip.show(t,n.x+16,n.y+16)}else if(null!==r&&a&&this.dataFrame&&this.seqCol&&this.seqHandler){const e=r.getFreq(a),t=[o.div(`${a}`),o.div(`${e.rowCount} rows`)];this.valueAggrType!==s.AGG.TOTAL_COUNT&&t.push(o.div(`${this.valueAggrType}: ${e.value.toFixed(3)}`));const i=o.divV(t);o.tooltip.show(i,n.x+16,n.y+16)}else o.tooltip.hide()}catch(e){const t=m(e);b._package.logger.error(`${this.toLog()}.canvasOnMouseMove() error:\n`+t)}}canvasOnMouseDown(e){try{const t=e,n=window.devicePixelRatio,[i,o]=this.getMonomer(this.canvas.getCursorPosition(t,n),n);if(null!==i&&null!==o&&this.dataFrame&&this.seqCol&&this.seqHandler){const e=s.BitSet.create(this.dataFrame.selection.length,e=>function(e,t,n,i,o,s){const r=t.getSplitted(i),a=s.pos<r.length?r.getCanonical(s.pos):null;return null!==a&&a===o}(this.dataFrame,this.seqHandler,this.getFilter(),e,o,i));this.dataFrame.selection.init(t=>e.get(t))}}catch(e){const t=m(e);b._package.logger.error(`${this.toLog()}.canvasOnMouseDown() error:\n`+t)}}canvasOnWheel(e){const t=window.devicePixelRatio;try{if(!this.visibleSlider)return;const n=this.canvas.width/(this._positionWidthWithMargin*t),i=e.deltaY/100*Math.max(Math.floor(n/5),1);this.slider.scrollBy(this.slider.min+i)}catch(e){const t=m(e);b._package.logger.error(`${this.toLog()}.canvasOnWheel() error:\n`+t)}}_onRendered=new u.Subject;get onRendered(){return this._onRendered}invalidate(e){const t=`invalidate(${e?` <- ${e} `:""})`,n=`${this.toLog()}.${t}`;this.render(x.None,t),this.viewSyncer.sync(`${n}`,async()=>{this._onRendered.next()})}async awaitRendered(e=5e3){await(0,p.PE)(this.onRendered,()=>{},()=>{this.invalidate()},e);const t=this.viewSyncer.resetErrors();if(t.length>0)throw t[0]}}function I(e,t,n,i,o){let s=0,r=-1;for(;-1!=(r=n.findNext(r,!0));){const e=t.getSplitted(r),n=o.pos,a=n<e.length?e.getCanonical(n):null;null!==a&&a===i&&s++}return s}},1687(e,t,n){"use strict";n.d(t,{_i:()=>E,AR:()=>T});var i=n(7389),o=n(6082),s=n(4328),r=n(1991),a=n.n(r),l=n(1858),c=n(2003),u=n(8070),h=n(7602),d=n(4954),m=n(4574),p=n(1757),g=n.n(p),f=n(9124),y=n(9192),b=n(4870),w=n(3328);class v extends m.O{seqHelper;emptyProps=new m.n("",void 0,w._package.logger);helmEditor;_filterPanel=i.div("",{style:{cursor:"pointer"}});logger;static viewerCounter=-1;viewerId=++v.viewerCounter;viewerToLog(){return`HelmBioFilter<${this.viewerId}>`}get type(){return"HelmBioFilter"}constructor(e){super(),this.seqHelper=e,this.logger=w._package.logger}viewSubs=[];async detach(){await super.detach();for(const e of this.viewSubs)e.unsubscribe()}async attach(){this.viewerToLog();try{const e=await(0,f.b2)();let t,n;this.helmEditor=e.createHelmWebEditor(),this.logger.warning("TEST: HelmBioFilter.init().sync() waitForElementInDom waiting..."),await i.tools.waitForElementInDom(this._filterPanel),this.logger.warning("TEST: HelmBioFilter.init().sync() waitForElementInDom ready"),this.updateFilterPanel(),this.viewSubs.push((0,l.fromEvent)(this._filterPanel,"click").subscribe(()=>{t=i.div(),n=e.createWebEditorApp(t,this.props.substructure),i.dialog({showHeader:!1,showFooter:!0}).add(t).onOK(()=>{try{const e=n.canvas.getHelm(!0).replace(/<\/span>/g,"").replace(/<span style='background:#bbf;'>/g,"");this.props=new m.n(e,void 0,w._package.logger)}catch(e){this.logger.error(e)}finally{g()(t).empty(),t=null,n=null}}).onCancel(()=>{g()(t).empty(),t=null,n=null}).show({modal:!0,fullScreen:!0})})),this.viewSubs.push(i.onSizeChanged(this._filterPanel).subscribe(e=>{try{if(n){const e=n.canvas.getHelm(!0).replace(/<\/span>/g,"").replace(/<span style='background:#bbf;'>/g,"");this.updateFilterPanel(e)}}catch(e){const[t,n]=(0,y.AP)(e);this.logger.error(t,void 0,n)}}))}catch(e){const[t,n]=(0,y.AP)(e),o=this._filterPanel;o.innerText="error",o.classList.add("d4-error"),i.tooltip.bind(o,t)}}applyProps(){this.helmEditor&&this.updateFilterPanel(this.props.substructure)}get filterPanel(){return this._filterPanel}updateFilterPanel(e){if(!this.helmEditor)throw new Error("helmEditor is not created, the filter is not in dom yet");const t=this._filterPanel.parentElement.clientWidth<100?100:this._filterPanel.parentElement.clientWidth,n=t/2;if(e)(0,b.Ku)(this._filterPanel,this.helmEditor.host),this.helmEditor.editor.setHelm(e),this.helmEditor.resizeEditor(t,n);else{const e=i.divText("Click to edit","helm-substructure-filter");(0,b.Ku)(this._filterPanel,e)}}async substructureSearch(e){const t=`${this.viewerToLog()}.substructureSearch( column = <${e.name}> )`;w._package.logger.debug(`${t}, start`);try{return await o.delay(10),await(0,d.if)(this.props.substructure,e,this.seqHelper)}finally{w._package.logger.debug(`${t}, end`)}}}const C="bio-substructure-filter";class A{props;filterId;dataFrameId;columnName;bitset;constructor(e,t,n,i,o){this.props=e,this.filterId=t,this.dataFrameId=n,this.columnName=i,this.bitset=o}}class T extends m.n{separator;constructor(e,t,n){super(e,!1,n),this.separator=t,this.readOnly=!0}}class E extends o.Filter{seqHelper;logger;bioFilter=null;bitset=null;loader;notation=void 0;filterSyncer;get calculating(){return"initial"==this.loader.style.display}set calculating(e){this.loader.style.display=e?"initial":"none"}get filterSummary(){return this.bioFilter?.filterSummary??""}get isFiltering(){return super.isFiltering&&(this.bioFilter?.isFiltering??!1)}get isReadyToApplyFilter(){return!this.calculating&&null!=this.bitset}get debounceTime(){if(null==this.column)return 1e3;const e=this.column.length;return e<500?0:e>1e4?1e3:Math.floor((e-500)/9500*1e3)}constructor(e,t){super(),this.seqHelper=e,this.logger=t,this.root=i.divV([]),this.loader=i.loader(),this.calculating=!1,this.filterSyncer=new h.g(this.logger)}static filterCounter=-1;filterId=++E.filterCounter;filterToLog(){return`BioSubstructureFilter<${this.filterId}>`}viewSubs=[];attach(e){const t=super.attach.bind(this),n=`${this.filterToLog()}.attach()`;this.filterSyncer.sync(n,async()=>{e&&await e.meta.detectSemanticTypes(),t(e),this.column||(this.columnName?this.column=this.dataFrame.getCol(this.columnName):this.column=e.columns.bySemType(o.SEMTYPE.MACROMOLECULE)),this.seqHelper.getSeqHandler(this.column),this.columnName??=this.column?.name,this.notation??=this.column?.meta.units,this.bioFilter=this.notation===c.Hi.FASTA?new S:this.notation===c.Hi.SEPARATOR?new M(this.column.getTag(c.gp.separator)):new v(this.seqHelper),this.root.appendChild(this.bioFilter.filterPanel),this.root.appendChild(this.loader),await this.bioFilter.attach(),this.viewSubs.push(o.debounce(this.bioFilter.onChanged,this.debounceTime).subscribe(this.bioFilterOnChangedDebounced.bind(this))),this.viewSubs.push(s.events.onResetFilterRequest.subscribe(this.grokEventsOnResetFilterRequest.bind(this))),this.viewSubs.push(s.events.onCustomEvent(C).subscribe(this.filterOnSync.bind(this)))})}detach(){const e=super.detach.bind(this),t=`${this.filterToLog()}.detach()`;this.filterSyncer.sync(t,async()=>{for(const e of this.viewSubs)e.unsubscribe();this.viewSubs=[],e(),this.bioFilter&&this.bioFilter.detach(),this.bioFilter=null})}filterOnSync(e){e.filterId!==this.filterId&&this.bioFilter&&e.dataFrameId===this.dataFrame.id&&e.columnName===this.columnName&&(this.bioFilter.props=e.props)}applyFilter(){const e=`${this.filterToLog()}.applyFilter()`;this.logger.debug(`${e}, IN`),this.bitset&&!this.isDetached&&this.dataFrame?.filter.and(this.bitset)}saveState(){const e=`${this.filterToLog()}.saveState()`,t=super.saveState();return this.logger.debug(`${e}, super.state = ${JSON.stringify(t)}`),this.bioFilter&&(t.props=this.bioFilter.saveProps()),t}applyState(e){const t=`${this.filterToLog()}.applyState()`;super.applyState(e),this.filterSyncer.sync(t,async()=>{e.props&&this.bioFilter&&(this.bioFilter.props=o.toJs(e.props??{}))})}fireFilterSync(){const e=`${this.filterToLog()}.fireFilterSync()`;this.logger.debug(`${e}, bioFilter = ${this.bioFilter?this.bioFilter.constructor.name:"null"}`+(this.bioFilter?`, props = ${JSON.stringify(this.bioFilter.saveProps())}`:"")),this.bioFilter&&s.events.fireCustomEvent(C,new A(this.bioFilter.props,this.filterId,this.dataFrame.id,this.columnName,this.bitset))}bioFilterOnChangedDebounced(){if(!this.dataFrame)return;const e=`${this.filterToLog()}.bioFilterOnChangedDebounced()`;if(this.logger.debug(`${e}, start, isFiltering = ${this.isFiltering}, props = ${this.bioFilter?JSON.stringify(this.bioFilter?.saveProps()):"null"}`),!this.isFiltering)return this.bitset=null,void this.dataFrame.rows.requestFilter();a()(this.dataFrame.rows.filters).has(`${this.columnName}: ${this.filterSummary}`)||this.filterSyncer.sync(e,async()=>{this.calculating=!0;try{this.logger.debug(`${e}, before substructureSearch`),this.bitset=await(this.bioFilter?.substructureSearch(this.column)),this.logger.debug(`${e}, after substructureSearch`),this.calculating=!1,this.fireFilterSync(),this.dataFrame?.rows.requestFilter()}finally{this.calculating=!1,this.logger.debug(`${e}, end`)}})}grokEventsOnResetFilterRequest(){const e=`${this.filterToLog()}.grokEventsOnResetFilterRequest()`;this.logger.debug(`${e}`),this.bioFilter?.resetFilter()}_onRendered=new l.Subject;get onRendered(){return this._onRendered}invalidate(e){const t=`${this.filterToLog()}.invalidate(${e?` <- ${e} `:""})`;this.filterSyncer.sync(t,async()=>{this._onRendered.next()})}async awaitRendered(e=1e4){const t=`awaitRendered( ${e} )`,n=`${this.filterToLog()}.${t}`;await o.delay(10),await(0,u.PE)(this.onRendered,()=>{this.logger.debug(`${n}, _onRendered event caught`)},()=>{this.invalidate(t)},e,`${n} timeout`);const i=this.filterSyncer.resetErrors();if(i.length>0)throw i[0]}}class S extends m.O{emptyProps=new m.n("",void 0,w._package.logger);substructureInput;get type(){return"FastaBioFilter"}constructor(){super(),this.substructureInput=i.input.string("",{value:"",onValueChanged:e=>{window.setTimeout(()=>{this.props=new m.n(e,void 0,w._package.logger),this._propsChanging||this.onChanged.next()},0)},placeholder:"Substructure"})}applyProps(){this.substructureInput.value!==this.props.substructure&&(this.substructureInput.value=this.props.substructure)}get filterPanel(){return this.substructureInput.root}get isFiltering(){return""!==this.substructureInput.value}async substructureSearch(e){return(0,d.nI)(this.props.substructure,e)}async attach(){}async detach(){await super.detach()}}class M extends m.O{emptyProps=new T("",void 0,w._package.logger);substructureInput;separatorInput;colSeparator="";get type(){return"SeparatorBioFilter"}constructor(e){super(),this.substructureInput=i.input.string("",{value:"",onValueChanged:e=>{this.props=new T(e,this.props.separator,w._package.logger),setTimeout(()=>{this._propsChanging||this.onChanged.next()})},placeholder:"Substructure"}),this.separatorInput=i.input.string("",{value:this.colSeparator=e,onValueChanged:e=>{const t=e||"";this.props=new T(this.props.substructure,t,w._package.logger),setTimeout(()=>{this._propsChanging||this.onChanged.next()})},placeholder:"Separator"})}applyProps(){this.substructureInput.value!==this.props.substructure&&(this.substructureInput.value=this.props.substructure);const e=this.props.separator??this.colSeparator;this.separatorInput.value!==e&&(this.separatorInput.value=e)}get filterSummary(){return this.props.separator?this.props.separator:this.colSeparator,`${this.props.substructure}, {sep}`}get isFiltering(){return""!==this.props.substructure}resetFilter(){this.props=new T("",void 0,w._package.logger)}get filterPanel(){return i.divV([this.substructureInput.root,this.separatorInput.root])}get substructure(){return this.separatorInput.value&&this.separatorInput.value!==this.colSeparator?this.substructureInput.value.replaceAll(this.separatorInput.value,this.colSeparator):this.substructureInput.value}set substructure(e){this.substructureInput.value=e}async substructureSearch(e){return(0,d.nI)(this.substructure,e,this.colSeparator)}async attach(){}async detach(){await super.detach()}}},1757(e){"use strict";e.exports=$},6082(e){"use strict";e.exports=DG},4328(e){"use strict";e.exports=grok},1858(e){"use strict";e.exports=rxjs},9713(e){"use strict";e.exports=rxjs.operators},7389(e){"use strict";e.exports=ui},1991(e){"use strict";e.exports=wu},8343(e,t,n){"use strict";const{normalizeIPv6:i,normalizeIPv4:o,removeDotSegments:s,recomposeAuthority:r,normalizeComponentEncoding:a}=n(4834),l=n(343);function c(e,t,n,i){const o={};return i||(e=m(u(e,n),n),t=m(u(t,n),n)),!(n=n||{}).tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=s(t.path||""),o.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=s(t.path||""),o.query=t.query):(t.path?("/"===t.path.charAt(0)?o.path=s(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path:o.path="/"+t.path,o.path=s(o.path)),o.query=t.query):(o.path=e.path,void 0!==t.query?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function u(e,t){const n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},i=Object.assign({},t),o=[],a=l[(i.scheme||n.scheme||"").toLowerCase()];a&&a.serialize&&a.serialize(n,i),void 0!==n.path&&(i.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),void 0!==n.scheme&&(n.path=n.path.split("%3A").join(":")))),"suffix"!==i.reference&&n.scheme&&o.push(n.scheme,":");const c=r(n);if(void 0!==c&&("suffix"!==i.reference&&o.push("//"),o.push(c),n.path&&"/"!==n.path.charAt(0)&&o.push("/")),void 0!==n.path){let e=n.path;i.absolutePath||a&&a.absolutePath||(e=s(e)),void 0===c&&(e=e.replace(/^\/\//u,"/%2F")),o.push(e)}return void 0!==n.query&&o.push("?",n.query),void 0!==n.fragment&&o.push("#",n.fragment),o.join("")}const h=Array.from({length:127},(e,t)=>/[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(t))),d=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function m(e,t){const n=Object.assign({},t),s={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},r=-1!==e.indexOf("%");let a=!1;"suffix"===n.reference&&(e=(n.scheme?n.scheme+":":"")+"//"+e);const c=e.match(d);if(c){if(s.scheme=c[1],s.userinfo=c[3],s.host=c[4],s.port=parseInt(c[5],10),s.path=c[6]||"",s.query=c[7],s.fragment=c[8],isNaN(s.port)&&(s.port=c[5]),s.host){const e=o(s.host);if(!1===e.isIPV4){const t=i(e.host);s.host=t.host.toLowerCase(),a=t.isIPV6}else s.host=e.host,a=!0}void 0!==s.scheme||void 0!==s.userinfo||void 0!==s.host||void 0!==s.port||void 0!==s.query||s.path?void 0===s.scheme?s.reference="relative":void 0===s.fragment?s.reference="absolute":s.reference="uri":s.reference="same-document",n.reference&&"suffix"!==n.reference&&n.reference!==s.reference&&(s.error=s.error||"URI is not a "+n.reference+" reference.");const e=l[(n.scheme||s.scheme||"").toLowerCase()];if(!(n.unicodeSupport||e&&e.unicodeSupport)&&s.host&&(n.domainHost||e&&e.domainHost)&&!1===a&&function(e){let t=0;for(let n=0,i=e.length;n<i;++n)if(t=e.charCodeAt(n),t>126||h[t])return!0;return!1}(s.host))try{s.host=URL.domainToASCII(s.host.toLowerCase())}catch(e){s.error=s.error||"Host's domain name can not be converted to ASCII: "+e}(!e||e&&!e.skipNormalize)&&(r&&void 0!==s.scheme&&(s.scheme=unescape(s.scheme)),r&&void 0!==s.host&&(s.host=unescape(s.host)),s.path&&(s.path=escape(unescape(s.path))),s.fragment&&(s.fragment=encodeURI(decodeURIComponent(s.fragment)))),e&&e.parse&&e.parse(s,n)}else s.error=s.error||"URI can not be parsed.";return s}const p={SCHEMES:l,normalize:function(e,t){return"string"==typeof e?e=u(m(e,t),t):"object"==typeof e&&(e=m(u(e,t),t)),e},resolve:function(e,t,n){const i=Object.assign({scheme:"null"},n);return u(c(m(e,i),m(t,i),i,!0),{...i,skipEscape:!0})},resolveComponents:c,equal:function(e,t,n){return"string"==typeof e?(e=unescape(e),e=u(a(m(e,n),!0),{...n,skipEscape:!0})):"object"==typeof e&&(e=u(a(e,!0),{...n,skipEscape:!0})),"string"==typeof t?(t=unescape(t),t=u(a(m(t,n),!0),{...n,skipEscape:!0})):"object"==typeof t&&(t=u(a(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()},serialize:u,parse:m};e.exports=p,e.exports.default=p,e.exports.fastUri=p},343(e){"use strict";const t=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu,n=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function i(e){return"boolean"==typeof e.secure?e.secure:"wss"===String(e.scheme).toLowerCase()}function o(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function s(e){const t="https"===String(e.scheme).toLowerCase();return e.port!==(t?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}const r={scheme:"http",domainHost:!0,parse:o,serialize:s},a={scheme:"ws",domainHost:!0,parse:function(e){return e.secure=i(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e){if(e.port!==(i(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,n]=e.resourceName.split("?");e.path=t&&"/"!==t?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}},l={http:r,https:{scheme:"https",domainHost:r.domainHost,parse:o,serialize:s},ws:a,wss:{scheme:"wss",domainHost:a.domainHost,parse:a.parse,serialize:a.serialize},urn:{scheme:"urn",parse:function(e,t){if(!e.path)return e.error="URN can not be parsed",e;const i=e.path.match(n);if(i){const n=t.scheme||e.scheme||"urn";e.nid=i[1].toLowerCase(),e.nss=i[2];const o=`${n}:${t.nid||e.nid}`,s=l[o];e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e},serialize:function(e,t){const n=t.scheme||e.scheme||"urn",i=e.nid.toLowerCase(),o=`${n}:${t.nid||i}`,s=l[o];s&&(e=s.serialize(e,t));const r=e,a=e.nss;return r.path=`${i||t.nid}:${a}`,t.skipEscape=!0,r},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(e,n){const i=e;return i.uuid=i.nss,i.nss=void 0,n.tolerant||i.uuid&&t.test(i.uuid)||(i.error=i.error||"UUID is not valid."),i},serialize:function(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t},skipNormalize:!0}};e.exports=l},4914(e){"use strict";e.exports={HEX:{0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15}}},4834(e,t,n){"use strict";const{HEX:i}=n(4914),o=/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u;function s(e){if(c(e,".")<3)return{host:e,isIPV4:!1};const t=e.match(o)||[],[n]=t;return n?{host:l(n,"."),isIPV4:!0}:{host:e,isIPV4:!1}}function r(e,t=!1){let n="",o=!0;for(const t of e){if(void 0===i[t])return;"0"!==t&&!0===o&&(o=!1),o||(n+=t)}return t&&0===n.length&&(n="0"),n}function a(e){if(c(e,":")<2)return{host:e,isIPV6:!1};const t=function(e){let t=0;const n={error:!1,address:"",zone:""},i=[],o=[];let s=!1,a=!1,l=!1;function c(){if(o.length){if(!1===s){const e=r(o);if(void 0===e)return n.error=!0,!1;i.push(e)}o.length=0}return!0}for(let r=0;r<e.length;r++){const u=e[r];if("["!==u&&"]"!==u)if(":"!==u)if("%"===u){if(!c())break;s=!0}else o.push(u);else{if(!0===a&&(l=!0),!c())break;if(t++,i.push(":"),t>7){n.error=!0;break}r-1>=0&&":"===e[r-1]&&(a=!0)}}return o.length&&(s?n.zone=o.join(""):l?i.push(o.join("")):i.push(r(o))),n.address=i.join(""),n}(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+="%"+t.zone,n+="%25"+t.zone),{host:e,escapedHost:n,isIPV6:!0}}}function l(e,t){let n="",i=!0;const o=e.length;for(let s=0;s<o;s++){const r=e[s];"0"===r&&i?(s+1<=o&&e[s+1]===t||s+1===o)&&(n+=r,i=!1):(i=r===t,n+=r)}return n}function c(e,t){let n=0;for(let i=0;i<e.length;i++)e[i]===t&&n++;return n}const u=/^\.\.?\//u,h=/^\/\.(?:\/|$)/u,d=/^\/\.\.(?:\/|$)/u,m=/^\/?(?:.|\n)*?(?=\/|$)/u;e.exports={recomposeAuthority:function(e){const t=[];if(void 0!==e.userinfo&&(t.push(e.userinfo),t.push("@")),void 0!==e.host){let n=unescape(e.host);const i=s(n);if(i.isIPV4)n=i.host;else{const t=a(i.host);n=!0===t.isIPV6?`[${t.escapedHost}]`:e.host}t.push(n)}return"number"!=typeof e.port&&"string"!=typeof e.port||(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0},normalizeComponentEncoding:function(e,t){const n=!0!==t?escape:unescape;return void 0!==e.scheme&&(e.scheme=n(e.scheme)),void 0!==e.userinfo&&(e.userinfo=n(e.userinfo)),void 0!==e.host&&(e.host=n(e.host)),void 0!==e.path&&(e.path=n(e.path)),void 0!==e.query&&(e.query=n(e.query)),void 0!==e.fragment&&(e.fragment=n(e.fragment)),e},removeDotSegments:function(e){const t=[];for(;e.length;)if(e.match(u))e=e.replace(u,"");else if(e.match(h))e=e.replace(h,"/");else if(e.match(d))e=e.replace(d,"/"),t.pop();else if("."===e||".."===e)e="";else{const n=e.match(m);if(!n)throw new Error("Unexpected dot segment condition");{const i=n[0];e=e.slice(i.length),t.push(i)}}return t.join("")},normalizeIPv4:s,normalizeIPv6:a,stringArrayToHexStripped:r}},3837(e){"use strict";e.exports=JSON.parse('{"$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON AnySchema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}')},7216(e){"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/applicator","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/applicator":true},"$dynamicAnchor":"meta","title":"Applicator vocabulary meta-schema","type":["object","boolean"],"properties":{"prefixItems":{"$ref":"#/$defs/schemaArray"},"items":{"$dynamicRef":"#meta"},"contains":{"$dynamicRef":"#meta"},"additionalProperties":{"$dynamicRef":"#meta"},"properties":{"type":"object","additionalProperties":{"$dynamicRef":"#meta"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$dynamicRef":"#meta"},"propertyNames":{"format":"regex"},"default":{}},"dependentSchemas":{"type":"object","additionalProperties":{"$dynamicRef":"#meta"},"default":{}},"propertyNames":{"$dynamicRef":"#meta"},"if":{"$dynamicRef":"#meta"},"then":{"$dynamicRef":"#meta"},"else":{"$dynamicRef":"#meta"},"allOf":{"$ref":"#/$defs/schemaArray"},"anyOf":{"$ref":"#/$defs/schemaArray"},"oneOf":{"$ref":"#/$defs/schemaArray"},"not":{"$dynamicRef":"#meta"}},"$defs":{"schemaArray":{"type":"array","minItems":1,"items":{"$dynamicRef":"#meta"}}}}')},8226(e){"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/content","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/content":true},"$dynamicAnchor":"meta","title":"Content vocabulary meta-schema","type":["object","boolean"],"properties":{"contentEncoding":{"type":"string"},"contentMediaType":{"type":"string"},"contentSchema":{"$dynamicRef":"#meta"}}}')},518(e){"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/core","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/core":true},"$dynamicAnchor":"meta","title":"Core vocabulary meta-schema","type":["object","boolean"],"properties":{"$id":{"$ref":"#/$defs/uriReferenceString","$comment":"Non-empty fragments not allowed.","pattern":"^[^#]*#?$"},"$schema":{"$ref":"#/$defs/uriString"},"$ref":{"$ref":"#/$defs/uriReferenceString"},"$anchor":{"$ref":"#/$defs/anchorString"},"$dynamicRef":{"$ref":"#/$defs/uriReferenceString"},"$dynamicAnchor":{"$ref":"#/$defs/anchorString"},"$vocabulary":{"type":"object","propertyNames":{"$ref":"#/$defs/uriString"},"additionalProperties":{"type":"boolean"}},"$comment":{"type":"string"},"$defs":{"type":"object","additionalProperties":{"$dynamicRef":"#meta"}}},"$defs":{"anchorString":{"type":"string","pattern":"^[A-Za-z_][-A-Za-z0-9._]*$"},"uriString":{"type":"string","format":"uri"},"uriReferenceString":{"type":"string","format":"uri-reference"}}}')},4588(e){"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/format-annotation","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/format-annotation":true},"$dynamicAnchor":"meta","title":"Format vocabulary meta-schema for annotation results","type":["object","boolean"],"properties":{"format":{"type":"string"}}}')},5707(e){"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/meta-data","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/meta-data":true},"$dynamicAnchor":"meta","title":"Meta-data vocabulary meta-schema","type":["object","boolean"],"properties":{"title":{"type":"string"},"description":{"type":"string"},"default":true,"deprecated":{"type":"boolean","default":false},"readOnly":{"type":"boolean","default":false},"writeOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true}}}')},9547(e){"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/unevaluated","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/unevaluated":true},"$dynamicAnchor":"meta","title":"Unevaluated applicator vocabulary meta-schema","type":["object","boolean"],"properties":{"unevaluatedItems":{"$dynamicRef":"#meta"},"unevaluatedProperties":{"$dynamicRef":"#meta"}}}')},7082(e){"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/validation","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/validation":true},"$dynamicAnchor":"meta","title":"Validation vocabulary meta-schema","type":["object","boolean"],"properties":{"type":{"anyOf":[{"$ref":"#/$defs/simpleTypes"},{"type":"array","items":{"$ref":"#/$defs/simpleTypes"},"minItems":1,"uniqueItems":true}]},"const":true,"enum":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/$defs/nonNegativeInteger"},"minLength":{"$ref":"#/$defs/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"maxItems":{"$ref":"#/$defs/nonNegativeInteger"},"minItems":{"$ref":"#/$defs/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"maxContains":{"$ref":"#/$defs/nonNegativeInteger"},"minContains":{"$ref":"#/$defs/nonNegativeInteger","default":1},"maxProperties":{"$ref":"#/$defs/nonNegativeInteger"},"minProperties":{"$ref":"#/$defs/nonNegativeIntegerDefault0"},"required":{"$ref":"#/$defs/stringArray"},"dependentRequired":{"type":"object","additionalProperties":{"$ref":"#/$defs/stringArray"}}},"$defs":{"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"$ref":"#/$defs/nonNegativeInteger","default":0},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}}}')},1678(e){"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/schema","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/core":true,"https://json-schema.org/draft/2020-12/vocab/applicator":true,"https://json-schema.org/draft/2020-12/vocab/unevaluated":true,"https://json-schema.org/draft/2020-12/vocab/validation":true,"https://json-schema.org/draft/2020-12/vocab/meta-data":true,"https://json-schema.org/draft/2020-12/vocab/format-annotation":true,"https://json-schema.org/draft/2020-12/vocab/content":true},"$dynamicAnchor":"meta","title":"Core and Validation specifications meta-schema","allOf":[{"$ref":"meta/core"},{"$ref":"meta/applicator"},{"$ref":"meta/unevaluated"},{"$ref":"meta/validation"},{"$ref":"meta/meta-data"},{"$ref":"meta/format-annotation"},{"$ref":"meta/content"}],"type":["object","boolean"],"$comment":"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.","properties":{"definitions":{"$comment":"\\"definitions\\" has been replaced by \\"$defs\\".","type":"object","additionalProperties":{"$dynamicRef":"#meta"},"deprecated":true,"default":{}},"dependencies":{"$comment":"\\"dependencies\\" has been split and replaced by \\"dependentSchemas\\" and \\"dependentRequired\\" in order to serve their differing semantics.","type":"object","additionalProperties":{"anyOf":[{"$dynamicRef":"#meta"},{"$ref":"meta/validation#/$defs/stringArray"}]},"deprecated":true,"default":{}},"$recursiveAnchor":{"$comment":"\\"$recursiveAnchor\\" has been replaced by \\"$dynamicAnchor\\".","$ref":"meta/core#/$defs/anchorString","deprecated":true},"$recursiveRef":{"$comment":"\\"$recursiveRef\\" has been replaced by \\"$dynamicRef\\".","$ref":"meta/core#/$defs/uriReferenceString","deprecated":true}}}')},2079(e){"use strict";e.exports=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}')}},i={};function o(e){var t=i[e];if(void 0!==t)return t.exports;var s=i[e]={id:e,loaded:!1,exports:{}};return n[e].call(s.exports,s,s.exports,o),s.loaded=!0,s.exports}o.m=n,o.amdO={},o.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return o.d(t,{a:t}),t},o.d=(e,t)=>{for(var n in t)o.o(t,n)&&!o.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o.f={},o.e=e=>Promise.all(Object.keys(o.f).reduce((t,n)=>(o.f[n](e,t),t),[])),o.u=e=>e+".js",o.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),o.hmd=e=>((e=Object.create(e)).children||(e.children=[]),Object.defineProperty(e,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+e.id)}}),e),o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),e={},t="bio:",o.l=(n,i,s,r)=>{if(e[n])e[n].push(i);else{var a,l;if(void 0!==s)for(var c=document.getElementsByTagName("script"),u=0;u<c.length;u++){var h=c[u];if(h.getAttribute("src")==n||h.getAttribute("data-webpack")==t+s){a=h;break}}a||(l=!0,(a=document.createElement("script")).charset="utf-8",o.nc&&a.setAttribute("nonce",o.nc),a.setAttribute("data-webpack",t+s),a.src=n),e[n]=[i];var d=(t,i)=>{a.onerror=a.onload=null,clearTimeout(m);var o=e[n];if(delete e[n],a.parentNode&&a.parentNode.removeChild(a),o&&o.forEach(e=>e(i)),t)return t(i)},m=setTimeout(d.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=d.bind(null,a.onerror),a.onload=d.bind(null,a.onload),l&&document.head.appendChild(a)}},o.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;o.g.importScripts&&(e=o.g.location+"");var t=o.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var n=t.getElementsByTagName("script");if(n.length)for(var i=n.length-1;i>-1&&(!e||!/^http(s?):/.test(e));)e=n[i--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),o.p=e})(),(()=>{o.b="undefined"!=typeof document&&document.baseURI||self.location.href;var e={242:0,255:0,529:0};o.f.j=(t,n)=>{var i=o.o(e,t)?e[t]:void 0;if(0!==i)if(i)n.push(i[2]);else{var s=new Promise((n,o)=>i=e[t]=[n,o]);n.push(i[2]=s);var r=o.p+o.u(t),a=new Error;o.l(r,n=>{if(o.o(e,t)&&(0!==(i=e[t])&&(e[t]=void 0),i)){var s=n&&("load"===n.type?"missing":n.type),r=n&&n.target&&n.target.src;a.message="Loading chunk "+t+" failed.\n("+s+": "+r+")",a.name="ChunkLoadError",a.type=s,a.request=r,i[1](a)}},"chunk-"+t,t)}};var t=(t,n)=>{var i,s,[r,a,l]=n,c=0;if(r.some(t=>0!==e[t])){for(i in a)o.o(a,i)&&(o.m[i]=a[i]);l&&l(o)}for(t&&t(n);c<r.length;c++)s=r[c],o.o(e,s)&&e[s]&&e[s][0](),e[s]=0},n=self.webpackChunkbio=self.webpackChunkbio||[];n.forEach(t.bind(null,0)),n.push=t.bind(null,n.push.bind(n))})(),o.nc=void 0;var s={};(()=>{"use strict";o.r(s),o.d(s,{_package:()=>Ge,initAutoTests:()=>Ve,test:()=>Be,tests:()=>t.CN});var e=o(6082),t=o(5749);(0,t.L1)("_first",()=>{(0,t.t6)("_first",async()=>{})});var n=o(8070),i=o(8924),r=o(7362),a=o(1093);(0,t.L1)("Palettes",()=>{(0,t.t6)("testPaletteN",async()=>{await async function(){const e=a.A.Chromatogram;(0,n.E3)(e instanceof r.e,!0),(0,n.E3)(e instanceof a.A,!0)}()}),(0,t.t6)("testPaletteAA",async()=>{await async function(){const e=i.X.Lesk,t=i.X.RasMol,o=i.X.GrokGroups;(0,n.E3)(e instanceof r.e,!0),(0,n.E3)(t instanceof r.e,!0),(0,n.E3)(o instanceof r.e,!0),(0,n.E3)(e instanceof i.X,!0),(0,n.E3)(t instanceof i.X,!0),(0,n.E3)(o instanceof i.X,!0)}()}),(0,t.t6)("testPalettePtMe",async()=>{const e=i.X.GrokGroups.get("MeNle"),n=i.X.GrokGroups.get("MeA"),o=i.X.GrokGroups.get("MeG"),s=i.X.GrokGroups.get("MeF"),r=i.X.GrokGroups.get("L"),a=i.X.GrokGroups.get("A"),l=i.X.GrokGroups.get("G"),c=i.X.GrokGroups.get("F");(0,t.E3)(e,r),(0,t.E3)(n,a),(0,t.E3)(o,l),(0,t.E3)(s,c)})});var l=o(4328),c=o(2003),u=o(8312);class h{units;aligned;alphabet;alphabetSize;alphabetIsMultichar;separator;constructor(e,t,n,i,o,s){this.units=e,this.aligned=t,this.alphabet=n,this.alphabetSize=i,this.alphabetIsMultichar=o,this.separator=s}}async function d(t,n){const i=(await t()).getCol(n),o=await l.functions.call("Bio:detectMacromolecule",{col:i});if(o&&(i.semType=o),i.semType===e.SEMTYPE.MACROMOLECULE){const e=`Negative test detected semType='${i.semType}', units='${i.meta.units}'.`;throw new Error(e)}}async function m(n,i,o,s,r,a,u,h,d=null){const m=(await n()).col(i),p=await l.functions.call("Bio:detectMacromolecule",{col:m});p&&(m.semType=p),(0,t.E3)(m.semType,e.SEMTYPE.MACROMOLECULE),(0,t.E3)(m.meta.units,s),(0,t.E3)(m.getTag(c.gp.aligned),r),(0,t.E3)(m.getTag(c.gp.alphabet),a),d&&(0,t.E3)(m.getTag(c.gp.separator),d);const g=o.getSeqHandler(m);(0,t.E3)(g.getAlphabetSize(),u),(0,t.E3)(g.getAlphabetIsMultichar(),h),g.isHelm()||((0,t.E3)(g.aligned,r),(0,t.E3)(g.alphabet,a))}var p=o(4025);async function g(n,i){const o=e.Column.fromList(e.TYPE.STRING,"seq",n),s=await l.functions.call("Bio:detectMacromolecule",{col:o});s&&(o.semType=s),(0,t.E3)(o.semType,e.SEMTYPE.MACROMOLECULE);const r=i.getSeqHandler(o);return await r.refinerPromise,i.getSeqHandler(o),o}async function f(e,n,i=!1){const o=await g(e,n);(0,t.E3)(o.meta.units===c.Hi.BILN,!i,`Incorrectly detected as ${o.meta.units}`),(0,t.E3)(null!=o.temp[p.j.notationProvider],!i,"No notation provider for BILN")}async function y(e,n,i){const o=await g(e,i),s=i.getSeqHandler(o);for(let i=0;i<e.length;i++){const o=s.getHelm(i);(0,t.E3)(o===n[i],!0,`Incorrect HELM conversion for ${e[i]}: Expected ${n[i]} \n Got ${o}`)}const r=s.getConverter(c.Hi.HELM);for(let i=0;i<e.length;i++){const o=r(e[i]);(0,t.E3)(o===n[i],!0,`Incorrect HELM conversion for ${e[i]}: Expected ${n[i]} \n Got ${o}`)}}async function b(n,i,o){const s=e.Column.fromList(e.TYPE.STRING,"helm",n),r=e.DataFrame.fromColumns([s]);await r.meta.detectSemanticTypes(),await l.data.detectSemanticTypes(r),(0,t.E3)(s.semType===e.SEMTYPE.MACROMOLECULE,!0,`Incorrectly detected as ${s.semType}`),(0,t.E3)(s.meta.units===c.Hi.HELM,!0,`Incorrectly detected as ${s.meta.units}`);const a=o.getSeqHandler(s).getConverter(c.Hi.BILN);for(let e=0;e<n.length;e++){const o=a(n[e]);(0,t.E3)(o===i[e],!0,`Incorrect BILN conversion for ${n[e]}: Expected ${i[e]} \n Got ${o}`)}}const w=[{name:"Valid Biln",seqs:["A-C(1,3)-G-G-H-A-V-E-A-K-Y-L-V-C(3,3)-S.G-I-V-E-A-C(2,3)-C(1,3)-T-S-I-C(2,3)-S-L-Y-Q-L-E-N-Y-C(3,3)-Y","A-C(1,3)-G-G-H-A-V-E-A-K-Y-L-V-C(3,3)-S.G-I-V-E-A-C(2,3)-C(1,3)-T-S-I-C(2,3)-S-L-Y-Q-L-E-N-Y-C(3,3)-Y","C-C(1,3)-S-W-P-A-R-C(2,3)-L-H-Q-D-L-C(3,3)-NH2.C(1,1)(2,2)(3,3)","C-C(1,3)-S-W-P-A-R-C(2,3)-L-H-Q-D-L-C(3,3)-NH2.[C](1,1)(2,2)(3,3)","D-T-H-F-P-I-C(1,3)-I-F-C(2,3)-C(3,3)-G-C(2,3)-C(4,3)-H-R-S-K-C(3,3)-G-M-C(4,3)-C(1,3)-K-T"],negative:!1},{name:"Simple Separator Neg",seqs:["meI/hHis/Aca/N/T/dE/Thr_PO3H2/Aca/D-Tyr_Et/Tyr_ab-dehydroMe/dV/E/N/D-Orn/D-aThr//Phe_4Me","meI/hHis/Aca/Cys_SEt/T/dK/Thr_PO3H2/Aca/Tyr_PO3H2/D-Chg/dV/Phe_ab-dehydro/N/D-Orn/D-aThr//Phe_4Me","Lys_Boc/hHis/Aca/Cys_SEt/T/dK/Thr_PO3H2/Aca/Tyr_PO3H2/D-Chg/dV/Thr_PO3H2/N/D-Orn/D-aThr//Phe_4Me","meI/hHis/Aca/Cys_SEt/T/dK/Thr_PO3H2/Aca/Tyr_PO3H2/D-Chg/dV/Thr_PO3H2/N/D-Orn/D-aThr//Phe_4Me","meI/hHis/Aca/N/T/dK/Thr_PO3H2/Aca/D-Tyr_Et/Tyr_ab-dehydroMe/dV/Chg/N/D-Orn/D-aThr//Phe_4Me"],negative:!0},{name:"Valid Biln without cyclization",seqs:["meI-hHis-Aca-N-T-dE-Thr_PO3H2-Aca-[D-Tyr_Et]-[Tyr_ab-dehydroMe]-dV-E-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-[D-Chg]-dV-[Phe_ab-dehydro]-N-[D-Orn]-[D-aThr]--Phe_4Me","Lys_Boc-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-[D-Chg]-dV-Thr_PO3H2-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-[D-Chg]-dV-Thr_PO3H2-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-N-T-dK-Thr_PO3H2-Aca-[D-Tyr_Et]-[Tyr_ab-dehydroMe]-dV-Chg-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-N-T-dK-Thr_PO3H2-Aca-[D-Tyr_Et]-Tyr_Bn-dV-E-N-dV---Phe_4Me","meI-hHis-Aca-N-T-dK-Thr_PO3H2-Aca-[D-Tyr_Et]-Aze-dV-E-N-dV---Phe_4Me","meI-hHis-Aca-N-T-dK-Thr_PO3H2-Aca-[D-Tyr_Et]-meQ-dV-E-N-dV---Phe_4Me"],negative:!1}],v=[{name:"Linear",biln:["meI-hHis-Aca-N-T-dE-Thr_PO3H2-Aca-[D-Tyr_Et]-[Tyr_ab-dehydroMe]-dV-E-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-[D-Chg]-dV-[Phe_ab-dehydro]-N-[D-Orn]-[D-aThr]--Phe_4Me","Lys_Boc-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-[D-Chg]-dV-Thr_PO3H2-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-[D-Chg]-dV-Thr_PO3H2-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-N-T-dK-Thr_PO3H2-Aca-[D-Tyr_Et]-[Tyr_ab-dehydroMe]-dV-Chg-N-[D-Orn]-[D-aThr]--Phe_4Me"],helm:["PEPTIDE1{[meI].[hHis].[Aca].N.T.[dE].[Thr_PO3H2].[Aca].[D-Tyr_Et].[Tyr_ab-dehydroMe].[dV].E.N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$","PEPTIDE1{[meI].[hHis].[Aca].[Cys_SEt].T.[dK].[Thr_PO3H2].[Aca].[Tyr_PO3H2].[D-Chg].[dV].[Phe_ab-dehydro].N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$","PEPTIDE1{[Lys_Boc].[hHis].[Aca].[Cys_SEt].T.[dK].[Thr_PO3H2].[Aca].[Tyr_PO3H2].[D-Chg].[dV].[Thr_PO3H2].N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$","PEPTIDE1{[meI].[hHis].[Aca].[Cys_SEt].T.[dK].[Thr_PO3H2].[Aca].[Tyr_PO3H2].[D-Chg].[dV].[Thr_PO3H2].N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$","PEPTIDE1{[meI].[hHis].[Aca].N.T.[dK].[Thr_PO3H2].[Aca].[D-Tyr_Et].[Tyr_ab-dehydroMe].[dV].[Chg].N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$"]},{name:"Cyclic",biln:["C-C(1,3)-S-W-P-A-R-C(2,3)-L-H-Q-D-L-C(3,3)-NH2.[C](1,1)(2,2)(3,3)","D-T-H-F-P-I-C(1,3)-I-F-C(2,3)-C(3,3)-G-C(2,3)-C(4,3)-H-R-S-K-C(3,3)-G-M-C(4,3)-C(1,3)-K-T","L-C(1,3)-G-S-H-L-V-E-A-L-Y-L-V-C(2,3)-G.G-I-V-E-Q-C(3,3)-C(1,3)-T-S-I-C(3,3)-S-L-Y-Q-L-E-N-Y-C(2,3)-N","H-Aib-E-G-T-F-T-S-D(2,3)-V-S-S-Y-L-E-G-Q-A-A-K(1,3)-E-F-I-A-W-L-V-R-G-R-G.C(2,3)-gGlu-G-G(1,2)","F(4,2).dI(1,1)(3,3)-Trp_Ome-Asp_OMe-Cys_Bn-meG-Phe_3Cl-dD-T-dI(4,3)-T-dK-aG-3Pal-xiIle-meD-Ala_tBu(1,2).L(2,1)-Pro_4Me3OH-S-NMe2Abz-Q-3Pal-xiIle-D-Hyp-Ala_tBu-dI(3,3)-Trp_Ome-Asp_OMe-N-meG-Phe_34diCl-Phe_34diCl(2,2)"],helm:["PEPTIDE1{C.C.S.W.P.A.R.C.L.H.Q.D.L.C.[NH2]}|PEPTIDE2{C}$PEPTIDE1,PEPTIDE2,14:R3-1:R3|PEPTIDE1,PEPTIDE2,8:R3-1:R2|PEPTIDE1,PEPTIDE2,2:R3-1:R1$$$V2.0","PEPTIDE1{D.T.H.F.P.I.C.I.F.C.C.G.C.C.H.R.S.K.C.G.M.C.C.K.T}$PEPTIDE1,PEPTIDE1,10:R3-13:R3|PEPTIDE1,PEPTIDE1,11:R3-19:R3|PEPTIDE1,PEPTIDE1,14:R3-22:R3|PEPTIDE1,PEPTIDE1,7:R3-23:R3$$$V2.0","PEPTIDE1{L.C.G.S.H.L.V.E.A.L.Y.L.V.C.G}|PEPTIDE2{G.I.V.E.Q.C.C.T.S.I.C.S.L.Y.Q.L.E.N.Y.C.N}$PEPTIDE1,PEPTIDE2,2:R3-7:R3|PEPTIDE2,PEPTIDE2,6:R3-11:R3|PEPTIDE1,PEPTIDE2,14:R3-20:R3$$$V2.0","PEPTIDE1{H.[Aib].E.G.T.F.T.S.D.V.S.S.Y.L.E.G.Q.A.A.K.E.F.I.A.W.L.V.R.G.R.G}|PEPTIDE2{C.[gGlu].G.G}$PEPTIDE1,PEPTIDE2,9:R3-1:R3|PEPTIDE1,PEPTIDE2,20:R3-4:R2$$$V2.0","PEPTIDE1{F}|PEPTIDE2{[dI].[Trp_Ome].[Asp_OMe].[Cys_Bn].[meG].[Phe_3Cl].[dD].T.[dI].T.[dK].[aG].[3Pal].[xiIle].[meD].[Ala_tBu]}|PEPTIDE3{L.[Pro_4Me3OH].S.[NMe2Abz].Q.[3Pal].[xiIle].D.[Hyp].[Ala_tBu].[dI].[Trp_Ome].[Asp_OMe].N.[meG].[Phe_34diCl].[Phe_34diCl]}$PEPTIDE1,PEPTIDE2,1:R2-9:R3|PEPTIDE2,PEPTIDE2,1:R1-16:R2|PEPTIDE2,PEPTIDE3,1:R3-11:R3|PEPTIDE3,PEPTIDE3,1:R1-17:R2$$$V2.0"]}],C=[{name:"Linear",biln:["meI-hHis-Aca-N-T-dE-Thr_PO3H2-Aca-[D-Tyr_Et]-[Tyr_ab-dehydroMe]-dV-E-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-[D-Chg]-dV-[Phe_ab-dehydro]-N-[D-Orn]-[D-aThr]--Phe_4Me","Lys_Boc-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-[D-Chg]-dV-Thr_PO3H2-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-[D-Chg]-dV-Thr_PO3H2-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-N-T-dK-Thr_PO3H2-Aca-[D-Tyr_Et]-[Tyr_ab-dehydroMe]-dV-Chg-N-[D-Orn]-[D-aThr]--Phe_4Me"],helm:["PEPTIDE1{[meI].[hHis].[Aca].N.T.[dE].[Thr_PO3H2].[Aca].[D-Tyr_Et].[Tyr_ab-dehydroMe].[dV].E.N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$","PEPTIDE1{[meI].[hHis].[Aca].[Cys_SEt].T.[dK].[Thr_PO3H2].[Aca].[Tyr_PO3H2].[D-Chg].[dV].[Phe_ab-dehydro].N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$","PEPTIDE1{[Lys_Boc].[hHis].[Aca].[Cys_SEt].T.[dK].[Thr_PO3H2].[Aca].[Tyr_PO3H2].[D-Chg].[dV].[Thr_PO3H2].N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$","PEPTIDE1{[meI].[hHis].[Aca].[Cys_SEt].T.[dK].[Thr_PO3H2].[Aca].[Tyr_PO3H2].[D-Chg].[dV].[Thr_PO3H2].N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$","PEPTIDE1{[meI].[hHis].[Aca].N.T.[dK].[Thr_PO3H2].[Aca].[D-Tyr_Et].[Tyr_ab-dehydroMe].[dV].[Chg].N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$"]},{name:"Cyclic",biln:["C-C(3,3)-S-W-P-A-R-C(2,3)-L-H-Q-D-L-C(1,3)-NH2.C(1,3)(2,2)(3,1)","D-T-H-F-P-I-C(4,3)-I-F-C(1,3)-C(2,3)-G-C(1,3)-C(3,3)-H-R-S-K-C(2,3)-G-M-C(3,3)-C(4,3)-K-T","L-C(1,3)-G-S-H-L-V-E-A-L-Y-L-V-C(3,3)-G.G-I-V-E-Q-C(2,3)-C(1,3)-T-S-I-C(2,3)-S-L-Y-Q-L-E-N-Y-C(3,3)-N","H-Aib-E-G-T-F-T-S-D(1,3)-V-S-S-Y-L-E-G-Q-A-A-K(2,3)-E-F-I-A-W-L-V-R-G-R-G.C(1,3)-gGlu-G-G(2,2)","F(1,2).dI(2,1)(3,3)-Trp_Ome-Asp_OMe-Cys_Bn-meG-Phe_3Cl-dD-T-dI(1,3)-T-dK-aG-3Pal-xiIle-meD-Ala_tBu(2,2).L(4,1)-Pro_4Me3OH-S-NMe2Abz-Q-3Pal-xiIle-D-Hyp-Ala_tBu-dI(3,3)-Trp_Ome-Asp_OMe-N-meG-Phe_34diCl-Phe_34diCl(4,2)"],helm:["PEPTIDE1{C.C.S.W.P.A.R.C.L.H.Q.D.L.C.[NH2]}|PEPTIDE2{C}$PEPTIDE1,PEPTIDE2,14:R3-1:R3|PEPTIDE1,PEPTIDE2,8:R3-1:R2|PEPTIDE1,PEPTIDE2,2:R3-1:R1$$$V2.0","PEPTIDE1{D.T.H.F.P.I.C.I.F.C.C.G.C.C.H.R.S.K.C.G.M.C.C.K.T}$PEPTIDE1,PEPTIDE1,10:R3-13:R3|PEPTIDE1,PEPTIDE1,11:R3-19:R3|PEPTIDE1,PEPTIDE1,14:R3-22:R3|PEPTIDE1,PEPTIDE1,7:R3-23:R3$$$V2.0","PEPTIDE1{L.C.G.S.H.L.V.E.A.L.Y.L.V.C.G}|PEPTIDE2{G.I.V.E.Q.C.C.T.S.I.C.S.L.Y.Q.L.E.N.Y.C.N}$PEPTIDE1,PEPTIDE2,2:R3-7:R3|PEPTIDE2,PEPTIDE2,6:R3-11:R3|PEPTIDE1,PEPTIDE2,14:R3-20:R3$$$V2.0","PEPTIDE1{H.[Aib].E.G.T.F.T.S.D.V.S.S.Y.L.E.G.Q.A.A.K.E.F.I.A.W.L.V.R.G.R.G}|PEPTIDE2{C.[gGlu].G.G}$PEPTIDE1,PEPTIDE2,9:R3-1:R3|PEPTIDE1,PEPTIDE2,20:R3-4:R2$$$V2.0","PEPTIDE1{F}|PEPTIDE2{[dI].[Trp_Ome].[Asp_OMe].[Cys_Bn].[meG].[Phe_3Cl].[dD].T.[dI].T.[dK].[aG].[3Pal].[xiIle].[meD].[Ala_tBu]}|PEPTIDE3{L.[Pro_4Me3OH].S.[NMe2Abz].Q.[3Pal].[xiIle].D.[Hyp].[Ala_tBu].[dI].[Trp_Ome].[Asp_OMe].N.[meG].[Phe_34diCl].[Phe_34diCl]}$PEPTIDE1,PEPTIDE2,1:R2-9:R3|PEPTIDE2,PEPTIDE2,1:R1-16:R2|PEPTIDE2,PEPTIDE3,1:R3-11:R3|PEPTIDE3,PEPTIDE3,1:R1-17:R2$$$V2.0"]}];async function A(t){const n=e.Column.fromList(e.TYPE.STRING,"col1",t);if(await l.functions.call("Bio:detectMacromolecule",{col:n}),n.semType===e.SEMTYPE.MACROMOLECULE){const e=`Negative test detected semType='${n.semType}', units='${n.meta.units}'.`;throw new Error(e)}}async function T(n,i,o,s,r,a,u,h=null){const d=e.Column.fromList(e.TYPE.STRING,"seq",n),m=await l.functions.call("Bio:detectMacromolecule",{col:d});m&&(d.semType=m),(0,t.E3)(d.semType,e.SEMTYPE.MACROMOLECULE),(0,t.E3)(d.meta.units,o),(0,t.E3)(d.getTag(c.gp.aligned),s),(0,t.E3)(d.getTag(c.gp.alphabet),r),h&&(0,t.E3)(d.getTag(c.gp.separator),h);const p=i.getSeqHandler(d);(0,t.E3)(p.getAlphabetSize(),a),(0,t.E3)(p.getAlphabetIsMultichar(),u),p.isHelm()||((0,t.E3)(p.aligned,s),(0,t.E3)(p.alphabet,r))}async function E(e,t,n){const i=await e(),o=[];for(const s of i.columns.names())if(s in t){const i=t[s];try{await m(e,s,n,i.units,i.aligned,i.alphabet,i.alphabetSize,i.alphabetIsMultichar,i.separator)}catch(e){const t=e.toString();o.push(`Positive col '${s}' failed: ${t}`)}}else try{await d(e,s)}catch(e){const t=e.toString();o.push(`Negative col '${s}' failed: ${t}`)}if(o.length>0)throw new Error(o.join("\n"))}(0,t.L1)("detectors",()=>{let n;(0,t.gM)(async()=>{n=await(0,u.Q)()});const i={negEmpty:{csv:"id,col1\n1,\n2,\n3,\n4,\n5,",neg:["col1"]},negNum1:{csv:"col1\n1\n2\n3",neg:["col1"]},negNum2:{csv:"col1\n4\n5\n6\n7",neg:["col1"]},negNum3:{csv:"col1\n8\n9\n10\n11\n12",neg:["col1"]},negSmiles:{csv:"col1\nCCCCN1C(=O)CN=C(c2cc(F)ccc12)C3CCCCC3\nC1CCCCC1\nCCCCCC",neg:["col1"]},negSmilesWithSquareBrackets:{csv:"col1\nCl.c1ccc2nc3ccccc3cc2c1\nOc1cccc2cc3ccccc3cc12\n[SeH]c1ccc2ccccc2c1",neg:["col1"]},negFastaUnSingleChar:{csv:"col1\nAlanine\nCysteine\nAspartic acid\nGlutamic acid\nPhenylalanine",neg:["col1"]},fastaMsaSameLength:{csv:"seq\nFWPHEYFWPHEYYV\nYNRQWYVYNRQWYV\nMKPSEYVMKPSEYV",pos:{seq:new h(c.Hi.FASTA,"SEQ.MSA",c.YI.PT,20,!1,void 0)}},fastaExtSameLength:{csv:"seq\nFW[Ac]PHEYFWPH\nYN[Re]VYNRQWYV\n[Me]EYVMPS[Et]",pos:{seq:new h(c.Hi.FASTA,"SEQ",c.YI.UN,16,!0,void 0)}},fastaMsaExtSameLength:{csv:"seq\nFW[Ac]PHEY[Re]WPH\nYN[Re]VYNR[Ac]WYV\n[Me]EYVMPSFW[Me]H",pos:{seq:new h(c.Hi.FASTA,"SEQ.MSA",c.YI.UN,14,!0,void 0)}},sepSameLength:{csv:"seq\nAca-A-A-A-A-A-A-A-A-A-A-A-A-A-C-G-NH2\nAca-A-A-A-A-A-A-A-A-A-A-A-A-A-C-G-NH2\nAca-A-A-A-A-A-A-A-A-A-A-A-A-A-C-G-NH2",pos:{seq:new h(c.Hi.SEPARATOR,"SEQ.MSA",c.YI.UN,5,!0,"-")}},sepMsaSameLength:{csv:"seq\nAca-A-A-A-A-A-A-A-A-A-A-A-A-A-Aca-G-NH2\nAca-A-Aca-A-A-A-meI-A-A-A-A-A-Aca-G-NH2\nAca-A-A-A-A-A-A-A-A-A-A-A-A-A-Aca-G-NH2",pos:{seq:new h(c.Hi.SEPARATOR,"SEQ",c.YI.UN,5,!0,"-")}},helmSameLength:{csv:"seq\nPEPTIDE1{Ac(1).A.A.A.A.A.A.A.A.A.A.A.A.A.C(1).G.NH2}$$$$\nPEPTIDE1{Ab(1).Y.V.K.H.P.F.W.R.W.Y.A.A.A.C(1).G.NH2}$$$$\nPEPTIDE1{Ad(1).S.W.Y.C.K.H.P.M.W.A.A.A.A.C(1)-G-NH2}$$$$",pos:{seq:new h(c.Hi.HELM,null,null,19,void 0,void 0)}},fastaNonDigitAlphabet:{csv:'flagC\n"NMe-pyridazineH"\n"Pyrrolo[2,3-c]pyridazineH"',neg:["flagC"]}};for(const[o,s]of Object.entries(i))(0,t.t6)(`csvData2-${o}`,async()=>{const t=(r=o,async()=>{const t=i[r].csv,n=e.DataFrame.fromCsv(t);return await l.data.detectSemanticTypes(n),n});var r;for(const e of s.neg??[])await d(t,e);for(const[e,i]of Object.entries(s.pos??{}))await m(t,e,n,i.units,i.aligned,i.alphabet,i.alphabetSize,i.alphabetIsMultichar,i.separator)});const o=new class{csvFastaDna1="seq\nACGTCACGTC\nCAGTGTCAGTGT\nTTCAACTTCAAC";fastaRna1="seq\nACGUCACGUC\nCAGUGUCAGUGU\nUUCAACUUCAAC";fastaPt1="seq\nFWPHEY\nYNRQWYV\nMKPSEYV";fastaUn="seq\n[meI][hHis][Aca]NT[dE][Thr_PO3H2][Aca]DN\n[meI][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca][Tyr_PO3H2][Aca]\n[Lys_Boc][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca][Tyr_PO3H2][Aca]";sepDna="seq\nA*C*G*T*C*A*C*G*T*C\nC*A*G*T*G*T*C*A*G*T*G*T\nT*T*C*A*A*C*T*T*C*A*A*C";sepRna="seq\nA*C*G*U*C*A*C*G*U*C\nC*A*G*U*G*U*C*A*G*U*G*U\nU*U*C*A*A*C*U*U*C*A*A*C";sepPt="seq\nF-W-P-H-E-Y-F-W-P-H-E-Y\nY-N-R-Q-W-Y-V-Y-N-R-Q-W-Y-V\nM-K-P-S-E-Y-V-M-K-P-S-E-Y-V";sepUn1="seq\nabc-dfgg-abc1-cfr3-rty-wert-cfr3-rty-wert\nrut12-her2-rty-wert-abc-abc1-dfgg-abc-abc1-dfgg\nrut12-rty-her2-abc-cfr3-wert-rut12-cfr3-wert-rut12";sepUn2="seq\nabc/dfgg/abc1/cfr3/rty/wert/abc/dfgg/abc1/cfr3/rty/wert\nrut12/her2/rty/wert//abc/abc1/dfgg/rut12/her2/rty/wert//abc/abc1/dfgg\nrut12/rty/her2/abc/cfr3//wert/rut12/rut12/rty/her2/abc/cfr3//wert/rut12";sepMsaDna1="seq\nA-C--G-T--C-T-A-C--G-T--C-T\nC-A-C--T--G-T-C-A-C--T--G-T\nA-C-C-G-T-A-C-T-A-C-C-G-T-A-C-T";sepMsaUnWEmpty="seq\nm1-M-m3-mon4-mon5-N-T-MON8-N9-m1-M-m3-mon4-mon5-N-T-MON8-N9\nm1-mon2-m3-mon4-mon5-Num--MON8-N9-m1-mon2-m3-mon4-mon5-Num--MON8-N9\n\nmon1-M-mon3-mon4-mon5---MON8-N9-mon1-M-mon3-mon4-mon5---MON8-N9";sepComplex="seq\nAca-F-K(AEEA-AEEA-R-Ac)-L-mF-V-Y-mNle-D-W-N-mF-Aca-G-NH2\nAca-F-K(AEEA-ARRA-W-Ac)-L-mF-V-Y-mNle-D-W-N-mF-Aca-G-NH2\nAca-F-K(AEEA-AEEA-Ac)-L-mF-V-Y-mNle-D-W-N-mF-Aca-G-NH2";fastaMsaDna1="seq\nAC-GT-CTAC-GT-CT\nCAC-T-GTCAC-T-GT\nACCGTACTACCGTACT";fastaMsaPt1="seq\nFWR-WYV-KHPFWR-WYV-KHP\nYNR-WYV-KHPYNR-WYV-KHP\nMWRSWY-CKHPMWRSWY-CKHP"},s={fastaPtCsv:"System:AppData/Bio/samples/FASTA_PT.csv",msaComplex:"System:AppData/Bio/samples/MSA.csv",fastaCsv:"System:AppData/Bio/samples/FASTA.csv",helmCsv:"System:AppData/Bio/samples/HELM.csv",peptidesComplex:"System:AppData/Bio/tests/peptides_complex_msa.csv",peptidesSimple:"System:AppData/Bio/tests/peptides_simple_msa.csv",testDemogCsv:"System:AppData/Bio/tests/testDemog.csv",testHelmCsv:"System:AppData/Bio/tests/testHelm.csv",testIdCsv:"System:AppData/Bio/tests/testId.csv",testSmilesCsv:"System:AppData/Bio/tests/testSmiles.csv",testSmiles2Csv:"System:AppData/Bio/tests/testSmiles2.csv",testSmilesShort:"System:AppData/Bio/tests/testSmilesShort.csv",testActivityCliffsCsv:"System:AppData/Bio/tests/testActivityCliffs.csv",testCerealCsv:"System:AppData/Bio/tests/testCereal.csv",testUnichemSources:"System:AppData/Bio/tests/testUnichemSources.csv",testDmvOffices:"System:AppData/Bio/tests/testDmvOffices.csv",testAlertCollection:"System:AppData/Bio/tests/testAlertCollection.csv",testSpgi100:"System:AppData/Bio/tests/testSpgi100.csv",testSpgi:"System:AppData/Bio/tests/SPGI-derived.csv",testUrl:"System:AppData/Bio/tests/testUrl.csv",fasta_negative_words:"System:AppData/Bio/tests/fasta_negative_words.csv"},r={};function a(e,t=p){return async()=>(e in r||(r[e]=(async()=>await t(s[e]))().catch(t=>{throw delete r[e],t})),r[e])}async function p(t){const n=await l.dapi.files.readAsText(t);return e.DataFrame.fromCsv(n)}const g=t=>async()=>{const n=o[t],i=e.DataFrame.fromCsv(n);return await l.data.detectSemanticTypes(i),i};(0,t.t6)("NegativeStartEnd",async()=>{await A(["START","END"])}),(0,t.t6)("NegativeStartEndIntermediate",async()=>{await A(["START","END","INTERMEDIATE"])}),(0,t.t6)("FastaDna1",async()=>{await m(g("csvFastaDna1"),"seq",n,c.Hi.FASTA,"SEQ",c.YI.DNA,4,!1)}),(0,t.t6)("FastaRna1",async()=>{await m(g("fastaRna1"),"seq",n,c.Hi.FASTA,"SEQ",c.YI.RNA,4,!1)}),(0,t.t6)("FastaPt1",async()=>{await m(g("fastaPt1"),"seq",n,c.Hi.FASTA,"SEQ",c.YI.PT,20,!1)}),(0,t.t6)("FastaPtGaps",()=>T(["FW-PH-EYY","FYNRQWYV-","FKP-Q-SEYV"],n,c.Hi.FASTA,"SEQ",c.YI.PT,20,!1)),(0,t.t6)("FastaPtGapsMsa",()=>T(["FW-PH-EYY","FYNRQWYV-","FKP-Q-SEY"],n,c.Hi.FASTA,"SEQ.MSA",c.YI.PT,20,!1)),(0,t.t6)("FastaUn",async()=>{await m(g("fastaUn"),"seq",n,c.Hi.FASTA,"SEQ.MSA",c.YI.UN,12,!0)}),(0,t.t6)("FastaMsaDna1",async()=>{await m(g("fastaMsaDna1"),"seq",n,c.Hi.FASTA,"SEQ.MSA",c.YI.DNA,4,!1)}),(0,t.t6)("FastaMsaPt1",async()=>{await m(g("fastaMsaPt1"),"seq",n,c.Hi.FASTA,"SEQ.MSA",c.YI.PT,20,!1)}),(0,t.t6)("SepDna",async()=>{await m(g("sepDna"),"seq",n,c.Hi.SEPARATOR,"SEQ",c.YI.DNA,4,!1,"*")}),(0,t.t6)("SepRna",async()=>{await m(g("sepRna"),"seq",n,c.Hi.SEPARATOR,"SEQ",c.YI.RNA,4,!1,"*")}),(0,t.t6)("SepPt",async()=>{await m(g("sepPt"),"seq",n,c.Hi.SEPARATOR,"SEQ",c.YI.PT,20,!1,"-")}),(0,t.t6)("SepUn1",async()=>{await m(g("sepUn1"),"seq",n,c.Hi.SEPARATOR,"SEQ",c.YI.UN,8,!0,"-")}),(0,t.t6)("SepUn2",async()=>{await m(g("sepUn2"),"seq",n,c.Hi.SEPARATOR,"SEQ",c.YI.UN,9,!0,"/")}),(0,t.t6)("SepMsaN1",async()=>{await m(g("sepMsaDna1"),"seq",n,c.Hi.SEPARATOR,"SEQ.MSA",c.YI.DNA,4,!1,"-")}),(0,t.t6)("SepMsaUnWEmpty",async()=>{await m(g("sepMsaUnWEmpty"),"seq",n,c.Hi.SEPARATOR,"SEQ.MSA",c.YI.UN,14,!0)}),(0,t.t6)("SepComplex",async()=>{await m(g("sepComplex"),"seq",n,c.Hi.SEPARATOR,"SEQ",c.YI.UN,17,!0)}),(0,t.t6)("samplesFastaCsv",async()=>{await E(a("fastaCsv"),{Sequence:new h(c.Hi.FASTA,"SEQ",c.YI.PT,20,!1)},n)});for(const e of w)(0,t.t6)(e.name,async()=>{await f(e.seqs,n,e.negative)});(0,t.t6)("samplesPeptidesComplex",async()=>{await E(a("peptidesComplex"),{},n)}),(0,t.t6)("samplesMsaComplex",async()=>{await E(a("msaComplex"),{MSA:new h(c.Hi.SEPARATOR,"SEQ.MSA",c.YI.UN,161,!0,"/")},n)}),(0,t.t6)("samplesIdCsv",async()=>{await E(a("testIdCsv"),{},n)}),(0,t.t6)("samplesSarSmallCsv",async()=>{await E(a("testSmilesCsv"),{},n)}),(0,t.t6)("samplesHelmCsv",async()=>{await E(a("helmCsv"),{HELM:new h(c.Hi.HELM,null,null,160,!0)},n)}),(0,t.t6)("samplesTestHelmCsv",async()=>{await E(a("testHelmCsv"),{"HELM string":new h(c.Hi.HELM,null,null,7,!0)},n)}),(0,t.t6)("samplesTestDemogCsv",async()=>{await E(a("testDemogCsv"),{},n)}),(0,t.t6)("samplesTestSmiles2Csv",async()=>{await E(a("testSmiles2Csv"),{},n)}),(0,t.t6)("samplesTestSmilesShort",async()=>{await E(a("testSmilesShort"),{},n)}),(0,t.t6)("samplesTestActivityCliffsNegativeSmiles",async()=>{await E(a("testActivityCliffsCsv"),{},n)}),(0,t.t6)("samplesFastaPtCsv",async()=>{await E(a("fastaPtCsv"),{sequence:new h(c.Hi.FASTA,"SEQ",c.YI.PT,20,!1)},n)}),(0,t.t6)("samplesTestCerealCsv",async()=>{await E(a("testCerealCsv"),{},n)}),(0,t.t6)("samplesTestUnichemSources",async()=>{await E(a("testUnichemSources"),{},n)}),(0,t.t6)("samplesTestDmvOffices",async()=>{await E(a("testDmvOffices"),{},n)}),(0,t.t6)("samplesTestAlertCollection",async()=>{await E(a("testAlertCollection"),{},n)}),(0,t.t6)("samplesTestSpgi",async()=>{await E(a("testSpgi"),{},n)}),(0,t.t6)("samplesTestSpgi100",async()=>{await E(a("testSpgi100"),{},n)}),(0,t.t6)("samplesTestUrl",async()=>{await E(a("testUrl"),{},n)}),(0,t.t6)("samplesFastaNegativeWords",async()=>{await E(a("fasta_negative_words"),{},n)})}),(0,t.L1)("detectors.weak-and-likely",()=>{let n;(0,t.gM)(async()=>{n=await(0,u.Q)()});const i={fastaDnaWeak1:"id,colName\n1,TTTTTTTTTT\n2,TTTTTTTTTT\n3,TTTTTTTTTT\n4,TTTTTTTTTT",fastaDnaWeak1LikelyName:"id,seq\n1,TTTTTTT\n2,TTTTTTT\n3,TTTTTTT\n4,TTTTTTT",fastaRnaWeak1:"id,colName\n1,UUUUUUUUUU\n2,UUUUUUUUUU\n3,UUUUUUUUUU\n4,UUUUUUUUUU",fastaRnaWeak1LikelyName:"id,seq\n1,UUUUUUU\n2,UUUUUUU\n3,UUUUUUU\n4,UUUUUUU",fastaPtWeak1:"id,colName\n1,SLSLSPGKSLSLSPGK\n2,SLSLSPGKSLSLSPGK\n3,SLSLSPGKSLSLSPGK\n4,SLSLSPGKSLSLSPGK",fastaPtWeak1LikelyName:"id,seq\n1,SLSLSPGKSLSLSPGK\n2,SLSLSPGKSLSLSPGK\n3,SLSLSPGKSLSLSPGK\n4,SLSLSPGKSLSLSPGK",fastaUn1:"id,colName\n1,word\n2,other\n3,some\n4,another",fastaUn1LikelyName:"id,seq\n1,word\n2,other\n3,some\n4,another",fastaUn2LikelyName:'protein\nBoombastic\nMegafantastic\n"just-a-random-thought,oy!"',fastaUnMsa1LikelyName:"id,seq\n1,word\n2,male\n3,bare\n4,core"},o=t=>async()=>{const n=i[t],o=e.DataFrame.fromCsv(n);return await l.data.detectSemanticTypes(o),o};(0,t.t6)("fastaDnaWeak1",async()=>{await d(o("fastaDnaWeak1"),"colName")}),(0,t.t6)("fastaDnaWeak1LikelyName",async()=>{await m(o("fastaDnaWeak1LikelyName"),"seq",n,c.Hi.FASTA,"SEQ.MSA",c.YI.DNA,4,!1)}),(0,t.t6)("fastaRnaWeak1",async()=>{await d(o("fastaRnaWeak1"),"colName")}),(0,t.t6)("fastaRnaWeak1LikelyName",async()=>{await m(o("fastaRnaWeak1LikelyName"),"seq",n,c.Hi.FASTA,"SEQ.MSA",c.YI.RNA,4,!1)}),(0,t.t6)("fastaPtWeak1",async()=>{await d(o("fastaPtWeak1"),"colName")}),(0,t.t6)("fastaPtWeak1LikelyName",async()=>{await m(o("fastaPtWeak1LikelyName"),"seq",n,c.Hi.FASTA,"SEQ.MSA",c.YI.PT,20,!1)}),(0,t.t6)("fastaUn1",async()=>{await d(o("fastaUn1"),"colName")}),(0,t.t6)("fastaUn1LikelyName",async()=>{await d(o("fastaUn1LikelyName"),"seq")}),(0,t.t6)("fastaUn2LikelyName",async()=>{await d(o("fastaUn2LikelyName"),"protein")}),(0,t.t6)("fastaUnMsa1LikelyName",async()=>{await d(o("fastaUnMsa1LikelyName"),"seq")})}),(0,t.L1)("detectorsBenchmark",()=>{let n,i;async function o(o,r,a,l,u,h){return await async function(o){const d=await(async()=>{const t=function(t,n,i,o,s){let r;switch(t){case c.Hi.FASTA:r=e=>{let t="";for(let n=0;n<e.length;n++){const i=e[n];t+=1==i.length?i:`[${i}]`}return t};break;case c.Hi.SEPARATOR:r=(e,t)=>e.join(t);break;default:throw new Error(`Not supported notation '${t}'.`)}const a=(e,t)=>{const n=new Array(t);for(let i=0;i<t;i++)n[i]=e[Math.floor(Math.random()*e.length)];return r(n,s)},l=Array(o);for(let e=0;e<o;e++)l[e]=a(n,i);return e.Column.fromStrings("seq",l)}(r,[...(0,c.Qf)(a)],l,u,h),n=i.prepare({col:t});return s(n),n})(),m=Date.now(),p=s(d),g=Date.now();(function(e,i){const o=n.getSeqHandler(e);(0,t.E3)(e.semType===i.semType,!0),(0,t.E3)(o.notation===i.notation,!0),(0,t.E3)(o.alphabet===i.alphabet,!0),(0,t.E3)(o.separator===i.separator,!0)})(p,{semType:e.SEMTYPE.MACROMOLECULE,notation:r,alphabet:a,separator:h});const f=g-m;if(f>o){const e=`ET ${f} ms is more than max allowed ${o} ms.`;throw console.error(e),new Error(e)}return console.log(`ET ${f} ms is OK.`),f}(o)}function s(e){e.callSync();const t=e.getOutputParamValue(),n=e.inputs.col;return t&&(n.semType=t),n}(0,t.gM)(async()=>{n=await(0,u.Q)();const t=e.Func.find({package:"Bio",name:"detectMacromolecule"});i=t[0];const o=e.Column.fromStrings("seq",["ACGT","ACGT","ACGT"]);await i.prepare({col:o}).call()}),(0,t.t6)("fastaDnaShorts50Few50",async()=>{await o(20,c.Hi.FASTA,c.YI.DNA,50,50)}),(0,t.t6)("fastaDnaShorts50Many1E6",async()=>{await o(20,c.Hi.FASTA,c.YI.DNA,50,1e6)}),(0,t.t6)("fastaDnaLong1e6Few50",async()=>{await o(20,c.Hi.FASTA,c.YI.DNA,1e6,50)}),(0,t.t6)("separatorDnaShorts50Few50",async()=>{await o(20,c.Hi.SEPARATOR,c.YI.DNA,50,50,"/")}),(0,t.t6)("separatorDnaShorts50Many1E6",async()=>{await o(20,c.Hi.SEPARATOR,c.YI.DNA,50,1e6,"/")}),(0,t.t6)("separatorDnaLong1e6Few50",async()=>{await o(20,c.Hi.SEPARATOR,c.YI.DNA,1e6,50,"/")})});var S=o(608),M=o(1619);async function x(n,i){const o=e.DataFrame.fromCsv(n);await l.data.detectSemanticTypes(o);const s=e.DataFrame.fromCsv(i),r=o.getCol("seq");(0,t.E3)(r.semType,e.SEMTYPE.MACROMOLECULE);const a=s.getCol("seq"),c=await(0,S.eE)(o,r,!0);(0,t.J6)(c.toList(),a.toList())}(0,t.L1)("MSA",async()=>{let n;async function i(i,o,s,r,a,u){const h=e.DataFrame.fromCsv(i);await l.data.detectSemanticTypes(h);const d=e.DataFrame.fromCsv(o).getCol("seq"),m=h.getCol("seq");(0,t.E3)(m.semType,e.SEMTYPE.MACROMOLECULE),(0,t.E3)(m.meta.units,s),a&&(0,t.E3)(m.getTag(c.gp.alphabet),a);const p=await(0,M.D)({col:m,engine:u?"PepSeA":void 0,engineParams:u?{method:u}:void 0},n);(0,t.E3)(p.semType,e.SEMTYPE.MACROMOLECULE),(0,t.E3)(p.meta.units,r),(0,t.E3)(p.getTag(c.gp.aligned),"SEQ.MSA"),a&&(0,t.E3)(p.getTag(c.gp.alphabet),a),(0,t.J6)(p.toList(),d.toList())}(0,t.gM)(async()=>{n=await(0,u.Q)()}),(0,t.t6)("isCorrect",async()=>{await x("seq\nFWRWYVKHP\nYNRWYVKHP\nMWRSWYCKHP","seq\nFWR-WYVKHP\nYNR-WYVKHP\nMWRSWYCKHP")}),(0,t.t6)("isCorrectLong",async()=>{await x("seq\nFWRWYVKHPFWRWYVKHPFWRWYVKHPFWRWYVKHPFWRWYVKHPFWRWYVKHPFWRWYVKHPFWRWYVKHP\nYNRWYVKHPYNRWYVKHPYNRWYVKHPYNRWYVKHPYNRWYVKHPYNRWYVKHPYNRWYVKHPYNRWYVKHP\nMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHP","seq\nFWR-WYVKHPFWR-WYVKHPFWR-WYVKHPFWR-WYVKHPFWR-WYVKHPFWR-WYVKHPFWR-WYVKHPFWR-WYVKHP\nYNR-WYVKHPYNR-WYVKHPYNR-WYVKHPYNR-WYVKHPYNR-WYVKHPYNR-WYVKHPYNR-WYVKHPYNR-WYVKHP\nMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHP")}),(0,t.t6)("isCorrectHelm",async()=>{await i("seq\n PEPTIDE1{meI.hHis.Aca.N.T.dE.Thr_PO3H2}$$$$\n PEPTIDE1{meI.Aca.N.T.dE.Thr_PO3H2}$$$$\n PEPTIDE1{hHis.Aca.N.T.dE.Thr_PO3H2}$$$$","seq\n meI.hHis.Aca.N.T.dE.Thr_PO3H2\n .meI.Aca.N.T.dE.Thr_PO3H2\n .hHis.Aca.N.T.dE.Thr_PO3H2",c.Hi.HELM,c.Hi.SEPARATOR,void 0,"mafft")},{timeout:8e4,skipReason:"Fails in docker"}),(0,t.t6)("isCorrectHelmLong",async()=>{await i("seq\n PEPTIDE1{meI.hHis.Aca.N.T.dE.Thr_PO3H2.Aca.D-Tyr_Et.dV.E.N.D-Orn.D-aThr.Phe_4Me.Thr_PO3H2}$$$$\n PEPTIDE1{meI.hHis.Aca.Cys_SEt.T.dK.Tyr_PO3H2.D-Chg.dV.Phe_ab-dehydro.N.D-Orn.D-aThr.Phe_4Me}$$$$\n PEPTIDE1{Lys_Boc.hHis.Aca.Cys_SEt.T.dK.Tyr_PO3H2.D-Chg.dV.Thr_PO3H2.N.D-Orn.D-aThr.Phe_4Me}$$$$","seq\n meI.hHis.Aca.N.T.dE.Thr_PO3H2.Aca.D-Tyr_Et.dV.E.N.D-Orn.D-aThr.Phe_4Me.Thr_PO3H2\n meI.hHis.Aca.Cys_SEt.T.dK..Tyr_PO3H2.D-Chg.dV.Phe_ab-dehydro.N.D-Orn.D-aThr.Phe_4Me.\n Lys_Boc.hHis.Aca.Cys_SEt.T.dK..Tyr_PO3H2.D-Chg.dV.Thr_PO3H2.N.D-Orn.D-aThr.Phe_4Me.",c.Hi.HELM,c.Hi.SEPARATOR,void 0,"mafft")},{timeout:8e4,skipReason:"Fails in docker"}),(0,t.t6)("isCorrectSeparator",async()=>{await i("seq\n F-W-P-H-E-Y\n Y-N-R-Q-W-Y-V\n M-K-P-S-E-Y-V","seq\n FWPHEY-\n YNRQWYV\n MKPSEYV",c.Hi.SEPARATOR,c.Hi.FASTA,c.YI.PT)}),(0,t.t6)("isCorrectSeparatorLong",async()=>{await i("seq\n M-I-E-V-F-L-F-G-I-V-L-G-L-I-P-I-T-L-A-G-L-F-V-T-A-Y-L-Q-Y-R-R-G-D-Q-L-D-L\n M-M-E-L-V-L-K-T-I-I-G-P-I-V-V-G-V-V-L-R-I-V-D-K-W-L-N-K-D-K\n M-D-R-T-D-E-V-S-N-H-T-H-D-K-P-T-L-T-W-F-E-E-I-F-E-E-Y-H-S-P-F-H-N","seq\n MIEV-FLFGIVLGLIPITLAGLFVTAYLQYRRGDQLDL\n MMEL-VLKTII-GPIVVGVVLRIVDKWLNKDK------\n MDRTDEVSNHTHDKPTLTWFEEIFEEYHSPFHN-----",c.Hi.SEPARATOR,c.Hi.FASTA,c.YI.PT)})});var P=o(1991),L=o.n(P),I=o(7278),_=o(4971);function N(e){return(t=e)&&void 0!==t.onRendered&&void 0!==t.invalidate&&void 0!==t.awaitRendered?e:null;var t}var R=o(6642);async function $(t){const n=await async function(e){return await Ge.files.readAsText(e)}(t),i=e.DataFrame.fromCsv(n);return i.name=t.replace(".csv",""),i}async function O(e,n=5e3){await(0,t.cb)(0),await(0,t.PE)(e.onAfterDrawContent,()=>{},()=>{e.invalidate()},n);const i=e.columns.length;for(let t=0;t<i;++t){const n=e.columns.byIndex(t);if(n){const t=e.cell(n.name,0),[i,o,s]=(0,R.BG)(t),r=N(s.rendererBack);r&&await r.awaitRendered()}}}var H=o(4139),D=o(4356);async function F(e,n){const i=(0,c.J9)(e);console.debug(`Bio: tests: splitters: src=${JSON.stringify(e)}, res=${JSON.stringify(i)} .`),(0,t.J6)(L().count(0).take(i.length).map(e=>i.getOriginal(e)).toArray(),n)}async function k(e,n){const i=(0,I.qp)(e);console.debug(`Bio: tests: splitters: src=${JSON.stringify(e)}, res=${JSON.stringify(i)} .`),(0,t.J6)(L().count(0).take(i.length).map(e=>i.getOriginal(e)).toArray(),n)}(0,t.L1)("splitters",async()=>{(0,t.gM)(async()=>{}),(0,t.Pl)(async()=>{});const e=["M[MeI]YKETLL[MeF]PKTDFPMRGGL[MeA]",["M","MeI","Y","K","E","T","L","L","MeF","P","K","T","D","F","P","M","R","G","G","L","MeA"]],n=["[meI][Pip][dK][Thr_PO3H2][L-hArg(Et,Et)][D-Tyr_Et][Tyr_ab-dehydroMe][dV]EN[D-Orn][D-aThr][Phe_4Me]",["meI","Pip","dK","Thr_PO3H2","L-hArg(Et,Et)","D-Tyr_Et","Tyr_ab-dehydroMe","dV","E","N","D-Orn","D-aThr","Phe_4Me"]],i=["PEPTIDE1{meI.hHis.Aca.N.T.dE.Thr_PO3H2.Aca.D-Tyr_Et.Tyr_ab-dehydroMe.dV.E.N.D-Orn.D-aThr.Phe_4Me}$$$",["meI","hHis","Aca","N","T","dE","Thr_PO3H2","Aca","D-Tyr_Et","Tyr_ab-dehydroMe","dV","E","N","D-Orn","D-aThr","Phe_4Me"]],o=["PEPTIDE1{meI.hHis.Aca.N.T.dK.Thr_PO3H2.Aca.D-Tyr_Et.D-Dap.dV.E.N.pnG.Phe_4Me}$$$",["meI","hHis","Aca","N","T","dK","Thr_PO3H2","Aca","D-Tyr_Et","D-Dap","dV","E","N","pnG","Phe_4Me"]],s=["PEPTIDE1{[meI].[hHis].[Aca].N.T.[dK].[Thr_PO3H2].[Aca].[D-Tyr_Et].[D-Dap].[dV].E.N.[pnG].[Phe_4Me]}$$$",["meI","hHis","Aca","N","T","dK","Thr_PO3H2","Aca","D-Tyr_Et","D-Dap","dV","E","N","pnG","Phe_4Me"]],r=["RNA1{R(U)P.R(T)P.R(G)P.R(C)P.R(A)}$$$$",["R","U","P","R","T","P","R","G","P","R","C","P","R","A"]],a=["RNA1{P.R(U)P.R(T)}$$$$",["P","R","U","P","R","T"]],l=["RNA1{P.R(U).P.R(T)}$$$$",["P","R","U","P","R","T"]];(0,t.t6)("fastaMulti",async()=>{await F(e[0],e[1])}),(0,t.t6)("fastaFromHelm",async()=>{await F(n[0],n[1])}),(0,t.t6)("helm1",async()=>{await k(i[0],i[1])}),(0,t.t6)("helm2",async()=>{await k(o[0],o[1])}),(0,t.t6)("helm3-multichar",async()=>{await k(s[0],s[1])}),(0,t.t6)("testHelm1",async()=>{await k(r[0],r[1])}),(0,t.t6)("testHelm2",async()=>{await k(a[0],a[1])}),(0,t.t6)("testHelm3",async()=>{await k(l[0],l[1])})}),(0,t.L1)("splitters",()=>{let n,i,o;(0,t.gM)(async()=>{n=await(0,u.Q)(),i=await(0,_.pj)(),o=await(0,D.u)(),await i.loadMonomerLibForTests()}),(0,t.Pl)(async()=>{await(0,D.E)(o),await i.loadMonomerLib(!0)}),(0,t.t6)("splitToMonomers",async()=>{const e=await l.dapi.files.readCsv("System:AppData/Bio/samples/MSA.csv"),n=e.getCol("MSA"),i=await l.functions.call("Bio:detectMacromolecule",{col:n});i&&(n.semType=i),n.setTag(c.gp.aligned,H.gN);const o=await l.functions.call("Bio:splitToMonomersTopMenu",{table:e,sequence:n});(0,t.E3)(o.columns.names().includes("17"),!0),await l.data.detectSemanticTypes(o);const s=l.shell.addTableView(o);await O(s.grid),(0,t.E3)(s.grid.dataFrame.id,e.id)}),(0,t.t6)("getHelmMonomers",async()=>{const t=e.DataFrame.fromCsv("HELM,Activity\nPEPTIDE1{hHis.N.T}$$$,5.30751\nPEPTIDE1{hHis.Aca.Cys_SEt}$$$,5.72388\n");await l.data.detectSemanticTypes(t);const n=["hHis","Aca","Cys_SEt","N","T"],i=t.getCol("HELM"),o=await l.functions.call("Bio:getHelmMonomers",{sequence:i}),s=n.filter(e=>!o.includes(e)),r=o.filter(e=>!n.includes(e));if(s.length>0||r.length){const e=[];throw s.length>0&&e.push(`Missed monomers ${JSON.stringify(s)}.`),r.length>0&&e.push(`Unexpected monomers ${JSON.stringify(r)}.`),new Error(e.join(" "))}})});var G=o(8604);(0,t.L1)("monomerLibraries",()=>{let e,i=null;(0,t.gM)(async()=>{e=await(0,_.pj)(),i=(0,D.u)()}),(0,t.Pl)(async()=>{await(0,D.E)(i)}),(0,t.t6)("default",async()=>{await(0,D.E)({exclude:[],explicit:[],duplicateMonomerPreferences:{}}),await e.loadMonomerLib(!0);const n=e.getMonomerLib();(0,t.E3)(n.getPolymerTypes().length>0,!0)}),(0,t.t6)("forTests",async()=>{await e.loadMonomerLibForTests(),function(e,t){const i=t,o=e.getSummaryObj();for(const e in i)i[e]||delete i[e];for(const e in o)o[e]||delete o[e];if(0==Object.keys(i).length&&0!=Object.keys(o).length)throw new Error("Expected empty monomer lib, actual is not.");if(0!=Object.keys(i).length&&0==Object.keys(o).length)throw new Error("Expected non-empty monomer lib, actual is empty.");try{(0,n.Xk)(o,i),(0,n.Xk)(i,o)}catch(e){throw new Error(`Expected monomer lib ${JSON.stringify(i)} does not match actual ${JSON.stringify(o)}.`)}}(e.getMonomerLib(),G.V)}),(0,t.t6)("empty",async()=>{const n=await(0,D.u)();let i=await e.getAvaliableLibraryNames();0===i.length&&(await e.refreshValidLibraryLists(),i=await e.getAvaliableLibraryNames()),n.exclude=i,n.explicit=[],await(0,D.E)(n),await e.loadMonomerLib(!0);const o=e.getMonomerLib().getPolymerTypes();(0,t.E3)(0===o.length,!0)}),(0,t.t6)("override",async()=>{const n={symbol:"over1",name:"Test override monomer 1",molfile:"",author:"Test Author",id:0,rgroups:[],smiles:"",polymerType:"PEPTIDE",monomerType:"Backbone",createDate:null},i=e.getMonomerLib(),o=i.getMonomer(n.polymerType,n.symbol);(0,t.E3)(null==o,!0,`Unexpectedly found monomer '${n.symbol}' `);const s=i.override({[n.polymerType]:{[n.symbol]:n}},"test").getMonomer(n.polymerType,n.symbol);s&&(s.lib=void 0),(0,t.Xk)(s,n)})});var B=o(7389),V=o(1757),U=o.n(V),q=o(1858),W=o(6873),Y=o(5433);async function j(n,i){const o=n(),s=e.DataFrame.fromColumns(o);await l.data.detectSemanticTypes(s);const r=Date.now(),a=(s.columns.byName("MSA"),l.shell.addTableView(s));await O(a.grid),(0,t.E3)(a.grid.dataFrame.id,s.id);const c=Date.now()-r;console.log(`Performance test: ${i}: ${c}ms`)}(0,t.L1)("renderers",()=>{let n;(0,t.gM)(async()=>{n=await(0,u.Q)()}),(0,t.t6)("long sequence performance ",async()=>{await j(()=>(0,W.dW)(1e4),"Long sequences")}),(0,t.t6)("many sequence performance",async()=>{await j(W.fD,"Many sequences")}),(0,t.t6)("rendererMacromoleculeFasta",async()=>{await async function(){const n=await l.dapi.files.readAsText("System:AppData/Bio/samples/FASTA.csv"),i=e.DataFrame.fromCsv(n),o=i.getCol("Sequence"),s=await l.functions.call("Bio:detectMacromolecule",{col:o});s&&(o.semType=s);const r=l.shell.addTableView(i);await l.data.detectSemanticTypes(i),await O(r.grid),(0,t.E3)(r.grid.dataFrame.id,i.id);const a=o.getTag(e.TAGS.CELL_RENDERER);(0,t.E3)(a,"sequence")}()}),(0,t.t6)("rendererMacromoleculeSeparator",async()=>{await async function(){const n=await l.dapi.files.readAsText("System:AppData/Bio/samples/SEPARATOR_PT.csv"),i=e.DataFrame.fromCsv(n),o=i.getCol("sequence"),s=await l.functions.call("Bio:detectMacromolecule",{col:o});s&&(o.semType=s);const r=l.shell.addTableView(i);await l.data.detectSemanticTypes(i),await O(r.grid),(0,t.E3)(r.grid.dataFrame.id,i.id);const a=o.getTag(e.TAGS.CELL_RENDERER);(0,t.E3)(a,"sequence")}()}),(0,t.t6)("rendererMacromoleculeDifference",async()=>{await async function(){const n=e.Column.fromStrings("SequencesDiff",["meI/hHis/Aca/N/T/dK/Thr_PO3H2/Aca#D-Tyr_Et/Tyr_ab-dehydroMe/meN/E/N/dV"]);n.meta.units=c.Hi.SEPARATOR,n.setTag(c.gp.separator,"/"),n.setTag(c.gp.aligned,"SEQ"),n.setTag(c.gp.alphabet,"UN"),n.setTag(c.gp.alphabetIsMultichar,"true"),n.semType=H.uF.MACROMOLECULE_DIFFERENCE;const i=e.DataFrame.fromColumns([n]),o=l.shell.addTableView(i);await l.data.detectSemanticTypes(i),await O(o.grid),(0,t.E3)(o.grid.dataFrame.id,i.id);const s=n.getTag(e.TAGS.CELL_RENDERER);(0,t.E3)(s,H.uF.MACROMOLECULE_DIFFERENCE)}()}),(0,t.t6)("afterMsa",async()=>{await async function(){const i=await l.dapi.files.readAsText("System:AppData/Bio/samples/FASTA.fasta"),o=(await l.functions.call("Bio:importFasta",{fileContent:i}))[0],s=o.getCol("sequence"),r=await l.functions.call("Bio:detectMacromolecule",{col:s});r&&(s.semType=r);const a=l.shell.addTableView(o);await l.data.detectSemanticTypes(o),console.log("Bio: tests/renderers/afterMsa, table view"),await O(a.grid),(0,t.E3)(a.grid.dataFrame.id,o.id),console.log(`Bio: tests/renderers/afterMsa, src before test semType="${s.semType}", units="${s.meta.units}", cell.renderer="${s.getTag(e.TAGS.CELL_RENDERER)}"`),(0,t.E3)(s.semType,e.SEMTYPE.MACROMOLECULE),(0,t.E3)(s.meta.units,c.Hi.FASTA),(0,t.E3)(s.getTag(c.gp.aligned),"SEQ"),(0,t.E3)(s.getTag(c.gp.alphabet),c.YI.PT),(0,t.E3)(s.getTag(e.TAGS.CELL_RENDERER),"sequence");const u=await(0,M.D)({col:s},n);await O(a.grid),(0,t.E3)(a.grid.dataFrame.id,o.id),(0,t.E3)(u.semType,e.SEMTYPE.MACROMOLECULE),(0,t.E3)(u.meta.units,c.Hi.FASTA),(0,t.E3)(u.getTag(c.gp.aligned),"SEQ.MSA"),(0,t.E3)(u.getTag(c.gp.alphabet),c.YI.PT),(0,t.E3)(u.getTag(e.TAGS.CELL_RENDERER),"sequence"),n.getSeqHandler(u)}()}),(0,t.t6)("afterConvert",async()=>{await async function(){const i=await l.dapi.files.readAsText("System:AppData/Bio/samples/FASTA_PT.csv"),o=e.DataFrame.fromCsv(i),s=o.getCol("sequence"),r=await l.functions.call("Bio:detectMacromolecule",{col:s});r&&(s.semType=r);const a=l.shell.addTableView(o);await l.data.detectSemanticTypes(o);const u=await(0,Y.r)(s,n,c.Hi.SEPARATOR,"/");await O(a.grid),(0,t.E3)(a.grid.dataFrame.id,o.id);const h=u.getTag(e.TAGS.CELL_RENDERER);(0,t.E3)(h,"sequence"),n.getSeqHandler(u)}()}),(0,t.t6)("afterConvertToHelm",async()=>{await async function(){const i=await l.dapi.files.readCsv("System:AppData/Bio/samples/FASTA_PT.csv"),o=l.shell.addTableView(i);await O(o.grid),await i.meta.detectSemanticTypes(),await l.data.detectSemanticTypes(i);const s=i.getCol("sequence"),r=n.getSeqHandler(s).convert(c.Hi.HELM);i.columns.add(r),await O(o.grid),(0,t.E3)(r.getTag(e.TAGS.CELL_RENDERER),"helm")}()}),(0,t.t6)("selectRendererBySemType",async()=>{await async function(){const n=e.Column.fromStrings("SequencesDiff",["meI/hHis/Aca/N/T/dK/Thr_PO3H2/Aca#D-Tyr_Et/Tyr_ab-dehydroMe/meN/E/N/dV"]);n.meta.units=c.Hi.SEPARATOR,n.setTag(c.gp.separator,"/"),n.setTag(c.gp.aligned,"SEQ"),n.setTag(c.gp.alphabet,"UN"),n.setTag(c.gp.alphabetIsMultichar,"true"),n.semType=H.uF.MACROMOLECULE_DIFFERENCE;const i=e.DataFrame.fromColumns([n]);l.shell.addTableView(i),await(0,t.cb)(100);const o=n.getTag(e.TAGS.CELL_RENDERER);if("MacromoleculeDifference"!==o)throw new Error(`Units 'separator', separator '/' and semType 'MacromoleculeDifference' have been manually set on column but after df was added as table, view renderer has set to '${o}' instead of correct 'MacromoleculeDifference'.`)}()}),(0,t.t6)("scatterPlotTooltip",async()=>{await async function(){const n=e.DataFrame.fromCsv(i);n.currentRowIdx=0;const o=l.shell.addTableView(n);await n.meta.detectSemanticTypes(),await l.data.detectSemanticTypes(n);const s=n.plot.scatter({x:"x",y:"y"});o.dockManager.dock(s,e.DOCK_TYPE.RIGHT,null),await Promise.all([(0,t.PE)(s.onAfterDrawScene,()=>{},()=>{s.invalidateCanvas()},1e3),O(o.grid,500)]);const r=s.root.getBoundingClientRect(),a=s.worldToScreen(1,0),c=new MouseEvent("mousemove",{cancelable:!0,bubbles:!0,view:window,button:0,clientX:r.left+a.x,clientY:r.top+a.y}),u=U()(s.root).find("canvas").get()[0];await(0,t.PE)(e.debounce((0,q.fromEvent)(u,"mousemove"),200),()=>{Ge.logger.debug(`Test: event, currentRowIdx=${n.currentRowIdx}`),(0,t.E3)(U()(B.tooltip.root).find("div table.d4-row-tooltip-table tr td canvas").length,1),(0,t.E3)(s.hitTest(a.x,a.y),1)},()=>{u.dispatchEvent(c)},500),await O(o.grid,500)}()});const i="seq,x,y\nACGGTGTCGT,0,0\nCGGTATCCCT,1,0\nCTCGGCATGC,2,0\n"});var K=o(819);(0,t.L1)("renderers: monomerPlacer",()=>{let n,i;(0,t.gM)(async()=>{n=await(0,_.pj)(),i=await(0,D.u)(),await n.loadMonomerLibForTests()}),(0,t.Pl)(async()=>{await(0,D.E)(i),await n.loadMonomerLib(!0)});const o={splitter:{csv:"id,seq\nid1,m1-M-m3-mon4-mon5-N-T-MON8-N9\nid2,m1-mon2-m3-mon4-mon5-Num-MON8-N9\nid3,mon1-M-mon3-mon4-mon5-MON8-N9\n",testList:[{src:{row:0,x:-1},tgt:{pos:null}},{src:{row:1,x:0},tgt:{pos:null}},{src:{row:1,x:5},tgt:{pos:0}},{src:{row:1,x:6},tgt:{pos:0}},{src:{row:1,x:26},tgt:{pos:1}},{src:{row:1,x:160},tgt:{pos:6}},{src:{row:1,x:190},tgt:{pos:7}},{src:{row:2,x:140},tgt:{pos:5}},{src:{row:2,x:145},tgt:{pos:5}}]},splitterMsa:{csv:"id,seq\nid1,m1-M-m3-mon4-mon5-N-T-MON8-N9\nid2,m1-mon2-m3-mon4-mon5-Num--MON8-N9\nid3,\nid4,mon1-M-mon3-mon4-mon5---MON8-N9\n",testList:[{src:{row:0,x:-1},tgt:{pos:null}},{src:{row:1,x:0},tgt:{pos:null}},{src:{row:1,x:1},tgt:{pos:null}},{src:{row:1,x:4},tgt:{pos:null}},{src:{row:1,x:5},tgt:{pos:0}},{src:{row:1,x:37},tgt:{pos:0}},{src:{row:1,x:38},tgt:{pos:1}},{src:{row:1,x:170},tgt:{pos:5}},{src:{row:1,x:200},tgt:{pos:5}},{src:{row:2,x:20},tgt:{pos:null}},{src:{row:3,x:170},tgt:{pos:5}},{src:{row:3,x:200},tgt:{pos:5}},{src:{row:3,x:297},tgt:{pos:null}}]},fastaMsa:{csv:"id,seq\nid1,QQYNIYPLT\nid2,QQWSSFPYT\nid3,\nid3,QHIRE--LT\n",testList:[{src:{row:1,x:-1},tgt:{pos:null}},{src:{row:1,x:0},tgt:{pos:null}},{src:{row:1,x:1},tgt:{pos:null}},{src:{row:1,x:19},tgt:{pos:0}},{src:{row:1,x:170},tgt:{pos:8}},{src:{row:1,x:171},tgt:{pos:8}},{src:{row:2,x:5},tgt:{pos:null}},{src:{row:3,x:170},tgt:{pos:8}},{src:{row:3,x:181},tgt:{pos:null}}]}};for(const[n,i]of Object.entries(o))(0,t.t6)(`getPosition-${n}`,async()=>{const t=e.DataFrame.fromCsv(i.csv);await l.data.detectSemanticTypes(t);const n=t.getCol("seq"),o=new K.Jy(null,n,Ge.logger,3,()=>({font:"12px monospace",fontCharWidth:7,separatorWidth:12,monomerToShort:c.zS}));await o.init();const s=i.testList;for(let e=0;e<n.length;++e)o.getCellMonomerLengths(e,1e4);const r=[];for(const[e,t]of L().enumerate(s)){const t={pos:o.getPosition(e.src.row,e.src.x,1e4)};e.tgt.pos!=t.pos&&r.push(`Test src ${JSON.stringify(e.src)} expected tgt ${JSON.stringify(e.tgt)}, but get ${JSON.stringify({res:t})}`)}if(r.length>0)throw new Error("Test failed error(s):\n"+r.join(", \n"))});const s=[10,20,30,40,50,60],r={left:{x:3,tgt:null},c0left:{x:10,tgt:0},c0mid:{x:12,tgt:0},c0right:{x:19,tgt:0},c1left:{x:20,tgt:1},c2right:{x:39,tgt:2},c4left:{x:50,tgt:4},c4right:{x:59,tgt:4},max:{x:60,tgt:null},right:{x:65,tgt:null}};for(const[e,n]of Object.entries(r))(0,t.t6)("hitBounds-"+e,async()=>{const e=(0,K.Bb)(s,n.x);(0,t.E3)(e,n.tgt)});const a={mono1:{src:{csv:"seq\nm1/m2/m3/m4/m5/m6/m7/m8/m9\nn1/m2/n3/m4/n5/m6/n7/m8/n9\nm1/n2/m3/n4/m5/n6/m7/n8/m9\n"},tgt:{lengths:[5,31,57,83,109,135,161,187,213,239]}},monoWithGaps:{src:{csv:"seq\nm1/m2/m3/m4/m5/m6//m8/m9\nn1/m2/n3/m4/n5/m6//m8/n9\nm1/n2/m3/n4/m5/n6/m7/n8/m9\n"},tgt:{lengths:[5,31,57,83,109,135,161,187,213,239]}},monoWithGapColumn:{src:{csv:"seq\nm1/m2/m3/m4/m5/m6//m8/m9\nn1/m2/n3/m4/n5/m6//m8/n9\nm1/n2/m3/n4/m5///n8/m9\n"},tgt:{lengths:[5,31,57,83,109,135,161,180,206,232]}}};for(const[n,i]of Object.entries(a))(0,t.t6)(`getCellMonomerLengths-${n}`,async()=>{const n=e.DataFrame.fromCsv(i.src.csv);await l.data.detectSemanticTypes(n);const o=n.getCol("seq"),s=new K.Jy(null,o,Ge.logger,3,()=>({fontCharWidth:7,font:"12px monospace",separatorWidth:12,monomerToShort:c.zS}));await s.init();const r=s.getCellMonomerLengths(0,1e3)[1];(0,t.J6)(r,i.tgt.lengths)})}),(0,t.L1)("converters",()=>{let n,i;(0,t.gM)(async()=>{n=await(0,u.Q)()}),function(e){e.fastaPt="fastaPt",e.separatorPt="separatorPt",e.helmPt="helmPt",e.fastaDna="fastaDna",e.separatorDna="separatorDna",e.helmDna="helmDna",e.fastaRna="fastaRna",e.separatorRna="separatorRna",e.helmRna="helmRna",e.fastaGaps="fastaGaps",e.separatorGaps="separatorGaps",e.helmGaps="helmGaps",e.fastaUn="fastaUn",e.separatorUn="separatorUn",e.helmUn="helmUn",e.helmLoneDeoxyribose="helmLoneDeoxyribose",e.helmLoneRibose="helmLoneRibose",e.helmLonePhosphorus="helmLonePhosphorus",e.fastaLoneDeoxyribose="fastaLoneDeoxyribose",e.fastaLoneRibose="fastaLoneRibose",e.fastaLonePhosphorus="fastaLonePhosphorus"}(i||(i={}));const o={[i.fastaPt]:"seq\nFWPHEYFWPHEY\nYNRQWYVYNRQWYV\nMKPSEYVMKPSEYV",[i.separatorPt]:"seq\nF-W-P-H-E-Y-F-W-P-H-E-Y\nY-N-R-Q-W-Y-V-Y-N-R-Q-W-Y-V\nM-K-P-S-E-Y-V-M-K-P-S-E-Y-V",[i.helmPt]:"seq\nPEPTIDE1{F.W.P.H.E.Y.F.W.P.H.E.Y}$$$$\nPEPTIDE1{Y.N.R.Q.W.Y.V.Y.N.R.Q.W.Y.V}$$$$\nPEPTIDE1{M.K.P.S.E.Y.V.M.K.P.S.E.Y.V}$$$$",[i.fastaDna]:"seq\nACGTCACGTC\nCAGTGTCAGTGT\nTTCAACTTCAAC",[i.separatorDna]:"seq\nA/C/G/T/C/A/C/G/T/C\nC/A/G/T/G/T/C/A/G/T/G/T\nT/T/C/A/A/C/T/T/C/A/A/C",[i.helmDna]:"seq\nRNA1{d(A)p.d(C)p.d(G)p.d(T)p.d(C)p.d(A)p.d(C)p.d(G)p.d(T)p.d(C)p}$$$$\nRNA1{d(C)p.d(A)p.d(G)p.d(T)p.d(G)p.d(T)p.d(C)p.d(A)p.d(G)p.d(T)p.d(G)p.d(T)p}$$$$\nRNA1{d(T)p.d(T)p.d(C)p.d(A)p.d(A)p.d(C)p.d(T)p.d(T)p.d(C)p.d(A)p.d(A)p.d(C)p}$$$$",[i.fastaRna]:"seq\nACGUCACGUC\nCAGUGUCAGUGU\nUUCAACUUCAAC",[i.separatorRna]:"seq\nA*C*G*U*C*A*C*G*U*C\nC*A*G*U*G*U*C*A*G*U*G*U\nU*U*C*A*A*C*U*U*C*A*A*C",[i.helmRna]:"seq\nRNA1{r(A)p.r(C)p.r(G)p.r(U)p.r(C)p.r(A)p.r(C)p.r(G)p.r(U)p.r(C)p}$$$$\nRNA1{r(C)p.r(A)p.r(G)p.r(U)p.r(G)p.r(U)p.r(C)p.r(A)p.r(G)p.r(U)p.r(G)p.r(U)p}$$$$\nRNA1{r(U)p.r(U)p.r(C)p.r(A)p.r(A)p.r(C)p.r(U)p.r(U)p.r(C)p.r(A)p.r(A)p.r(C)p}$$$$",[i.fastaGaps]:"seq\nFW-PH-EYYFW-PH-EYY\nFYNRQWYV-FYNRQWYV-\nFKP-Q-SEYVFKP-Q-SEYV",[i.separatorGaps]:"seq\nF/W//P/H//E/Y/Y/F/W//P/H//E/Y/Y\nF/Y/N/R/Q/W/Y/V//F/Y/N/R/Q/W/Y/V/\nF/K/P//Q//S/E/Y/V/F/K/P//Q//S/E/Y/V",[i.helmGaps]:"seq\nPEPTIDE1{F.W.*.P.H.*.E.Y.Y.F.W.*.P.H.*.E.Y.Y}$$$$\nPEPTIDE1{F.Y.N.R.Q.W.Y.V.*.F.Y.N.R.Q.W.Y.V.*}$$$$\nPEPTIDE1{F.K.P.*.Q.*.S.E.Y.V.F.K.P.*.Q.*.S.E.Y.V}$$$$",[i.fastaUn]:"seq\n[meI][hHis][Aca]NT[dE][Thr_PO3H2][Aca]D[meI][hHis][Aca]NT[dE][Thr_PO3H2][Aca]D\n[meI][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca][Tyr_PO3H2][meI][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca][Tyr_PO3H2]\n[Lys_Boc][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca][Tyr_PO3H2][Lys_Boc][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca]",[i.separatorUn]:"seq\nmeI-hHis-Aca-N-T-dE-Thr_PO3H2-Aca-D-meI-hHis-Aca-N-T-dE-Thr_PO3H2-Aca-D\nmeI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-meI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2\nLys_Boc-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-Lys_Boc-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca",[i.helmUn]:"seq\nPEPTIDE1{meI.hHis.Aca.N.T.dE.Thr_PO3H2.Aca.D.meI.hHis.Aca.N.T.dE.Thr_PO3H2.Aca.D}$$$$\nPEPTIDE1{meI.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.Tyr_PO3H2.meI.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.Tyr_PO3H2}$$$$\nPEPTIDE1{Lys_Boc.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.Tyr_PO3H2.Lys_Boc.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca}$$$$",[i.helmLoneDeoxyribose]:"seq\nRNA1{d(A).d(C).d(G).d(T).d(C).d(A).d(C).d(G).d(T).d(C)}$$$$\nRNA1{d(C).d(A).d(G).d(T).d(G).d(T)p.d(C).d(A).d(G).d(T).d(G).d(T)p}$$$$\nRNA1{d(T).d(T).d(C).d(A).d(A).d(C)p.d(T).d(T).d(C).d(A).d(A).d(C)p}$$$$",[i.helmLoneRibose]:"seq\nRNA1{r(A).r(C).r(G).r(U).r(C).r(A).r(C).r(G).r(U).r(C)}$$$$\nRNA1{r(C).r(A).r(G).r(U).r(G).r(U)p.r(C).r(A).r(G).r(U).r(G).r(U)p}$$$$\nRNA1{r(U).r(U).r(C).r(A).r(A).r(C)p.r(U).r(U).r(C).r(A).r(A).r(C)p}$$$$",[i.helmLonePhosphorus]:"seq\nRNA1{p.p.r(A)p.r(C)p.r(G)p.r(U)p.r(C)p.r(A)p.r(C)p.r(G)p.r(U)p.r(C)p}$$$$\nRNA1{p.p.r(C)p.r(A)p.p.r(G)p.r(U)p.r(G)p.r(U)p.r(C)p.r(A)p.p.r(G)p.r(U)p.r(G)p.r(U)p}$$$$\nRNA1{p.r(U)p.r(U)p.r(C)p.r(A)p.r(A)p.r(C)p.r(U)p.r(U)p.r(C)p.r(A)p.r(A)p.r(C)p.p.p}$$$$"},s=new Set(Object.values(c.gp));async function r(t){const n=o[t],i=e.DataFrame.fromCsv(n);return await l.data.detectSemanticTypes(i),i}function a(e,i){if(e===c.Hi.SEPARATOR&&!i)throw new Error(`Argument 'separator' is mandatory for target notation '${e.toString()}'.`);return function(o){const s=n.getSeqHandler(o).convert(e,i);return(0,t.E3)(s.meta.units,e),s}}async function h(e,i,o){const a=(await r(e)).getCol("seq"),l=i(a),u=(await r(o)).getCol("seq");(0,t.J6)(l.toList(),u.toList());const h=n.getSeqHandler(a),d=n.getSeqHandler(l);for(const[e,n]of Object.entries(u.tags)){if(!s.has(e)||h.notation===c.Hi.HELM&&[c.gp.alphabet,c.gp.alphabetIsMultichar].includes(e)||d.notation===c.Hi.HELM&&[c.gp.alphabet,c.gp.alphabetIsMultichar].includes(e))continue;const i=l.getTag(e);(0,t.E3)(i,n,`Tag '${e}' expected value '${n}' is not equal to actual '${i}'.`)}}(0,t.t6)("testFastaPtToSeparator",async()=>{await h(i.fastaPt,a(c.Hi.SEPARATOR,"-"),i.separatorPt)}),(0,t.t6)("testFastaDnaToSeparator",async()=>{await h(i.fastaDna,a(c.Hi.SEPARATOR,"/"),i.separatorDna)}),(0,t.t6)("testFastaRnaToSeparator",async()=>{await h(i.fastaRna,a(c.Hi.SEPARATOR,"*"),i.separatorRna)}),(0,t.t6)("testFastaGapsToSeparator",async()=>{await h(i.fastaGaps,a(c.Hi.SEPARATOR,"/"),i.separatorGaps)}),(0,t.t6)("testFastaUnToSeparator",async()=>{await h(i.fastaUn,a(c.Hi.SEPARATOR,"-"),i.separatorUn)}),(0,t.t6)("testFastaPtToHelm",async()=>{await h(i.fastaPt,a(c.Hi.HELM),i.helmPt)}),(0,t.t6)("testFastaDnaToHelm",async()=>{await h(i.fastaDna,a(c.Hi.HELM),i.helmDna)}),(0,t.t6)("testFastaRnaToHelm",async()=>{await h(i.fastaRna,a(c.Hi.HELM),i.helmRna)}),(0,t.t6)("testFastaGapsToHelm",async()=>{await h(i.fastaGaps,a(c.Hi.HELM),i.helmGaps)}),(0,t.t6)("testSeparatorPtToFasta",async()=>{await h(i.separatorPt,a(c.Hi.FASTA),i.fastaPt)}),(0,t.t6)("testSeparatorDnaToFasta",async()=>{await h(i.separatorDna,a(c.Hi.FASTA),i.fastaDna)}),(0,t.t6)("testSeparatorRnaToFasta",async()=>{await h(i.separatorRna,a(c.Hi.FASTA),i.fastaRna)}),(0,t.t6)("testSeparatorGapsToFasta",async()=>{await h(i.separatorGaps,a(c.Hi.FASTA),i.fastaGaps)}),(0,t.t6)("testSeparatorUnToFasta",async()=>{await h(i.separatorUn,a(c.Hi.FASTA),i.fastaUn)}),(0,t.t6)("testSeparatorPtToHelm",async()=>{await h(i.separatorPt,a(c.Hi.HELM),i.helmPt)}),(0,t.t6)("testSeparatorDnaToHelm",async()=>{await h(i.separatorDna,a(c.Hi.HELM),i.helmDna)}),(0,t.t6)("testSeparatorRnaToHelm",async()=>{await h(i.separatorRna,a(c.Hi.HELM),i.helmRna)}),(0,t.t6)("testSeparatorGapsToHelm",async()=>{await h(i.separatorGaps,a(c.Hi.HELM),i.helmGaps)}),(0,t.t6)("testHelmDnaToFasta",async()=>{await h(i.helmDna,a(c.Hi.FASTA),i.fastaDna)}),(0,t.t6)("testHelmRnaToFasta",async()=>{await h(i.helmRna,a(c.Hi.FASTA),i.fastaRna)}),(0,t.t6)("testHelmPtToFasta",async()=>{await h(i.helmPt,a(c.Hi.FASTA),i.fastaPt)}),(0,t.t6)("testHelmUnToFasta",async()=>{await h(i.helmUn,a(c.Hi.FASTA),i.fastaUn)}),(0,t.t6)("testHelmDnaToSeparator",async()=>{await h(i.helmDna,a(c.Hi.SEPARATOR,"/"),i.separatorDna)}),(0,t.t6)("testHelmRnaToSeparator",async()=>{await h(i.helmRna,a(c.Hi.SEPARATOR,"*"),i.separatorRna)}),(0,t.t6)("testHelmPtToSeparator",async()=>{await h(i.helmPt,a(c.Hi.SEPARATOR,"-"),i.separatorPt)}),(0,t.t6)("testHelmUnToSeparator",async()=>{await h(i.helmUn,a(c.Hi.SEPARATOR,"-"),i.separatorUn)}),(0,t.t6)("testHelmLoneRibose",async()=>{await h(i.helmLoneRibose,a(c.Hi.FASTA),i.fastaRna)}),(0,t.t6)("testHelmLoneDeoxyribose",async()=>{await h(i.helmLoneDeoxyribose,a(c.Hi.SEPARATOR,"/"),i.separatorDna)}),(0,t.t6)("testHelmLonePhosphorus",async()=>{await h(i.helmLonePhosphorus,a(c.Hi.FASTA),i.fastaRna)});for(const e of v)(0,t.t6)(`testBilnToHelm_${e.name}`,async()=>{await y(e.biln,e.helm,n)});for(const e of C)(0,t.t6)(`testHelmToBiln_${e.name}`,async()=>{await b(e.helm,e.biln,n)})});var z=o(3516);(0,t.L1)("fastaFileHandler",()=>{const n=["description:1","description:2","description:3","description:4"],i=(e.Column.fromStrings("description",n),["MDYKETLLMPKTDFPMRGGLPNKEPQIQEKW","MIEVFLFGIVLGLIPITLAGLFVTAYLQYRRGDQLDL","MMELVLKTIIGPIVVGVVLRIVDKWLNKDK","MDRTDEVSNHTHDKPTLTWFEEIFEEYHSPFHN"]);function o(e){const o=new z.m(e),s=o.descriptionsArray,r=o.sequencesArray;(0,t.J6)([s,r],[n,i])}(0,t.t6)("testNormalFormatting",async()=>{o(">description:1\nMDYKETLLMPKTDFPMRGGLPNKEPQIQEKW\n\n>description:2\nMIEVFLFGIVLGLIPITLAGLFVTAYLQYRRGDQLDL\n\n>description:3\nMMELVLKTIIGPIVVGVVLRIVDKWLNKDK\n\n>description:4\nMDRTDEVSNHTHDKPTLTWFEEIFEEYHSPFHN\n")}),(0,t.t6)("testExtraSpaces",async()=>{o(">description:1\n MDYKETLLMPKTDFPMRGGLPNKEPQIQEKW\n\n>description:2\nMI EVF LFGIVLGLI PITLAGLFVTAY LQYRRGDQLDL\n\n>description:3\nM MELVLKTI IGPI VVGVVLR IVDKWLNKDK\n\n>description:4\nMDR TDEVSNHTHDKP TLTWFEEIFEEYHSPFHN\n ")}),(0,t.t6)("testExtraNewlines",async()=>{o(">description:1\n\nMDYKETLLMPKTDFPMRGGLPNKEPQIQEKW\n\n>description:2\nMIEVF\nLFGIVLGLI\nPITLAGLFVTA\nYLQYRRGDQLDL\n\n>description:3\nM\nME\n\nLVLKTIIG\n\nPIVVGVVLRI\nVDKWLNKDK\n\n\n>description:4\n\nMDRT\n\nDEVSNHTHDKP\n\nTLTWFEEIFEE\n\n\n\nYHSPFHN\n")})});var Z=o(3890);(0,t.L1)("fastaExport",()=>{let n,i;(0,t.gM)(async()=>{n=await(0,u.Q)()}),function(e){e.single="single",e.multi="multi"}(i||(i={}));const o={[i.single]:{src:"MDYKETLLMPKTDFPMRGGLP",tgt:["MDYKETLLMP","KTDFPMRGGL","P"]},[i.multi]:{src:"M[MeI]YKETLL[MeF]PKTDFPMRGGL[MeA]",tgt:["M[MeI]YKETLL[MeF]P","KTDFPMRGGL","[MeA]"]}};let s;!function(e){e.test1="test1",e.test2="test2"}(s||(s={}));const r={[s.test1]:{srcCsv:"id,seq\n1,MDYKETLLMP\n2,KTDFPMRGGL\n3,P",idCols:["id"],seqCol:"seq",lineWidth:10,tgtFasta:">1\nMDYKETLLMP\n>2\nKTDFPMRGGL\n>3\nP\n"},[s.test2]:{srcCsv:"id,id2,seq\n1,seqA,M[MeI]YKETLL[MeF]P\n2,seqB,KTDFPMRGGL\n3,seqC,[MeA]\n",idCols:["id2","id"],seqCol:"seq",lineWidth:5,tgtFasta:">seqA|1\nM[MeI]YKE\nTLL[MeF]P\n>seqB|2\nKTDFP\nMRGGL\n>seqC|3\n[MeA]\n"}};function a(i,s=10){const r=o[i].src,a=e.Column.fromStrings("src",[r]);a.semType=e.SEMTYPE.MACROMOLECULE,a.meta.units=c.Hi.FASTA;const l=n.getSeqHandler(a).getSplitted(0),u=(0,Z.aS)(l,s),h=o[i].tgt;(0,t.J6)(u,h)}async function l(i){const o=e.DataFrame.fromCsv(i.srcCsv),s=o.getCol(i.seqCol);s.semType=e.SEMTYPE.MACROMOLECULE,s.meta.units=c.Hi.FASTA;const r=i.idCols.map(e=>o.getCol(e)),a=n.getSeqHandler(s),l=(0,Z.wz)(r,a,i.lineWidth);(0,t.E3)(l,i.tgtFasta)}(0,t.t6)("wrapSequenceSingle",async()=>{a(i.single,10)}),(0,t.t6)("wrapSequenceMulti",async()=>{a(i.multi,10)}),(0,t.t6)("saveAsFastaTest1",async()=>{l(r[s.test1])}),(0,t.t6)("saveAsFastaTest2",async()=>{l(r[s.test2])})});var X=o(4152),Q=o(439);const J=Q._S;(0,t.L1)("bio",()=>{let n;(0,t.gM)(async()=>{n=await(0,u.Q)()});const o="seq\nACGTCT\nCAGTGT\nTTCAAC";(0,t.t6)("testGetStatsHelm1",async()=>{const n=e.DataFrame.fromCsv("seq\nPEPTIDE1{meI}$$$$").getCol("seq");n.semType=e.SEMTYPE.MACROMOLECULE,n.meta.units=c.Hi.HELM;const i=(0,I.vZ)(n,1,c.qp);(0,t.Xk)(i.freq,{meI:1}),(0,t.E3)(i.sameLength,!0)}),(0,t.t6)("testGetStatsN1",async()=>{await function(n){const i=e.DataFrame.fromCsv(n).col("seq");i.semType=e.SEMTYPE.MACROMOLECULE,i.meta.units=c.Hi.FASTA;const o=(0,I.vZ)(i,5,c.J9);(0,t.Xk)(o.freq,{A:4,C:5,G:3,T:6}),(0,t.E3)(o.sameLength,!0)}(o)}),(0,t.t6)("testGetAlphabetSimilarity",async()=>{await async function(){const e={A:2041,C:3015,G:3015,T:2048,[J]:1e3},n=new Set(Object.keys(a.Q.Names)),i=(0,c.nq)(e,n);(0,t.E3)(i>.6,!0)}()}),(0,t.t6)("testPickupPaletteN1",async()=>{await async function(i){const o=e.DataFrame.fromCsv(i).col("seq");o.semType=e.SEMTYPE.MACROMOLECULE,o.meta.units=c.Hi.FASTA;const s=(0,c.SM)(o,n);(0,t.E3)(s instanceof a.A,!0)}(o)}),(0,t.t6)("testPickupPaletteN1e",async()=>{await async function(){const i=e.DataFrame.fromCsv("seq\nACGTAT\nCAGTTG\nTTCG2C").col("seq");i.semType=e.SEMTYPE.MACROMOLECULE,i.meta.units=c.Hi.FASTA;const o=(0,c.SM)(i,n);(0,t.E3)(o instanceof a.A,!0)}()}),(0,t.t6)("testPickupPaletteAA1",async()=>{await async function(){const o=e.DataFrame.fromCsv("seq\nFWPHEYV\nYNRQWYV\nMKPSEYV").col("seq");o.semType=e.SEMTYPE.MACROMOLECULE,o.meta.units=c.Hi.FASTA;const s=(0,c.SM)(o,n);(0,t.E3)(s instanceof i.X,!0)}()}),(0,t.t6)("testPickupPaletteX",async()=>{await async function(){const i=e.DataFrame.fromCsv("seq\nXZJ{}2\n5Z4733\n3Z6></\n675687").col("seq");i.semType=e.SEMTYPE.MACROMOLECULE,i.meta.units=c.Hi.FASTA;const o=(0,c.SM)(i,n);(0,t.E3)(o instanceof X.$u,!0)}()})}),(0,t.L1)("WebLogo.monomerToShort",()=>{(0,t.t6)("longMonomerSingle",async()=>{(0,t.E3)((0,c.zS)("S",5),"S")}),(0,t.t6)("longMonomerShort",async()=>{(0,t.E3)((0,c.zS)("Short",5),"Short")}),(0,t.t6)("longMonomerLong56",async()=>{(0,t.E3)((0,c.zS)("Long56",6),"Long56")}),(0,t.t6)("longMonomerComplexFirstPartShort",async()=>{(0,t.E3)((0,c.zS)("Long-long",5),"Long…")}),(0,t.t6)("longMonomerComplexFirstPartLong56",async()=>{(0,t.E3)((0,c.zS)("Long56-long",6),"Long5…")}),(0,t.t6)("monomerToShort",async()=>{const e=[["AbC","AbC"],["AbCd","Ab…"],["ABc","ABc"],["ABcd","AB…"],["A_b","A_b"],["A_bc","A…"],["Ab_c","Ab…"],["A1_b","A1…"],["Abc_d","Ab…"],["Abcd_e","Ab…"],["A-b","A-b"],["A-bc","A…"],["Ab-c","Ab…"],["A1-b","A1…"],["Abc-d","Ab…"],["Abcd-e","Ab…"],["A","A"],["Ab","Ab"],["Abc","Abc"],["Ab…","Ab…"],["Abcd","Ab…"],["Abcde","Ab…"]],n=e.map(e=>e[0]),i=e.map(e=>e[1]),o=n.map(e=>(0,c.zS)(e,3));(0,t.J6)(o,i)})});var ee=o(250);const te=Q._S;function ne(e,n){(0,t.E3)(e.name,n.name),(0,t.J6)(e.getMonomers(),n.getMonomers());for(const i of e.getMonomers())(0,t.E3)(e.getFreq(i).rowCount,n.getFreq(i).rowCount)}(0,t.L1)("WebLogo.positions",()=>{let n;(0,t.gM)(async()=>{n=await(0,u.Q)()});const i="seq\nATC-G-TTGC--\nATC-G-TTGC--\n-TC-G-TTGC--\n-TC-GCTTGC--\n-TC-GCTTGC--";(0,t.t6)("allPositions",async()=>{const n=e.DataFrame.fromCsv(i),o=l.shell.addTableView(n),s=n.getCol("seq");s.semType=e.SEMTYPE.MACROMOLECULE,s.meta.units=c.Hi.FASTA,s.setTag(c.gp.alphabet,c.YI.DNA),s.setTag(c.gp.aligned,"SEQ.MSA");const r=await n.plot.fromType("WebLogo");await(0,t.PE)(r.onLayoutCalculated,()=>{},()=>{o.dockManager.dock(r.root,e.DOCK_TYPE.DOWN)},500,"Layout calculate timeout");const a=r.positions,u=[new ee.Ue(0,"1",{A:new ee.Tc(2),[te]:new ee.Tc(3)}),new ee.Ue(1,"2",{T:new ee.Tc(5)}),new ee.Ue(2,"3",{C:new ee.Tc(5)}),new ee.Ue(3,"4",{[te]:new ee.Tc(5)}),new ee.Ue(4,"5",{G:new ee.Tc(5)}),new ee.Ue(5,"6",{[te]:new ee.Tc(3),C:new ee.Tc(2)}),new ee.Ue(6,"7",{T:new ee.Tc(5)}),new ee.Ue(7,"8",{T:new ee.Tc(5)}),new ee.Ue(8,"9",{G:new ee.Tc(5)}),new ee.Ue(9,"10",{C:new ee.Tc(5)}),new ee.Ue(10,"11",{[te]:new ee.Tc(5)}),new ee.Ue(11,"12",{[te]:new ee.Tc(5)})];(0,t.E3)(a.length,u.length);for(let e=0;e<a.length;e++){(0,t.E3)(a[e].name,u[e].name);for(const n of a[e].getMonomers())(0,t.E3)(a[e].getFreq(n).rowCount,u[e].getFreq(n).rowCount)}await r.awaitRendered()}),(0,t.t6)("positions with shrinkEmptyTail option true (filtered)",async()=>{const n=e.DataFrame.fromCsv("seq\n-TC-G-TTGC--\n-TC-GCTTGC--\n-T--C-GT-\n-T--C-GT-\n-T--C-GT-\n-T--CCGT-"),i=l.shell.addTableView(n),o=n.getCol("seq");o.semType=e.SEMTYPE.MACROMOLECULE,o.meta.units=c.Hi.FASTA,o.setTag(c.gp.alphabet,c.YI.DNA),o.setTag(c.gp.aligned,"SEQ"),n.filter.init(e=>e>2),n.filter.fireChanged();const s=await n.plot.fromType("WebLogo",{shrinkEmptyTail:!0});await(0,t.PE)(s.onLayoutCalculated,()=>{},()=>{i.dockManager.dock(s.root,e.DOCK_TYPE.DOWN)},500);const r=s.positions,a=[new ee.Ue(0,"1",{[te]:new ee.Tc(3)}),new ee.Ue(1,"2",{T:new ee.Tc(3)}),new ee.Ue(2,"3",{[te]:new ee.Tc(3)}),new ee.Ue(3,"4",{[te]:new ee.Tc(3)}),new ee.Ue(4,"5",{C:new ee.Tc(3)}),new ee.Ue(5,"6",{[te]:new ee.Tc(2),C:new ee.Tc(1)}),new ee.Ue(6,"7",{G:new ee.Tc(3)}),new ee.Ue(7,"8",{T:new ee.Tc(3)}),new ee.Ue(8,"9",{[te]:new ee.Tc(3)})];(0,t.E3)(r.length,a.length);for(let e=0;e<r.length;e++){(0,t.E3)(r[e].name,a[e].name);for(const n of r[e].getMonomers())(0,t.E3)(r[e].getFreq(n).rowCount,a[e].getFreq(n).rowCount)}await s.awaitRendered()}),(0,t.t6)("positions with skipEmptyPositions option",async()=>{const n=e.DataFrame.fromCsv(i),o=l.shell.addTableView(n),s=n.getCol("seq");s.semType=e.SEMTYPE.MACROMOLECULE,s.meta.units=c.Hi.FASTA,s.setTag(c.gp.alphabet,c.YI.DNA),s.setTag(c.gp.aligned,"SEQ.MSA");const r=await n.plot.fromType("WebLogo",{skipEmptyPositions:!0});await(0,t.PE)(r.onLayoutCalculated,()=>{},()=>{o.dockManager.dock(r.root,e.DOCK_TYPE.DOWN)},500);const a=r.positions,u=[new ee.Ue(0,"1",{A:new ee.Tc(2),[te]:new ee.Tc(3)}),new ee.Ue(1,"2",{T:new ee.Tc(5)}),new ee.Ue(2,"3",{C:new ee.Tc(5)}),new ee.Ue(4,"5",{G:new ee.Tc(5)}),new ee.Ue(5,"6",{[te]:new ee.Tc(3),C:new ee.Tc(2)}),new ee.Ue(6,"7",{T:new ee.Tc(5)}),new ee.Ue(7,"8",{T:new ee.Tc(5)}),new ee.Ue(8,"9",{G:new ee.Tc(5)}),new ee.Ue(9,"10",{C:new ee.Tc(5)})];(0,t.E3)(a.length,u.length);for(let e=0;e<a.length;e++)ne(a[e],u[e]);await r.awaitRendered()}),(0,t.t6)("count sequences for monomer at position",async()=>{const o=function(t,n,i){const o=e.DataFrame.fromCsv(t),s=o.getCol("seq");return s.semType=e.SEMTYPE.MACROMOLECULE,s.meta.units=n,s.setTag(c.gp.alphabet,i),s.setTag(c.gp.aligned,"SEQ.MSA"),o}(i,c.Hi.FASTA,c.YI.DNA),s=o.getCol("seq"),r=l.shell.addTableView(o),a=await o.plot.fromType("WebLogo",{startPositionName:"3",endPositionName:"7",skipEmptyPositions:!0});await(0,t.PE)(a.onLayoutCalculated,()=>{},()=>{r.dockManager.dock(a.root,e.DOCK_TYPE.DOWN)},500);const u=a.positions,h=[new ee.Ue(2,"3",{C:new ee.Tc(5)}),new ee.Ue(4,"5",{G:new ee.Tc(5)}),new ee.Ue(5,"6",{[te]:new ee.Tc(3),C:new ee.Tc(2)}),new ee.Ue(6,"7",{T:new ee.Tc(5)})];(0,t.E3)(u.length,h.length);for(let e=0;e<u.length;e++)ne(u[e],h[e]);const d=u[1],m=n.getSeqHandler(s),p=(0,ee.eN)(o,m,o.filter,"G",d);(0,t.E3)(p,5),await a.awaitRendered()}),(0,t.t6)("empty",async()=>{const n=e.DataFrame.fromColumns([(()=>{const t=e.Column.fromStrings("seq",[]);return t.semType=e.SEMTYPE.MACROMOLECULE,t.meta.units=c.Hi.FASTA,t.setTag(c.gp.alphabet,c.YI.DNA),t})()]),i=l.shell.addTableView(n),o=await n.plot.fromType("WebLogo");await(0,t.PE)(o.onLayoutCalculated,()=>{},()=>{i.dockManager.dock(o.root,e.DOCK_TYPE.DOWN)},500),o.positions,await o.awaitRendered()})}),(0,t.L1)("WebLogo.project",()=>{(0,t.t6)("fasta",async()=>{const n="Tests.Bio.WebLogo-project.fasta",i=await Ge.files.readCsv("tests/filter_FASTA.csv"),o=i.name,s=i.getCol("fasta");await l.data.detectSemanticTypes(i);const r=l.shell.addTableView(i),a=await i.plot.fromType("WebLogo",{sequenceColumnName:s.name});r.dockManager.dock(a),await a.awaitRendered(),await O(r.grid),await async function(t,n,i,o){const s=e.Project.create(),r=i.saveLayout();s.name=t,s.addChild(n),s.addChild(r),await l.dapi.layouts.save(i.saveLayout()),await l.dapi.tables.uploadDataFrame(o),await l.dapi.tables.save(n),await l.dapi.projects.save(s)}(n,i.getTableInfo(),r,i),l.shell.closeAll(),await(0,t.cb)(500),await l.dapi.projects.open(n);const c=l.shell.getTableView(o),u=L()(c.viewers).toArray();(0,t.E3)(u.length,2),(0,t.E3)(u.filter(e=>"Grid"===e.type).length,1);const h=u.find(e=>"WebLogo"===e.type);(0,t.E3)(!!h,!0),await O(r.grid),await h.awaitRendered()},{skipReason:"depends on 1.18"})}),(0,t.L1)("WebLogo.layout",()=>{(0,t.t6)("fasta",async()=>{const e=await Ge.files.readCsv("tests/filter_FASTA.csv"),n=e.getCol("fasta");await l.data.detectSemanticTypes(e);const i=l.shell.addTableView(e),o=await e.plot.fromType("WebLogo",{sequenceColumnName:n.name});i.dockManager.dock(o),await(0,t.cb)(2*ee.VN.render),await o.awaitRendered(),await O(i.grid);const s=i.saveLayout();s.toJson(),i.loadLayout(s),await(0,t.cb)(2*ee.VN.render),await o.awaitRendered(),await O(i.grid);const r=L()(i.viewers).toArray();(0,t.E3)(r.length,2),(0,t.E3)(r.filter(e=>"Grid"===e.type).length,1),(0,t.E3)(r.filter(e=>"WebLogo"===e.type).length,1)})});var ie=o(966);function oe(e,t){let n=null;for(const i of e.viewers)i.type===t&&(n=i);return n}(0,t.L1)("checkInputColumn",()=>{let n;(0,t.gM)(async()=>{n=await(0,u.Q)()});const i="seq\nseq1,\nseq2,\nseq3,\nseq4";(0,t.t6)("testMsaPos",async()=>{const o=e.DataFrame.fromCsv(i).getCol("seq");o.semType=e.SEMTYPE.MACROMOLECULE,o.meta.units=c.Hi.FASTA,o.setTag(c.gp.alphabet,c.YI.DNA),o.setTag(c.gp.aligned,"SEQ");const[s,r]=(0,ie.l)(o,"Test",n,[c.Hi.FASTA],[c.YI.DNA,c.YI.RNA,c.YI.PT]);(0,t.E3)(s,!0)}),(0,t.t6)("testMsaNegHelm",async()=>{const o=e.DataFrame.fromCsv(i).getCol("seq");o.semType=e.SEMTYPE.MACROMOLECULE,o.meta.units=c.Hi.HELM,o.setTag(c.gp.alphabetIsMultichar,"true");const[s,r]=(0,ie.l)(o,"Test",n,[c.Hi.FASTA],[c.YI.DNA,c.YI.RNA,c.YI.PT]);(0,t.E3)(s,!1)}),(0,t.t6)("testMsaNegUN",async()=>{const o=e.DataFrame.fromCsv(i).getCol("seq");o.semType=e.SEMTYPE.MACROMOLECULE,o.meta.units=c.Hi.FASTA,o.setTag(c.gp.alphabet,"UN"),o.setTag(c.gp.alphabetSize,"11"),o.setTag(c.gp.alphabetIsMultichar,"true"),o.setTag(c.gp.aligned,"SEQ");const[s,r]=(0,ie.l)(o,"Test",n,[c.Hi.FASTA],[c.YI.DNA,c.YI.RNA,c.YI.PT]);(0,t.E3)(s,!1)}),(0,t.t6)("testGetActionFunctionMeta",async()=>{e.Func.find({package:"Bio",name:"multipleSequenceAlignmentDialog"})[0].inputs.find(e=>"sequence"==e.name)})}),(0,t.L1)("similarity/diversity",async()=>{(0,t.t6)("similaritySearchViewer",async()=>{await async function(){const n=await Ge.files.readAsText("tests/sample_MSA_data.csv"),i=e.DataFrame.fromCsv(n);await l.data.detectSemanticTypes(i);const o=l.shell.addTableView(i),s=o.dataFrame.getCol("MSA");(0,t.E3)(s.semType,e.SEMTYPE.MACROMOLECULE);const r=await o.dataFrame.plot.fromType("Sequence Similarity Search");let a=!1;if(r.computeCompleted.subscribe(e=>{e&&(a=!0)}),o.dockManager.dock(r,e.DOCK_TYPE.RIGHT,null,"Similarity"),await r.renderPromise,await(0,t.bk)(()=>void 0!==oe(o,"Sequence Similarity Search"),"Sequence Similarity Search viewer has not been created",100),!r.initialized)throw new Error("The viewer is not initialized.");if(!r.targetColumn)throw new Error("The viewer has not molecule column (onTableAttached).");if(!r.beforeRender())throw new Error("The viewer is not able to render.");if(!r.computeRequested)throw new Error("The viewer has not compute requested even.");if(!a)throw new Error("The viewer has not compute completed.");const c=r;await(0,t.bk)(()=>0!==c.root.getElementsByClassName("d4-grid").length,"Sequence Similarity Search viewer grid has not been created",100);(0,t.E3)(c.fingerprint,"Morgan"),(0,t.E3)(c.distanceMetric,"Hamming"),(0,t.E3)(c.scores.get(0),e.FLOAT_NULL),(0,t.E3)(c.idxs.get(0),0),(0,t.E3)(c.molCol.get(0),"D-Tyr_Et/Tyr_ab-dehydroMe/dV/E/N/D-Orn/D-aThr//Phe_4Me"),(0,t.E3)(c.scores.get(1).toFixed(2),"0.10"),(0,t.E3)(c.idxs.get(1),7),(0,t.E3)(c.molCol.get(1),"/D-Tyr_Et/meQ/dV/E/N/dV///Phe_4Me"),o.dataFrame.currentRowIdx=1,await(0,t.bk)(()=>1===c.targetMoleculeIdx,"Target molecule has not been changed",5e3),await(0,t.bk)(()=>"meI/hHis/Aca/Cys_SEt/T/dK/Thr_PO3H2/Aca/Tyr_PO3H2/D-Chg/dV/Phe_ab-dehydro/N/D-Orn/D-aThr//Phe_4Me"===c.molCol.get(0),"Incorrect first similar molecule",5e3)}()}),(0,t.t6)("diversitySearchViewer",async()=>{await async function(){const n=await Ge.files.readAsText("tests/sample_MSA_data.csv"),i=e.DataFrame.fromCsv(n),o=l.shell.addTableView(i);await l.data.detectSemanticTypes(i);const s=o.dataFrame.getCol("MSA");(0,t.E3)(s.semType,e.SEMTYPE.MACROMOLECULE);const r=await o.dataFrame.plot.fromType("Sequence Diversity Search");let a=!1;if(r.computeCompleted.subscribe(e=>{e&&(a=!0)}),o.dockManager.dock(r,e.DOCK_TYPE.DOWN,null,"Diversity"),await r.renderPromise,await(0,t.bk)(()=>void 0!==oe(o,"Sequence Diversity Search"),"Sequence Diversity Search viewer has not been created",100),!r.initialized)throw new Error("The viewer is not initialized.");if(!r.targetColumn)throw new Error("The viewer has not molecule column (onTableAttached).");if(!r.beforeRender())throw new Error("The viewer is not able to render.");if(!r.computeRequested)throw new Error("The viewer has not compute requested even.");if(!a)throw new Error("The viewer has not compute completed.");const c=r;await(0,t.bk)(()=>0!==c.root.getElementsByClassName("d4-grid").length,"Sequence Diversity Search viewer grid has not been created",100),(0,t.E3)(c.fingerprint,"Morgan"),(0,t.E3)(c.distanceMetric,"Hamming"),(0,t.E3)(c.initialized,!0),(0,t.E3)(c.renderMolIds.length>0,!0)}()})});var se=o(1687),re=o(4574);(0,t.L1)("bio-substructure-filters",async()=>{let n,i,o;async function s(e,t){if(!t.columns.names().includes(e))throw new Error(`The column '${e}' not found. Available in data frame are ${JSON.stringify(t.columns.names())}`);const i=new se._i(n,Ge.logger);return i.attach(t),i.applyState({columnName:e}),i.column=t.col(e),i.columnName=e,i}(0,t.gM)(async()=>{n=await(0,u.Q)(),i=await(0,_.pj)(),o=await(0,D.u)(),await i.loadMonomerLibForTests()}),(0,t.Pl)(async()=>{await(0,D.E)(o),await i.loadMonomerLib(!0)}),(0,t.t6)("fasta",async()=>{const e=await $("tests/filter_FASTA.csv");await l.data.detectSemanticTypes(e);const i=new se._i(n,Ge.logger);i.attach(e),await i.awaitRendered();try{(0,t.E3)(!!i.bioFilter,!0),(0,t.E3)(i.bioFilter.type,"FastaBioFilter");const n=i.bioFilter;await(0,t.PE)(e.onRowsFiltered,()=>{},()=>{n.props=new re.n("MD",void 0,Ge.logger)},5e3,"testEvent onRowsFiltered"),(0,t.E3)(i.dataFrame.filter.trueCount,3),(0,t.E3)(i.dataFrame?.filter.toBinaryString(),"10010000100000")}finally{i.detach()}await i.awaitRendered()}),(0,t.t6)("separator",async()=>{const e=await $("tests/filter_MSA.csv"),i=new se._i(n,Ge.logger);await l.data.detectSemanticTypes(e),i.attach(e),await i.awaitRendered();try{(0,t.E3)(!!i.bioFilter,!0),(0,t.E3)(i.bioFilter.type,"SeparatorBioFilter");const n=i.bioFilter;await(0,t.PE)(e.onRowsFiltered,()=>{},()=>{n.props=new se.AR("meI",void 0,Ge.logger)},5e3,"testEvent onRowsFiltered"),(0,t.E3)(i.dataFrame.filter.trueCount,7),(0,t.E3)(i.dataFrame.filter.get(2),!1),await(0,t.PE)(e.onRowsFiltered,()=>{},()=>{n.props=new se.AR("/meI",void 0,Ge.logger)},5e3,"testEvent onRowsFiltered"),(0,t.E3)(i.dataFrame.filter.trueCount,0),await(0,t.PE)(e.onRowsFiltered,()=>{},()=>{n.props=new se.AR("meI-hHis","-",Ge.logger)},5e3,"testEvent onRowsFiltered"),(0,t.E3)(i.dataFrame.filter.trueCount,7),(0,t.E3)(i.dataFrame.filter.get(2),!1)}finally{i.detach()}await i.awaitRendered()}),(0,t.t6)("helm-dialog",async()=>{if(e.Func.find({package:"Helm",name:"getHelmHelper"}).length){const e="Bio tests: substructureFilters/helm-dialog",i=await $("tests/filter_HELM.csv"),o=l.shell.addTableView(i);await l.data.detectSemanticTypes(i),await i.meta.detectSemanticTypes(),Ge.logger.debug(`${e}, filter attaching.`);const s=new se._i(n,Ge.logger);s.attach(i);const r=B.dialog("Test filters").add(s.root).show();await s.awaitRendered();try{const n=s.bioFilter;(0,t.E3)(null!==s.bioFilter,!0,"bioFilter is not created"),Ge.logger.debug(`${e}, filter 1 change awaiting...`),await(0,t.PE)(i.onRowsFiltered,()=>{},()=>{n.props=new re.n("PEPTIDE1{A.C}$$$$V2.0",void 0,Ge.logger)},2e4),Ge.logger.debug(`${e}, filter 1 changed.`),(0,t.E3)(s.dataFrame.filter.trueCount,1),(0,t.E3)(s.dataFrame.filter.toBinaryString(),"0001"),Ge.logger.debug(`${e}, filter 2 change awaiting...`),await(0,t.PE)(i.onRowsFiltered,()=>{},()=>{n.props=new re.n("PEPTIDE1{C}$$$$V2.0",void 0,Ge.logger)},2e4),setTimeout(()=>o.grid.invalidate(),500),await O(o.grid),await(0,t.cb)(1e3),Ge.logger.debug(`${e}, filter 2 changed.`),(0,t.E3)(s.dataFrame.filter.trueCount,2),(0,t.E3)(s.dataFrame.filter.toBinaryString(),"1001")}finally{r.close()}await s.awaitRendered(),await(0,t.cb)(3e3)}},{}),(0,t.t6)("helm-view",async()=>{if(e.Func.find({package:"Helm",name:"getHelmHelper"}).length){const e=await $("tests/filter_HELM.csv");e.getCol("HELM string"),await l.data.detectSemanticTypes(e);const t=l.shell.addTableView(e);t.getFiltersGroup(),await O(t.grid)}}),(0,t.t6)("sync-fasta",async()=>{const e=await Ge.files.readCsv("tests/filter_FASTA.csv");await l.data.detectSemanticTypes(e);const n=await s("fasta",e),i=await s("fasta",e);await Promise.all([n.awaitRendered(),i.awaitRendered()]);try{(0,t.E3)(!!n.bioFilter,!0),(0,t.E3)(!!i.bioFilter,!0),(0,t.E3)(n.bioFilter.type,"FastaBioFilter"),(0,t.E3)(i.bioFilter.type,"FastaBioFilter");const o=n.bioFilter,s=i.bioFilter;await(0,t.PE)(e.onRowsFiltered,()=>{},()=>{o.props=new re.n("MD",void 0,Ge.logger)},1e4,"await onRowsFiltered"),(0,t.E3)(e.filter.trueCount,3),await n.awaitRendered(),(0,t.E3)(s.props.substructure,"MD")}finally{n.detach(),i.detach()}await Promise.all([n.awaitRendered(),i.awaitRendered()])}),(0,t.t6)("sync-msa",async()=>{const e=await Ge.files.readCsv("tests/filter_MSA.csv");await l.data.detectSemanticTypes(e);const n="hHis-Aca",i=await s("MSA",e),o=await s("MSA",e);await Promise.all([i.awaitRendered(),o.awaitRendered()]);try{(0,t.E3)(!!i.bioFilter,!0),(0,t.E3)(!!o.bioFilter,!0),(0,t.E3)(i.bioFilter.type,"SeparatorBioFilter"),(0,t.E3)(o.bioFilter.type,"SeparatorBioFilter");const s=i.bioFilter,r=o.bioFilter;await(0,t.PE)(e.onRowsFiltered,()=>{},()=>{s.props=new se.AR(n,"-",Ge.logger)},1e4,"await onRowsFiltered"),(0,t.E3)(e.filter.trueCount,8),(0,t.E3)(r.props.substructure,n),(0,t.E3)(r.props.separator,"-")}finally{i.detach(),o.detach()}await Promise.all([i.awaitRendered(),o.awaitRendered()])}),(0,t.t6)("sync-helm",async()=>{if(e.Func.find({package:"Helm",name:"getHelmHelper"}).length){const e=await Ge.files.readCsv("tests/filter_HELM.csv");await l.data.detectSemanticTypes(e);const n=l.shell.addTableView(e),i="PEPTIDE1{A.C}$$$$V2.0",o=1,r=await s("HELM string",e),a=await s("HELM string",e),c=B.dialog("Test filters").add(r.root).add(a.root).show();await Promise.all([r.awaitRendered(),a.awaitRendered()]);try{(0,t.E3)(!!r.bioFilter,!0),(0,t.E3)(!!a.bioFilter,!0),(0,t.E3)(r.bioFilter.type,"HelmBioFilter"),(0,t.E3)(a.bioFilter.type,"HelmBioFilter");const s=r.bioFilter,l=a.bioFilter;await(0,t.PE)(e.onRowsFiltered,()=>{},()=>{s.props=new re.n(i,void 0,Ge.logger)},6e4,"await onRowsFiltered"),await O(n.grid),Ge.logger.debug("Bio tests: substructureFilters/sync-helm, before changed event"),await(0,t.cb)(2*r.debounceTime),Ge.logger.debug("Bio tests: substructureFilters/sync-helm, after changed event"),(0,t.E3)(e.filter.trueCount,o),await r.awaitRendered(),(0,t.E3)(l.props.substructure,i)}finally{r.detach(),a.detach(),c.close()}await Promise.all([r.awaitRendered(),a.awaitRendered()]),await O(n.grid),await(0,t.cb)(3e3)}}),(0,t.t6)("two-columns-fasta",async()=>{const n=e.DataFrame.fromCsv("id,seq1,seq2,trueSeq1,trueSeq2\n0,CGGCTACGGC,ATTGCATTCG,0,1,\n1,CGGCTGCCGC,ATAGCATTCG,1,1,\n2,CGGCTGCGCC,AATGCATACG,1,0,\n3,CGGCTGCATT,TTTGCATTCG,1,1,\n4,CGGCTGCATT,AAAGCATACG,1,0,\n");await l.data.detectSemanticTypes(n);const i=l.shell.addTableView(n),o="seq1",s="CGGCTG",r=n.getCol("trueSeq1").toList(),a="seq2",c="GCATT",u=n.getCol("trueSeq2").toList(),h=[{type:"Bio:bioSubstructureFilter",columnName:o},{type:"Bio:bioSubstructureFilter",columnName:a}],d=await n.plot.fromType(e.VIEWER.FILTERS,{filters:h});i.dockManager.dock(d,e.DOCK_TYPE.LEFT),await(0,t.cb)(100),await O(i.grid);const m=d.filters[0],p=d.filters[1];(0,t.E3)(m.column.name,o),(0,t.E3)(p.column.name,a);const g=m.bioFilter,f=p.bioFilter;await(0,t.PE)(n.onRowsFiltered,()=>{},()=>{g.props=new re.n(s,void 0,Ge.logger)},1e3),await(0,t.PE)(n.onRowsFiltered,()=>{},()=>{f.props=new re.n("",void 0,Ge.logger)},1e3,"testEvent onRowsFiltered on seq1"),(0,t.E3)(n.filter.trueCount,r.filter(e=>1===e).length),(0,t.E3)(n.filter.toBinaryString(),r.map(e=>e.toString()).join("")),await(0,t.PE)(n.onRowsFiltered,()=>{},()=>{g.props=new re.n("",void 0,Ge.logger)},1e3),await(0,t.PE)(n.onRowsFiltered,()=>{},()=>{f.props=new re.n(c,void 0,Ge.logger)},1e3,"testEvent onRowsFiltered on seq2"),(0,t.E3)(n.filter.trueCount,u.filter(e=>1===e).length),(0,t.E3)(n.filter.toBinaryString(),u.map(e=>e.toString()).join("")),await(0,t.PE)(n.onRowsFiltered,()=>{},()=>{g.props=new re.n("",void 0,Ge.logger)},1e3),await(0,t.PE)(n.onRowsFiltered,()=>{},()=>{f.props=new re.n("",void 0,Ge.logger)},1e3,"testEvent onRowsFiltered on neither"),(0,t.E3)(n.filter.trueCount,n.rowCount),await(0,t.PE)(n.onRowsFiltered,()=>{},()=>{g.props=new re.n(s,void 0,Ge.logger)},5e3),await(0,t.PE)(n.onRowsFiltered,()=>{},()=>{f.props=new re.n(c,void 0,Ge.logger)},5e3,"testEvent onRowsFiltered on both");const y=L().count(0).take(n.rowCount).map(e=>r[e]*u[e]).toArray();(0,t.E3)(n.filter.trueCount,y.filter(e=>1===e).length),(0,t.E3)(n.filter.toBinaryString(),y.map(e=>e.toString()).join("")),await Promise.all([m.awaitRendered(),p.awaitRendered(),O(i.grid)])},{skipReason:"Inconsistent behavior of test"}),(0,t.t6)("reset-fasta",async()=>{const n=await $("tests/filter_FASTA.csv"),i=l.shell.addTableView(n);await l.data.detectSemanticTypes(n),await n.meta.detectSemanticTypes();const o="MD",s=await n.plot.fromType(e.VIEWER.FILTERS,{filters:[{type:"Bio:bioSubstructureFilter",columnName:"fasta"}]});i.dockManager.dock(s,e.DOCK_TYPE.LEFT),await(0,t.cb)(100),await O(i.grid);const r=s.filters[0];await(0,t.bk)(()=>null!==r.bioFilter,"FastaBioFilter hasn't been created",1e3);const a=r.bioFilter;await(0,t.PE)(n.onRowsFiltered,()=>{},()=>{a.props=new re.n(o,void 0,Ge.logger)},1e3,"testEvent onRowsFiltered"),(0,t.E3)(n.filter.trueCount,3),(0,t.E3)(a.props.substructure,o),(0,t.E3)(a.substructureInput.value,o),U()(s.root).find('i[name="icon-arrow-rotate-left"]')[0].click(),await(0,t.cb)(100),await O(i.grid),(0,t.E3)(a.props.substructure,""),(0,t.E3)(a.substructureInput.value,"")}),(0,t.t6)("reopen",async()=>{const n=await Ge.files.readCsv("tests/filter_FASTA.csv"),i=l.shell.addTableView(n);await l.data.detectSemanticTypes(n),await n.meta.detectSemanticTypes();const o=[{type:"Bio:bioSubstructureFilter",columnName:"fasta"}],s=await n.plot.fromType(e.VIEWER.FILTERS,{filters:o});i.dockManager.dock(s,e.DOCK_TYPE.LEFT),await(0,t.cb)(100),await O(i.grid),s.close(),await O(i.grid);const r=await n.plot.fromType(e.VIEWER.FILTERS,{filters:o});i.dockManager.dock(r,e.DOCK_TYPE.LEFT),await(0,t.cb)(100),await O(i.grid)},{})});var ae=o(8152);class le{errorList=[];warningList=[];infoList=[];debugList=[];error(e,t,n){this.errorList.push({message:e,params:t,stackTrace:n})}warning(e,t){this.warningList.push({message:e,params:t})}info(e,t){this.infoList.push({message:e,params:t})}debug(e,t){this.debugList.push({message:e,params:t})}}var ce=o(9192);(0,t.L1)("PepSeA",()=>{(0,t.t6)("Basic alignment",async()=>{const n=e.DataFrame.fromCsv('HELM,MSA\n"PEPTIDE1{F.L.R.G.W.[MeF].Y.S.N.N.C}$$$$","F.L.R.G.W.MeF.Y..S.N.N.C"\n"PEPTIDE1{F.L.R.G.Y.[MeF].Y.W.N.C}$$$$","F.L.R.G.Y.MeF.Y.W...N.C"\n"PEPTIDE1{F.G.Y.[MeF].Y.W.S.D.N.C}$$$$","F...G.Y.MeF.Y.W.S.D.N.C"\n"PEPTIDE1{F.L.R.G.Y.[MeF].Y.W.S.N.D.C}$$$$","F.L.R.G.Y.MeF.Y.W.S.N.D.C"\n"PEPTIDE1{F.V.R.G.Y.[MeF].Y.W.S.N.C}$$$$","F.V.R.G.Y.MeF.Y.W.S..N.C"\n'),i=await(0,ae.GD)(n,n.getCol("HELM"),"msa(HELM)"),o=n.getCol("MSA");for(let e=0;e<i.length;++e)(0,t.E3)(i.get(e)==o.get(e),!0)},{timeout:6e4,skipReason:"Fails in docker"}),(0,t.t6)("stderr",async()=>{const n=new le,i=e.DataFrame.fromCsv('HELM,MSA\n"PEPTIDE1{F.L.Mis.G.W.[MeF].Y.S.N.N.C}$$$$","F.L.Mis.G.W.MeF.Y..S.N.N.C"\n"PEPTIDE1{F.L.Mis.G.Y.[MeF].Y.W.N.C}$$$$","F.L.Mis.G.Y.MeF.Y...W.N.C"\n"PEPTIDE1{F.G.Y.[MeF].Y.W.S.D.N.C}$$$$","F...G.Y.MeF.Y.W.S.D.N.C"\n'),o=await(0,ae.GD)(i,i.getCol("HELM"),"msa(HELM)",void 0,void 0,void 0,void 0,n),s=i.getCol("MSA");(0,t.J6)(o.toList(),s.toList()),(0,t.E3)(n.warningList[0].message,"Mis not found in Monomer Map\nMeF not found in Monomer Map\n")},{timeout:6e4,skipReason:"Fails in docker"}),(0,t.t6)("error",async()=>{const n=new le;try{const t=e.DataFrame.fromCsv('HELM\n"PEPTIDE1{[NH2].*.A.Q.T.T.Y.K.N.Y.R.R.N.L.L.*.[COOH]}$$$$"\n"PEPTIDE1{[NH2].M.A.N.T.T.Y.K.N.Y.R.N.N.L.L.*.[COOH]}$$$$"\n"PEPTIDE1{[NH2].*.A.N.T.T.Y.K.C.Y.R.R.N.L.L.*.[COOH]}$$$$"\n"PEPTIDE1{[NH2].*.A.N.T.T.Y.K.F.Y.R.R.N.L.L.*.[COOH]}$$$$"\n');await(0,ae.GD)(t,t.getCol("HELM"),"msa(HELM)",void 0,void 0,void 0,void 0,n)}catch(e){const[t,i]=(0,ce.AP)(e);n.error(t,void 0,i)}(0,t.E3)(n.errorList[0].message,"PepSeA error: The pair (*,M) couldn't be found in the substitution matrix")},{skipReason:"Fails in docker"})});const ue="seq\nACGTCACGTC\nCAGTGTCAGTGT\nTTCAACTTCAAC",he="seq\nAC-GT-CTAC-GT-CT\nCAC-T-GTCAC-T-GT\nACCGTACTACCGTACT",de="seq\nabc-dfgg-abc1-cfr3-rty-wert-abc-dfgg-abc1-cfr3-rty-wert\nrut12-her2-rty-wert-abc-abc1-dfgg-rut12-her2-rty-wert-abc-abc1-dfgg\nrut12-rty-her2-abc-cfr3-wert-rut12-rut12-rty-her2-abc-cfr3-wert-rut12";var me;(0,t.L1)("SeqHandler",()=>{let n;async function i(t){const i=e.DataFrame.fromCsv(t);await l.data.detectSemanticTypes(i);const o=n.getSeqHandler(i.getCol("seq"));return[i,o]}(0,t.gM)(async()=>{n=await(0,u.Q)()}),(0,t.t6)("Seq-Fasta",async()=>{const[e,n]=await i(ue);(0,t.E3)(n.notation,c.Hi.FASTA),(0,t.E3)(n.isMsa(),!1)}),(0,t.t6)("Seq-Fasta-MSA",async()=>{const[e,n]=await i(he);(0,t.E3)(n.notation,c.Hi.FASTA),(0,t.E3)(n.isMsa(),!0)}),(0,t.t6)("Seq-Fasta-units",async()=>{const[e,n]=await i(ue);(0,t.E3)(n.notation,c.Hi.FASTA),(0,t.E3)(n.isMsa(),!1)}),(0,t.t6)("Seq-Fasta-MSA-units",async()=>{const[e,n]=await i(he);(0,t.E3)(n.notation,c.Hi.FASTA),(0,t.E3)(n.isMsa(),!0)}),(0,t.t6)("Seq-Helm",async()=>{const[e,n]=await i("seq\nPEPTIDE1{meI.hHis.Aca.N.T.dE.Thr_PO3H2.Aca.D-Tyr_Et.Tyr_ab-dehydroMe.dV.E.N.D-Orn.D-aThr.Phe_4Me}$$$$\nPEPTIDE1{meI.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.Tyr_PO3H2.D-Chg.dV.Phe_ab-dehydro.N.D-Orn.D-aThr.Phe_4Me}$$$$\nPEPTIDE1{Lys_Boc.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.Tyr_PO3H2.D-Chg.dV.Thr_PO3H2.N.D-Orn.D-aThr.Phe_4Me}$$$$\nPEPTIDE1{meI.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.Tyr_PO3H2.D-Chg.dV.Thr_PO3H2.N.D-Orn.D-aThr.Phe_4Me}$$$$");(0,t.E3)(n.notation,c.Hi.HELM),(0,t.E3)(n.isHelm(),!0)}),(0,t.t6)("Seq-UN",async()=>{const[e,n]=await i(de);(0,t.E3)(n.notation,c.Hi.SEPARATOR),(0,t.E3)(n.separator,"-"),(0,t.E3)(n.alphabet,c.YI.UN)}),(0,t.t6)("Seq-UN-auto",async()=>{const[e,n]=await i(de);(0,t.E3)(n.notation,c.Hi.SEPARATOR),(0,t.E3)(n.separator,"-"),(0,t.E3)(n.alphabet,c.YI.UN)}),(0,t.t6)("column-version",async()=>{const i=e.DataFrame.fromCsv(ue);await l.data.detectSemanticTypes(i);const o=i.getCol("seq"),s=n.getSeqHandler(o),r=o.version,a=n.getSeqHandler(o),c=o.version;(0,t.E3)(r,c,"Unexpected column version changed"),(0,t.E3)(s,a,"Unexpected SeqHandler object changed"),i.rows.addNew(["TACCCCTTCAAC"]);const u=n.getSeqHandler(o),h=o.version;(0,t.E3)(c<h,!0,"Stalled column version on add row"),(0,t.E3)(a!==u,!0,"Stalled SeqHandler object on add row"),o.set(1,"CAGTGTCCCCGT");const d=n.getSeqHandler(o),m=o.version;(0,t.E3)(h<m,!0,"Stalled column version on change data"),(0,t.E3)(u!==d,!0,"Stalled SeqHandler object on change data"),o.setTag("testTag","testValue");const p=n.getSeqHandler(o),g=o.version;(0,t.E3)(m<g,!0,"Stalled column version on set tag"),(0,t.E3)(d!==p,!0,"Stalled SeqHandler object on set tag")})}),function(e){e.fasta="fasta",e.fastaMsa="fastaMsa",e.separator="separator",e.separatorMsa="separatorMsa",e.helm="helm"}(me||(me={})),(0,t.L1)("SeqHandler: splitted",()=>{let n;(0,t.gM)(async()=>{n=await(0,u.Q)()}),Q.b9[c.Hi.FASTA],Q.b9[c.Hi.HELM];const i=Q.b9[c.Hi.SEPARATOR],o={[me.fasta]:{src:{csv:"seq\nACGTCACGTC\nCAGTGTCAGTGT\nTTCAACTTCAAC"},tgt:{notation:c.Hi.FASTA,splitted:[["A","C","G","T","C","A","C","G","T","C"],["C","A","G","T","G","T","C","A","G","T","G","T"],["T","T","C","A","A","C","T","T","C","A","A","C"]]}},[me.fastaMsa]:{src:{csv:"seq\nAC-GT-CTAC-GT-CT\nCAC-T-GTCAC-T-GT\nACCGTACTACCGTACT"},tgt:{notation:c.Hi.FASTA,splitted:[["A","C","-","G","T","-","C","T","A","C","-","G","T","-","C","T"],["C","A","C","-","T","-","G","T","C","A","C","-","T","-","G","T"],["A","C","C","G","T","A","C","T","A","C","C","G","T","A","C","T"]]}},[me.separator]:{src:{csv:"seq\nabc-dfgg-abc1-cfr3-rty-wert-abc-dfgg-abc1-cfr3-rty-wert\nrut12-her2-rty-wert-abc-abc1-dfgg-rut12-her2-rty-wert-abc\nrut12-rty-her2-abc-cfr3-wert-rut12-rut12-rty-her2-abc-cfr3"},tgt:{notation:c.Hi.SEPARATOR,separator:"-",splitted:[["abc","dfgg","abc1","cfr3","rty","wert","abc","dfgg","abc1","cfr3","rty","wert"],["rut12","her2","rty","wert","abc","abc1","dfgg","rut12","her2","rty","wert","abc"],["rut12","rty","her2","abc","cfr3","wert","rut12","rut12","rty","her2","abc","cfr3"]]}},[me.separatorMsa]:{src:{csv:'seq\nrut0-dfgg-abc1-cfr3-rty-wert-abc-dfgg-abc1-cfr3-rty-wert\nrut1-her2-rty--abc1-dfgg-rut12-her2-rty--abc1-dfgg\nrut2-rty-her2---wert-rut12-rty-her2---wert\n"rut3-rty-her2-""-""-""-""-wert-rut12-rty-her2-""-""-""-""-wert"\n"""-""-rut4-her2-wert-rut12-rty-her2-wert"\n"rut5-rty-her2-wert-rut12-rty-her2-wert-""-"""'},tgt:{notation:c.Hi.SEPARATOR,separator:"-",splitted:[["rut0","dfgg","abc1","cfr3","rty","wert","abc","dfgg","abc1","cfr3","rty","wert"],["rut1","her2","rty",i,"abc1","dfgg","rut12","her2","rty",i,"abc1","dfgg"],["rut2","rty","her2",i,i,"wert","rut12","rty","her2",i,i,"wert"],["rut3","rty","her2",i,i,"wert","rut12","rty","her2",i,i,"wert"],[i,"rut4","her2","wert","rut12","rty","her2","wert"],["rut5","rty","her2","wert","rut12","rty","her2","wert",i]]}},[me.helm]:{src:{csv:"seq\nPEPTIDE1{meI.hHis.Aca.N.T.dE.Thr_PO3H2.Aca.D-Tyr_Et.Thr_PO3H2.Aca.D-Tyr_Et}$$$$\nPEPTIDE1{meI.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.dK.Thr_PO3H2.Aca}$$$$\nPEPTIDE1{Lys_Boc.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.dK.Thr_PO3H2.Aca}$$$$\nPEPTIDE1{meI.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.T.dK.Thr_PO3H2}$$$$,\nPEPTIDE1{meI.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.T.dK}|PEPTIDE2{Thr_PO3H2}$$$$"},tgt:{notation:c.Hi.HELM,splitted:[["meI","hHis","Aca","N","T","dE","Thr_PO3H2","Aca","D-Tyr_Et","Thr_PO3H2","Aca","D-Tyr_Et"],["meI","hHis","Aca","Cys_SEt","T","dK","Thr_PO3H2","Aca","dK","Thr_PO3H2","Aca"],["Lys_Boc","hHis","Aca","Cys_SEt","T","dK","Thr_PO3H2","Aca","dK","Thr_PO3H2","Aca"],["meI","hHis","Aca","Cys_SEt","T","dK","Thr_PO3H2","T","dK","Thr_PO3H2"],["meI","hHis","Aca","Cys_SEt","T","dK","Thr_PO3H2","T","dK","Thr_PO3H2"]]}}};for(const[i,s]of Object.entries(o))(0,t.t6)(`${i}`,async()=>{const i=e.DataFrame.fromCsv(s.src.csv).getCol("seq"),o=await l.functions.call("Bio:detectMacromolecule",{col:i});o&&(i.semType=o),(0,t.E3)(i.semType,e.SEMTYPE.MACROMOLECULE);const r=n.getSeqHandler(i);(0,t.E3)(r.notation,s.tgt.notation),(0,t.E3)(r.separator===s.tgt.separator,!0);const a=L().count(0).take(r.length).map(e=>{const t=r.getSplitted(e);return L().count(0).take(t.length).map(e=>t.getOriginal(e)).toArray()}).toArray();(0,t.J6)(a,s.tgt.splitted)})}),(0,t.L1)("SeqHandler: getRegion",()=>{let n;(0,t.gM)(async()=>{n=await(0,u.Q)()});const i={fastaDna:{srcCsv:"seq\nATTCGT\nACTGCTC\nATTCCGTA",startIdx:2,endIdx:4,tgtCsv:"seq\nTCG\nTGC\nTCC",units:c.Hi.FASTA,alphabet:c.YI.DNA,positionNames:{tag:"a, b, c, d, e, f, g, h",start:"c",end:"e"}},separatorPt:{srcCsv:"seq\nM-D-Y-K-E-T-L\nM-I-E-V-F-L-F-G-I\nM-M-",startIdx:5,endIdx:null,tgtCsv:"seq\nT-L--\nL-F-G-I\n---",units:c.Hi.SEPARATOR,alphabet:c.YI.PT,positionNames:{tag:"1, 1A, 1B, 2, 3, 4, 4A, 4A, 4C",start:"4",end:null}},helm:{srcCsv:"seq\nPEPTIDE1{[meI].[hHis].[Aca].N.T.[dE].[Thr_PO3H2].[Aca].[D-Tyr_Et].[Tyr_ab-dehydroMe].[dV].E.N.[D-Orn]}$$$$\nPEPTIDE1{[meI].[hHis].[Aca].[Cys_SEt].T.[dK].[Thr_PO3H2].[Aca].[Tyr_PO3H2].[D-Chg].[dV].[Phe_ab-dehydro]}$$$$\nPEPTIDE1{[Lys_Boc].[hHis].[Aca].[Cys_SEt].T}$$$$",startIdx:3,endIdx:6,tgtCsv:"seq\nPEPTIDE1{N.T.[dE].[Thr_PO3H2]}$$$$\nPEPTIDE1{[Cys_SEt].T.[dK].[Thr_PO3H2]}$$$$\nPEPTIDE1{[Cys_SEt].T.*.*}$$$$",units:c.Hi.HELM,alphabet:c.YI.UN,positionNames:{tag:null,start:"4",end:"7"}}};for(const[o,s]of Object.entries(i))(0,t.t6)(`${o}-idx`,async()=>{const i=e.DataFrame.fromCsv(s.srcCsv).getCol("seq"),o=await l.functions.call("Bio:detectMacromolecule",{col:i});o&&(i.semType=o);const r=n.getSeqHandler(i).getRegion(s.startIdx,s.endIdx,"regSeq"),a=e.DataFrame.fromCsv(s.tgtCsv).getCol("seq");(0,t.E3)(i.meta.units,s.units),(0,t.E3)(r.meta.units,s.units),(0,t.E3)(i.getTag(c.gp.alphabet),s.alphabet),(0,t.E3)(r.getTag(c.gp.alphabet),s.alphabet),(0,t.J6)(r.toList(),a.toList())}),s.positionNames&&(0,t.t6)(`${o}-positionNames`,async()=>{const n=e.DataFrame.fromCsv(s.srcCsv).getCol("seq");s.positionNames.tag&&n.setTag(c.gp.positionNames,s.positionNames.tag);const i=await l.functions.call("Bio:detectMacromolecule",{col:n});i&&(n.semType=i);const o=await l.functions.call("Bio:getRegion",{sequence:n,start:s.positionNames.start,end:s.positionNames.end}),r=e.DataFrame.fromCsv(s.tgtCsv).getCol("seq");(0,t.E3)(n.meta.units,s.units),(0,t.E3)(o.meta.units,s.units),(0,t.E3)(n.getTag(c.gp.alphabet),s.alphabet),(0,t.E3)(o.getTag(c.gp.alphabet),s.alphabet),(0,t.J6)(o.toList(),r.toList())})}),(0,t.L1)("SeqHandler: getHelm",()=>{let n,i,o;(0,t.gM)(async()=>{n=await(0,u.Q)(),i=await(0,_.pj)(),o=await(0,D.u)(),await i.loadMonomerLibForTests()}),(0,t.Pl)(async()=>{await(0,D.E)(o),await i.loadMonomerLib(!0)});const s={fasta:{src:{seq:"MDYKETMDYKET",notation:c.Hi.FASTA},tgt:{helm:"PEPTIDE1{M.D.Y.K.E.T.M.D.Y.K.E.T}$$$$"}},separator:{src:{seq:"M-D-Y-K-E-T-M-D-Y-K-E-T",notation:c.Hi.SEPARATOR,separator:"-"},tgt:{helm:"PEPTIDE1{M.D.Y.K.E.T.M.D.Y.K.E.T}$$$$"}},helm:{src:{seq:"PEPTIDE1{M.D.Y.K.E.T}$$$$",notation:c.Hi.HELM},tgt:{helm:"PEPTIDE1{M.D.Y.K.E.T}$$$$"}},"helm-cyclic":{src:{seq:"PEPTIDE1{M.D.Y.K.E.T}$PEPTIDE1,PEPTIDE1,6:R2-1:R1$$$V2.0",notation:c.Hi.HELM},tgt:{helm:"PEPTIDE1{M.D.Y.K.E.T}$PEPTIDE1,PEPTIDE1,6:R2-1:R1$$$V2.0"}}};for(const[e,n]of Object.entries(s))(0,t.t6)(e,async()=>{await r(n.src.seq,n.src.notation,n.src.separator,n.tgt.helm)});async function r(i,o,s,r){const a=e.Column.fromStrings("seq",[i]),c=e.DataFrame.fromColumns([a]);await l.data.detectSemanticTypes(c);const u=n.getSeqHandler(a),h=(await u.getValue(0)).helm;(0,t.E3)(h,r)}});var pe=o(2582);(0,t.L1)("helm",()=>{const e={"single-linear":{src:{helm:"PEPTIDE1{R.F.Y.[GGaz].T.[meI]}$$$$"},tgt:{simplePolymers:[6],connections:[],bondedRGroups:[1,2,2,2,2,1]}},"single-cyclized-C-2-2":{src:{helm:"PEPTIDE1{R.F.C.Y.G.H.[GGaz].C.T.[meI]}$PEPTIDE1,PEPTIDE1,3:R3-8:R3$$$"},tgt:{simplePolymers:[10],connections:[[["PEPTIDE1",3,"R3"],["PEPTIDE1",8,"R3"]]],bondedRGroups:[1,2,3,2,2,2,2,3,2,1]}},"single-cyclized-C-1-1":{src:{helm:"PEPTIDE1{F.C.Y.G.H.[GGaz].C.[meI]}$PEPTIDE1,PEPTIDE1,2:R3-7:R3$$$"},tgt:{simplePolymers:[8],connections:[[["PEPTIDE1",2,"R3"],["PEPTIDE1",7,"R3"]]],bondedRGroups:[1,3,2,2,2,1,3,1]}},"single-cyclized-C-0-0":{src:{helm:"PEPTIDE1{C.Y.G.H.[GGaz].C}$PEPTIDE1,PEPTIDE1,1:R3-6:R3$$$"},tgt:{simplePolymers:[6],connections:[[["PEPTIDE1",1,"R3"],["PEPTIDE1",6,"R3"]]],bondedRGroups:[2,2,2,2,2,2]}},"two-separated-5-1":{src:{helm:"PEPTIDE1{R.F.Y.[GGaz].T}|PEPTIDE2{[meI]}$$$$"},tgt:{simplePolymers:[5,1],connections:[],bondedRGroups:[1,2,2,2,1,0]}},"two-separated-1-5":{src:{helm:"PEPTIDE1{[meI]}|PEPTIDE2{R.F.Y.[GGaz].T}$$$$"},tgt:{simplePolymers:[1,5],connections:[],bondedRGroups:[0,1,2,2,2,1]}},"two-separated-4-2":{src:{helm:"PEPTIDE1{R.F.Y.[GGaz]}|PEPTIDE2{T.[meI]}$$$$"},tgt:{simplePolymers:[4,2],connections:[],bondedRGroups:[1,2,2,1,1,1]}},"two-connected-1":{src:{helm:"PEPTIDE1{R.F.Y.[GGaz].T}|PEPTIDE2{[meI]}$PEPTIDE1,PEPTIDE2,5:R2-1:R1$$$"},tgt:{simplePolymers:[5,1],connections:[[["PEPTIDE1",5,"R2"],["PEPTIDE2",1,"R1"]]],bondedRGroups:[1,2,2,2,2,1]}},"two-connected-2":{src:{helm:"PEPTIDE1{R.F.Y.[GGaz]}|PEPTIDE2{T.[meI]}$PEPTIDE1,PEPTIDE2,4:R2-1:R1$$$"},tgt:{simplePolymers:[4,2],connections:[[["PEPTIDE1",4,"R2"],["PEPTIDE2",1,"R1"]]],bondedRGroups:[1,2,2,2,2,1]}},"two-cyclized-1-9":{src:{helm:"PEPTIDE1{[meI]}|PEPTIDE2{R.F.[GGaz].T.G.H.F.Y.P}$PEPTIDE2,PEPTIDE2,3:R3-9:R2|PEPTIDE2,PEPTIDE1,3:R4-1:R1$$$V2.0"},tgt:{simplePolymers:[1,9],connections:[[["PEPTIDE2",3,"R3"],["PEPTIDE2",9,"R2"]],[["PEPTIDE2",3,"R4"],["PEPTIDE1",1,"R1"]]],bondedRGroups:[1,1,2,4,2,2,2,2,2,1]}}};for(const[n,{src:i,tgt:o}]of Object.entries(e))(0,t.t6)(n,async()=>{const e=new pe.f(i.helm),n=e.simplePolymers.map(e=>e.monomers.length),s=n.reduce((e,t)=>e+t,0);(0,t.J6)(n,o.simplePolymers);const r=e.connectionList.getConnectionData().map(e=>[[e[0].polymerId,e[0].bond.monomerIdx+1,`R${e[0].bond.rGroupId}`],[e[1].polymerId,e[1].bond.monomerIdx+1,`R${e[1].bond.rGroupId}`]]);(0,t.J6)(r,o.connections);const a=L().count(0).take(e.bondedRGroupsMap.length).map(t=>e.bondedRGroupsMap[t].length).toArray();(0,t.E3)(s,a.length)})});var ge=o(6077),fe=o(6717);const ye=new e.FileSource("System:AppData/Bio"),be={symbol:"allyl_mon",name:"monomer with Allyl R group",molfile:"\n RDKit 2D\n\n 9 8 0 0 0 0 0 0 0 0999 V2000\n 1.4434 -2.1667 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0\n 1.4434 -0.6667 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n 0.1443 0.0833 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n -1.1547 -0.6667 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n -2.4537 0.0833 0.0000 S 0 0 0 0 0 0 0 0 0 0 0 0\n -3.7528 -0.6667 0.0000 R# 0 0 0 0 0 0 0 0 0 0 0 0\n 0.1443 1.5833 0.0000 N 0 0 0 0 0 0 0 0 0 0 0 0\n 1.4434 2.3333 0.0000 R# 0 0 0 0 0 0 0 0 0 0 0 0\n 2.7424 0.0833 0.0000 R# 0 0 0 0 0 0 0 0 0 0 0 0\n 1 2 2 0\n 2 3 1 0\n 3 4 1 6\n 4 5 1 0\n 5 6 1 0\n 3 7 1 0\n 7 8 1 0\n 2 9 1 0\nM RGP 3 6 3 8 1 9 2\nM END\n",smiles:"O=C([C@H](CS[*:3])N[*:1])[*:2]",polymerType:"PEPTIDE",monomerType:"Backbone",naturalAnalog:"C",id:16,rgroups:[{alternateId:"R1-H",capGroupName:"H",capGroupSmiles:"[H][*:1]",label:"R1"},{alternateId:"R2-OH",capGroupName:"OH",capGroupSmiles:"O[*:2]",label:"R2"},{alternateId:"R3-Allyl",capGroupName:"Allyl",capGroupSmiles:"C=C[*:3]",label:"R3"}],author:"Admin",createDate:"2026-02-18T14:48:41.723Z",meta:{}},we={symbol:"SomeComplex",name:"Some complex monomer with complex R group",molfile:"\n RDKit 2D\n\n 10 9 0 0 0 0 0 0 0 0999 V2000\n -1.4289 -0.3750 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n -2.7280 0.3750 0.0000 S 0 0 0 0 0 0 0 0 0 0 0 0\n -4.0270 -0.3750 0.0000 R# 0 0 0 0 0 0 0 0 0 0 0 0\n -0.1299 0.3750 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n -0.1299 1.8750 0.0000 N 0 0 0 0 0 0 0 0 0 0 0 0\n 1.1691 2.6250 0.0000 R# 0 0 0 0 0 0 0 0 0 0 0 0\n 1.1691 -0.3750 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n 1.1691 -1.8750 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0\n 2.4682 -2.6250 0.0000 R# 0 0 0 0 0 0 0 0 0 0 0 0\n 2.4682 0.3750 0.0000 R# 0 0 0 0 0 0 0 0 0 0 0 0\n 1 2 1 0\n 2 3 1 0\n 4 1 1 6\n 4 5 1 0\n 5 6 1 0\n 4 7 1 0\n 7 8 1 0\n 8 9 1 0\n 7 10 1 0\nM RGP 4 3 3 6 1 9 4 10 2\nM END\n",smiles:"[*:4]OC([C@H](CS[*:3])N[*:1])[*:2]",polymerType:"PEPTIDE",monomerType:"Backbone",naturalAnalog:"C",id:16,rgroups:[{alternateId:"R1-H",capGroupName:"H",capGroupSmiles:"[H][*:1]",label:"R1"},{alternateId:"R2-OH",capGroupName:"OH",capGroupSmiles:"O[*:2]",label:"R2"},{alternateId:"R3-Something",capGroupName:"Something",capGroupSmiles:"C=CC([*:3])=C",label:"R3"},{alternateId:"R4-SomethingElse",capGroupName:"SomethingElse",capGroupSmiles:"ClCCCC=CC([*:4])=CCC",label:"R4"}],author:"Admin",createDate:"2026-02-18T14:48:41.723Z",meta:{}},ve={"peptides-fasta":{inPath:"tests/to-atomic-level-peptides-fasta-input.csv",outPath:"tests/to-atomic-level-peptides-fasta-output.csv"},"dna-fasta":{inPath:"tests/to-atomic-level-dna-fasta-input.csv",outPath:"tests/to-atomic-level-dna-fasta-output.csv"},"msa-separator":{inPath:"tests/to-atomic-level-msa-separator-input.csv",outPath:"tests/to-atomic-level-msa-separator-output.csv"},"msa-fasta":{inPath:"tests/to-atomic-level-msa-fasta-input.csv",outPath:"tests/to-atomic-level-msa-fasta-output.csv"}},Ce="molfile(sequence)";function Ae(e){return e.replaceAll("\r\n","\n").replace(/\n$/,"").split("\n").map(e=>e.trimEnd()).join("\n")}(0,t.L1)("toAtomicLevel",async()=>{const n={},i={};let o,s,r,a,h,d;async function m(e,n){const i=e.getCol("sequence");await l.functions.call("Bio:toAtomicLevel",{table:e,seqCol:i,nonlinear:!1});const o=e.getCol(Ce),s=n.getCol(Ce),r=L()(o.values()).map(e=>Ae(e)).toArray(),a=L()(s.values()).map(e=>Ae(e)).toArray();(0,t.J6)(r,a)}(0,t.gM)(async()=>{h=await(0,fe.j)(),r=await(0,u.Q)(),o=await(0,_.pj)(),s=await(0,D.u)(),await o.loadMonomerLibForTests(),a=o.getMonomerLib();for(const[t,o]of Object.entries(ve))o.inPath,n[t]=e.DataFrame.fromCsv((await ye.readAsText(o.inPath)).replace(/\n$/,"")),n[t].name=o.inPath.split("/").pop(),await l.data.detectSemanticTypes(n[t]),i[t]=e.DataFrame.fromCsv((await ye.readAsText(o.outPath)).replace(/\n$/,""))}),(0,t.Pl)(async()=>{await(0,D.E)(s),await o.loadMonomerLib(!0)});for(const[e,o]of Object.entries(ve))(0,t.t6)(`${e}`,async()=>{await m(n[e],i[e])});!function(e){e.fastaDna="fastaDna",e.fastaRna="fastaRna",e.fastaPt="fastaPt",e.fastaUn="fastaUn",e.separatorDna="separatorDna",e.separatorRna="separatorRna",e.separatorPt="separatorPt",e.separatorUn="separatorUn",e.helm="helm"}(d||(d={}));const p={[d.fastaDna]:"seq\nACGTCACGTC\nCAGTGTCAGTGT\nTTCAACTTCAAC",[d.fastaRna]:"seq\nACGUCACGUC\nCAGUGUCAGUGU\nUUCAACUUCAAC",[d.fastaPt]:"seq\nFWPHEYFWPHEY\nYNRQWYVYNRQWYV\nMKPSEYVMKPSEYV",[d.fastaUn]:"seq\n[meI][hHis][Aca]NT[dE][Thr_PO3H2][Aca]D[meI][hHis][Aca]NT[dE][Thr_PO3H2][Aca]D\n[meI][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca][Tyr_PO3H2][meI][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca][Tyr_PO3H2]\n[Lys_Boc][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca][Tyr_PO3H2][Lys_Boc][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca][Tyr_PO3H2]",[d.separatorDna]:"seq\nA/C/G/T/C/A/C/G/T/C\nC/A/G/T/G/T/C/A/G/T/G/T\nT/T/C/A/A/C/T/T/C/A/A/C",[d.separatorRna]:"seq\nA*C*G*U*C*A*C*G*U*C\nC*A*G*U*G*U*C*A*G*U*G*U\nU*U*C*A*A*C*U*U*C*A*A*C",[d.separatorPt]:"seq\nF-W-P-H-E-Y-F-W-P-H-E-Y\nY-N-R-Q-W-Y-V-Y-N-R-Q-W-Y-V\nM-K-P-S-E-Y-V-M-K-P-S-E-Y-V",[d.separatorUn]:"seq\nmeI-hHis-Aca-N-T-dE-Thr_PO3H2-Aca-D-meI-hHis-Aca-N-T-dE-Thr_PO3H2-Aca-D\nmeI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-meI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2\nLys_Boc-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-Lys_Boc-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2",[d.helm]:"seq\nPEPTIDE1{meI.D-gGlu.Aca.N.T.dE.Thr_PO3H2.Aca.D.Thr_PO3H2.Aca.D}$$$\nPEPTIDE1{meI.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.Tyr_PO3H2.Thr_PO3H2.Aca.Tyr_PO3H2}$$$\nPEPTIDE1{Lys_Boc.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.Tyr_PO3H2.Thr_PO3H2.Aca.Tyr_PO3H2}$$$"};async function g(t){const n=p[t],i=e.DataFrame.fromCsv(n.replace(/\n$/,""));return await l.data.detectSemanticTypes(i),i}async function f(e,n){let i=null;const s=o.getMonomerLib();s._monomers.PEPTIDE[be.symbol]=be,s._monomers.PEPTIDE[we.symbol]=we;try{const i=await r.getHelmToMolfileConverter(s),o=r.helmToAtomicLevelSingle(e,i,!0,!0),a=l.chem.convert(o.molfile,l.chem.Notation.Unknown,l.chem.Notation.Smiles);(0,t.E3)(a,n)}catch(e){i=e}if(delete s._monomers.PEPTIDE[be.symbol],delete s._monomers.PEPTIDE[we.symbol],i)throw i}async function y(e,t="seq",n){const i=e.getCol(t),o=await(0,ge.C4)(e,i,a,r,h);return o.warnings.length>0&&Ge.logger.warning(`_toAtomicLevel() warnings ${o.warnings.join("\n")}`),o.molCol}(0,t.t6)("fastaDna",async()=>{await y(await g(d.fastaDna),"seq")}),(0,t.t6)("fastaRna",async()=>{await y(await g(d.fastaRna),"seq")}),(0,t.t6)("fastaPt",async()=>{await y(await g(d.fastaPt),"seq")}),(0,t.t6)("fastaUn",async()=>{await y(await g(d.fastaUn),"seq")}),(0,t.t6)("separatorDna",async()=>{await y(await g(d.separatorDna),"seq")}),(0,t.t6)("separatorDna",async()=>{await y(await g(d.separatorRna),"seq")}),(0,t.t6)("separatorPt",async()=>{await y(await g(d.separatorPt),"seq")}),(0,t.t6)("separatorUn",async()=>{await y(await g(d.separatorUn),"seq")}),(0,t.t6)("helm",async()=>{await y(await g(d.helm),"seq")}),(0,t.t6)("ptFasta2",async()=>{const n=await Ge.files.readAsText("tests/to-atomic-level-pt-fasta-2.mol"),i=e.DataFrame.fromCsv("seq\nAR"),o=i.getCol("seq");o.semType=e.SEMTYPE.MACROMOLECULE,o.meta.units=c.Hi.FASTA,o.setTag(c.gp.alphabet,c.YI.PT),r.getSeqHandler(o);const s=await y(i,"seq");(0,t.E3)(Ae(s.get(0)),Ae(n))}),(0,t.t6)("SingleHelmMonomerWithAllylGroups",async()=>{const e=`PEPTIDE1{[${be.symbol}]}$$$$V2.0`;await f(e,"C=CSC[C@H](N)C(=O)O")}),(0,t.t6)("SingleHelmMonomerWithComplexRGroups",async()=>{const e=`PEPTIDE1{[${we.symbol}]}$$$$V2.0`;await f(e,"C=CC(=C)SC[C@H](N)C(O)OC(C=CCCCCl)=CCC")}),(0,t.t6)("HelmPolymerWithComplexRGroups",async()=>{const e=`PEPTIDE1{[dI].[Trp_Ome].[Asp_OMe].[D-Cit].[meG].[Phe_4NH2].[Phe_34diCl].[meY].[Pro_4Me3OH].[Met_O].[NMe2Abz].[Tyr_Ph4OH].[3Pal].[xiIle].[Tyr_35diI].[Ala_tBu]}|PEPTIDE2{[${be.symbol}].[${we.symbol}]}$PEPTIDE1,PEPTIDE1,16:R2-1:R1|PEPTIDE1,PEPTIDE2,1:R3-1:R1$$$V2.0`;await f(e,"C=CSC[C@H](NCC[C@@H](C)[C@H]1NC(=O)[C@H](C(C)(C)C)NC(=O)[C@H](Cc2cc(I)c(O)c(I)c2)NC(=O)[C@H](C(C)CC)NC(=O)[C@H](Cc2cccnc2)NC(=O)[C@H](Cc2ccc(Oc3ccc(O)cc3)cc2)NC(=O)c2ccccc2N(C)C(=O)[C@H](CCS(C)=O)NC(=O)[C@@H]2C(O)C(C)CN2C(=O)[C@H](Cc2ccc(O)cc2)N(C)C(=O)[C@H](Cc2ccc(Cl)c(Cl)c2)NC(=O)[C@H](Cc2ccc(N)cc2)NC(=O)CN(C)C(=O)[C@@H](CCCNC(N)=O)NC(=O)[C@H](CC(=O)OC)NC(=O)[C@H](Cc2cn(OC)c3ccccc23)NC1=O)C(=O)N[C@@H](CSC(=C)C=C)C(O)OC(C=CCCCCl)=CCC")})}),(0,t.L1)("toAtomicLevelHelmRna",async()=>{let n,i,o,s,r;async function a(n){const i=`seq\n${n}`,a=e.DataFrame.fromCsv(i);await l.data.detectSemanticTypes(a);const c=a.getCol("seq");(0,t.E3)(c.semType,e.SEMTYPE.MACROMOLECULE);const u=await(0,ge.C4)(a,c,s,o,r);if(!u.molCol)throw new Error(`_toAtomicLevel returned no molCol for HELM '${n}'. Warnings: ${(u.warnings??[]).join(" / ")}`);const h=u.molCol.get(0);if(!h)throw new Error(`_toAtomicLevel produced an empty molfile for HELM '${n}'`);let d;try{d=l.chem.convert(h,l.chem.Notation.Unknown,l.chem.Notation.Smiles)}catch(e){throw new Error(`SMILES conversion threw for HELM '${n}': ${e?.message??e}\n--- MOLFILE START ---\n${h}\n--- MOLFILE END ---`)}if("MALFORMED_INPUT_VALUE"===d||/^MALFORMED/.test(d))throw new Error(`RDKit could not parse molfile produced for HELM '${n}'.\n--- MOLFILE START ---\n${h}\n--- MOLFILE END ---`);return{molfile:h,smiles:d}}function c(e,t){const n=r.get_mol(e);if(!n||!n.is_valid())throw new Error(`RDKit refused the produced molfile:\n${e}`);try{return t(n)}finally{n.delete()}}function h(e,t){const n=r.get_qmol(t);try{const t=e.get_substruct_match(n);return!!t&&"{}"!==t}finally{n.delete()}}function d(e,t){const n=r.get_qmol(t);try{const t=e.get_substruct_matches(n);if(!t||"{}"===t)return 0;const i=JSON.parse(t);return Array.isArray(i)?i.length:i&&"object"==typeof i&&Array.isArray(i.atoms)&&i.atoms.length>0?1:0}finally{n.delete()}}function m(e,t){return d(e,`[#${t}]`)}(0,t.gM)(async()=>{r=await(0,fe.j)(),o=await(0,u.Q)(),n=await(0,_.pj)(),i=await(0,D.u)(),await n.loadMonomerLibForTests(),s=n.getMonomerLib()}),(0,t.Pl)(async()=>{await(0,D.E)(i),await n.loadMonomerLib(!0)});const p="[#6][OX2][PX4](=[OX1])([OX2,SX2,OX1H,SX1H,OX1-,SX1-])[OX2][#6]",g="[#6][OX2][PX4](=[OX1])([SX2,SX1H,SX1-])[OX2][#6]",f="[CX4][PX4]",y="[#6;R]1[#6;R][#6;R][#6;R][O;R]1",b="n1cnc2c1ncnc2N",w="[CH3]c1cn([!#1])c(=O)nc1N",v="[F][CX4;R]",C="[NX3]C(=O)[CH3]",A="[#6;R2]",T="[#7;R]1[#6;R](=[OX1])[#7;R][#6;R][#6;R]1";function E(e){const t=h(e,"[#6]1[#6][#6][#6][#6]1"),n=d(e,"[#6;R2]");return t&&n>=4}function S(e,t){const n=new Set,i=r.get_qmol(t);try{const t=e.get_substruct_matches(i);if(!t||"{}"===t)return n;const o=JSON.parse(t),s=Array.isArray(o)?o:[o];for(const e of s)for(const t of e?.atoms??[])n.add(t)}finally{i.delete()}return n}(0,t.t6)("rna-canonical",async()=>{const{molfile:e}=await a("RNA1{r(A)p.r(C)p.r(G)p}$$$$");c(e,e=>{const n=d(e,y);(0,t.E3)(n>=3,!0,`expected ≥ 3 furanose rings, got ${n}`);const i=d(e,p);(0,t.E3)(i>=2,!0,`expected ≥ 2 inter-nucleotide phosphodiester linkers, got ${i}`);const o=d(e,f);(0,t.E3)(o,0,`expected 0 direct C-P bonds (chain must use C-O-P-O-C), got ${o}`);const s=d(e,b);(0,t.E3)(s>=1,!0,`expected ≥ 1 purine ring, got ${s}`),(0,t.E3)(m(e,15),3,"expected 3 phosphorus atoms")})}),(0,t.t6)("rna-modified-base",async()=>{const{molfile:e}=await a("RNA1{r(C)p.r(A)p}$$$$"),{molfile:n}=await a("RNA1{r([m5C])p.r(A)p}$$$$");c(e,e=>{(0,t.E3)(d(e,w),0,"plain r(C) must not contain 5-methylcytosine")}),c(n,e=>{(0,t.E3)(d(e,w),1,"r([m5C]) must contain exactly one 5-methylcytosine ring")})}),(0,t.t6)("rna-modified-phosphate",async()=>{const{molfile:e}=await a("RNA1{r(A)p.r(C)p}$$$$"),{molfile:n}=await a("RNA1{r(A)[Rsp].r(C)p}$$$$");c(e,e=>{(0,t.E3)(m(e,16),0,"plain RNA must contain no sulfur"),(0,t.E3)(m(e,15),2,"expected 2 phosphates in plain"),(0,t.E3)(d(e,p)>=1,!0,"plain inter-nucleotide diester must be present")}),c(n,e=>{(0,t.E3)(h(e,"[PX4]=S")||h(e,"[PX4][SX2,SX1H,SX1-]"),!0,"sulfur must be bonded to a phosphorus atom"),(0,t.E3)(d(e,g),1,"expected exactly one phosphorothioate diester linker"),(0,t.E3)(m(e,15),2,"expected 2 phosphates in modified"),(0,t.E3)(d(e,f),0,"expected zero direct C-P bonds")})}),(0,t.t6)("rna-modified-sugar",async()=>{const{molfile:e}=await a("RNA1{r(A)p.r(C)p}$$$$"),{molfile:n}=await a("RNA1{[fl2r](A)p.r(C)p}$$$$");c(e,e=>{(0,t.E3)(m(e,9),0,"plain RNA must contain no fluorine")}),c(n,e=>{(0,t.E3)(m(e,9),1,"fl2r contributes exactly one fluorine"),(0,t.E3)(d(e,v)>=1,!0,"fluorine must be on a furanose ring carbon (2'-F)"),(0,t.E3)(d(e,y)>=2,!0,"expected ≥ 2 furanose rings")})}),(0,t.t6)("rna-no-trailing-phosphate",async()=>{const{molfile:e}=await a("RNA1{r(A)p.r(C)p}$$$$"),{molfile:n}=await a("RNA1{r(A)p.r(C)}$$$$"),i=c(e,e=>m(e,15)),o=c(n,e=>m(e,15));(0,t.E3)(i,2,"with trailing P: 2 phosphates (1 linker + 1 trail)"),(0,t.E3)(o,1,"no trailing P: 1 phosphate (the linker only)"),c(n,e=>{(0,t.E3)(d(e,p),1,"inter-nucleotide diester must still be present"),(0,t.E3)(d(e,f),0,"no direct C-P bond"),(0,t.E3)(d(e,y),2,"both furanose rings present")})}),(0,t.t6)("rna-no-trailing-phosphate-with-modifications",async()=>{const{molfile:e}=await a("RNA1{[fl2r]([m5C])[Rsp].r(A)}$$$$");c(e,e=>{(0,t.E3)(m(e,9),1,"expected exactly 1 fluorine"),(0,t.E3)(d(e,v),1,"2'-F must be on a furanose ring carbon"),(0,t.E3)(m(e,15),1,"expected exactly 1 phosphorus (Rsp)"),(0,t.E3)(m(e,16),1,"expected exactly 1 sulfur (Rsp)"),(0,t.E3)(d(e,g),1,"Rsp linker must remain a phosphorothioate diester"),(0,t.E3)(d(e,w),1,"expected one 5-methylcytosine base")})}),(0,t.t6)("rna-all-modifications",async()=>{const{molfile:e}=await a("RNA1{[fl2r]([m5C])[Rsp].r(A)p}$$$$");c(e,e=>{(0,t.E3)(d(e,v),1,"fl2r: 2'-F on furanose"),(0,t.E3)(d(e,w),1,"m5C: 5-methylcytosine"),(0,t.E3)(d(e,g),1,"Rsp: phosphorothioate diester"),(0,t.E3)(m(e,15),2,"two phosphates (Rsp + trailing p)"),(0,t.E3)(m(e,16),1,"exactly one sulfur (from Rsp)")})}),(0,t.t6)("rna-helm-3p-terminal-galnac",async()=>{const{molfile:e}=await a("RNA1{r(T)[GalNAc]}$$$$V2.0");c(e,e=>{(0,t.E3)(m(e,15),0,"GalNAc terminus: no P expected"),(0,t.E3)(d(e,C)>=1,!0,"expected N-acetyl group from GalNAc"),(0,t.E3)(h(e,"[#6]1[#6][#6][#6][#6][O]1"),!0,"expected a pyranose (6-membered) ring from GalNAc")})}),(0,t.t6)("rna-helm-5p-terminal-chol",async()=>{const{molfile:e}=await a("RNA1{[Chol].r(T)}$$$$V2.0");c(e,e=>{(0,t.E3)(E(e),!0,"Chol terminus must produce the steroid (gonane) ring system"),(0,t.E3)(d(e,y),1,"expected exactly 1 furanose ring (from r(T))")})}),(0,t.t6)("rna-helm-5p-terminal-chol-with-trailing-phosphate",async()=>{const{molfile:e}=await a("RNA1{[Chol].r(T)p}$$$$V2.0");c(e,e=>{(0,t.E3)(E(e),!0,"expected steroid ring system from Chol"),(0,t.E3)(m(e,15),1,"expected exactly 1 phosphorus"),(0,t.E3)(d(e,y),1,"expected 1 furanose")})}),(0,t.t6)("rna-helm-both-terminals",async()=>{const{molfile:e}=await a("RNA1{[Chol].r(T)[GalNAc]}$$$$V2.0");c(e,e=>{(0,t.E3)(m(e,15),0,"expected zero phosphates"),(0,t.E3)(E(e),!0,"expected steroid (Chol) ring system"),(0,t.E3)(d(e,C)>=1,!0,"expected N-acetyl group from GalNAc"),(0,t.E3)(h(e,"[#6]1[#6][#6][#6][#6][O]1"),!0,"expected pyranose ring from GalNAc")})}),(0,t.t6)("rna-helm-lna-base-above-sugar",async()=>{const{molfile:e}=await a("RNA1{[lna](A)p.[lna](T)}$$$$V2.0");c(e,e=>{(0,t.E3)(h(e,"[*]"),!0,"molecule must be non-empty");const n=d(e,A);(0,t.E3)(n>=4,!0,`expected ≥ 4 ring carbons in 2 rings (LNA bicyclic), got ${n}`),(0,t.E3)(d(e,p)>=1,!0,"expected ≥ 1 phosphodiester linker"),(0,t.E3)(d(e,f),0,"expected zero direct C-P bonds"),(0,t.E3)(d(e,b)>=1,!0,"expected adenine ring (purine)"),(0,t.E3)(h(e,"[CH3][#6]1=[#6][#7]([!#1])[#6](=O)[#7][#6]1=O")||h(e,"Cc1cn([!#1])c(=O)[nH]c1=O"),!0,"expected thymine ring (5-methyluracil)")}),function(e){const n=function(e){const t=[],n=e.indexOf("M V30 BEGIN ATOM");if(n<0)return t;const i=e.indexOf("M V30 END ATOM",n),o=e.substring(n,i>=0?i:e.length),s=/^M\s+V30\s+(\d+)\s+(\S+)\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)/gm;let r;for(;r=s.exec(o);)parseInt(r[1])-1===t.length&&t.push({element:r[2],x:parseFloat(r[3]),y:parseFloat(r[4])});return t}(e);if(0===n.length)throw new Error("failed to parse molblock atoms");c(e,e=>{const i=S(e,y),o=S(e,"[a]");if(0===i.size)throw new Error("no furanose ring atoms found — cannot verify layout");if(0===o.size)throw new Error("no aromatic base atoms found — cannot verify layout");let s=-1/0;for(const e of i)s=Math.max(s,n[e].y);let r=1/0;for(const e of o)r=Math.min(r,n[e].y);(0,t.E3)(r>s,!0,`expected base atoms above sugar (minBaseY=${r.toFixed(3)}, maxSugarY=${s.toFixed(3)})`)})}(e)}),(0,t.t6)("rna-helm-3p-terminal-galnac-no-extra-oh",async()=>{const{molfile:e}=await a("RNA1{[lna](T)[GalNAc]}$$$$V2.0");c(e,e=>{(0,t.E3)(m(e,8),10,"expected exactly 10 oxygen atoms in lna(T)GalNAc"),(0,t.E3)(m(e,15),0,"expected no phosphate"),(0,t.E3)(h(e,C),!0,"expected GalNAc N-acetyl group"),(0,t.E3)(d(e,A)>=2,!0,"expected LNA bicyclic bridgeheads")})}),(0,t.t6)("rna-helm-h-cap-phosphate-sp-connects",async()=>{const{molfile:e,smiles:n}=await a("RNA1{r(T)[sp].r(A)}$$$$V2.0");(0,t.E3)(-1===n.indexOf("."),!0,`expected single connected fragment, got: ${n}`),c(e,e=>{(0,t.E3)(d(e,"[PX4][SX2,SX1H,SX1-]"),1,"sp's sulfur must be on its phosphorus"),(0,t.E3)(m(e,15),1,"one phosphorus from the sp linker"),(0,t.E3)(m(e,16),1,"one sulfur from the sp linker"),(0,t.E3)(d(e,g),1,"sp linker must be a phosphorothioate diester (C-O-P-O-C)"),(0,t.E3)(d(e,f),0,"no direct C-P bond")})}),(0,t.t6)("rna-helm-sp-bridging-o-preserved",async()=>{const{molfile:e}=await a("RNA1{m(A)[sp].r(A)[sp]}$$$$V2.0");c(e,e=>{(0,t.E3)(m(e,15),2,"expected exactly 2 phosphorus atoms"),(0,t.E3)(m(e,16),2,"expected exactly 2 sulfur atoms"),(0,t.E3)(d(e,"[PX4][SX2,SX1H,SX1-]"),2,"both sulfurs must be bonded to a phosphorus atom"),(0,t.E3)(d(e,g),1,"inter-nucleotide sp must remain a phosphorothioate diester"),(0,t.E3)(d(e,"[CX4][OX2][PX4](=[OX1])[SX2,SX1H,SX1-]"),3,"every C-O-P-P=O-S match must be present (3: 2 from diester, 1 from monoester)"),(0,t.E3)(d(e,f),0,"expected zero direct C-P bonds — bridging O must be present"),(0,t.E3)(d(e,"[CH3][OX2][#6;R]"),1,"expected exactly one 2'-OMe group on the m sugar")})}),(0,t.t6)("rna-helm-bio-terminal-at-end",async()=>{const{molfile:e}=await a("RNA1{r(T)[Bio]}$$$$V2.0");c(e,e=>{(0,t.E3)(m(e,15),0,"Bio terminus: no phosphate"),(0,t.E3)(h(e,T),!0,"expected biotin ureido (cyclic urea) ring system"),(0,t.E3)(h(e,"[#16;R]"),!0,"expected ring sulfur (biotin's thiolane)"),(0,t.E3)(d(e,y),1,"expected the r(T) furanose")})}),(0,t.t6)("rna-helm-bio-terminal-at-start",async()=>{const{molfile:e}=await a("RNA1{[Bio].r(T)}$$$$V2.0");c(e,e=>{(0,t.E3)(m(e,15),0,"no phosphates"),(0,t.E3)(h(e,T),!0,"expected biotin ureido ring system at the 5' end"),(0,t.E3)(h(e,"[#16;R]"),!0,"expected biotin's thiolane ring sulfur"),(0,t.E3)(d(e,y),1,"expected the r(T) furanose")})}),(0,t.t6)("rna-helm-chol-terminal-at-start",async()=>{const{molfile:e}=await a("RNA1{[Chol].r(T)}$$$$V2.0");c(e,e=>{(0,t.E3)(E(e),!0,"expected steroid (gonane) ring system from Chol at 5'"),(0,t.E3)(d(e,y),1,"expected one r(T) furanose")})}),(0,t.t6)("rna-helm-chol-terminal-at-end",async()=>{const{molfile:e}=await a("RNA1{r(T)[Chol]}$$$$V2.0");c(e,e=>{(0,t.E3)(m(e,15),0,"no phosphate when Chol replaces trailing P"),(0,t.E3)(E(e),!0,"expected steroid (gonane) ring system from Chol at 3'"),(0,t.E3)(d(e,y),1,"expected one r(T) furanose")})})});var Te=o(8754);(0,t.L1)("toAtomicLevel-ui",()=>{let n,i,o,s,r;(0,t.gM)(async()=>{o=await(0,u.Q)(),r=await(0,fe.j)(),n=await(0,_.pj)(),i=await(0,D.u)(),await n.loadMonomerLibForTests(),s=n.getMonomerLib()}),(0,t.Pl)(async()=>{await(0,D.E)(i),await n.loadMonomerLib(!0)});const a={fasta:{src:{seq:"MDYKETLLMPK",units:c.Hi.FASTA},tgt:{atomCount:94,bondCount:95}},"fasta-with-gap":{src:{seq:"MD-YKETLLMPK",units:c.Hi.FASTA},tgt:{atomCount:94,bondCount:95}},helm:{src:{seq:"PEPTIDE1{meI.hHis.Aca.N.T.dK.Thr_PO3H2}$$$$",units:c.Hi.HELM},tgt:{atomCount:68,bondCount:68}},"helm-with-gap":{src:{seq:"PEPTIDE1{meI.hHis.*.Aca.N.T.dK.Thr_PO3H2}$$$$",units:c.Hi.HELM},tgt:{atomCount:68,bondCount:68}}},h=async t=>{const n=t.src.seq,i=e.DataFrame.fromColumns([e.Column.fromList(e.COLUMN_TYPE.STRING,"seq",[n])]);return await l.data.detectSemanticTypes(i),i.getCol("seq")};for(const[e,n]of Object.entries(a))(0,t.t6)(`${e}-linear`,async()=>{const e=await h(n);await d(e,!1,n.tgt)});if(e.Func.find({package:"Helm",name:"getHelmHelper"}).length)for(const[e,n]of Object.entries(a))(0,t.t6)(`${e}-nonlinear`,async()=>{const e=await h(n);await d(e,!0,n.tgt)});async function d(n,i,a){const l=await(0,Te.V)(n.dataFrame,n,i,!1,s,o,r);(0,t.E3)(l.molCol.semType,e.SEMTYPE.MOLECULE);const c=l.molCol.get(0),u=r.get_mol(c);(0,t.E3)(null!=u,!0,"No molecule generated");try{const e=u.get_num_atoms(),n=u.get_num_bonds();(0,t.E3)(e,a.atomCount),(0,t.E3)(n,a.bondCount)}finally{u.delete()}}});var Ee=o(6863);async function Se(t,n){const i=e.DataFrame.fromCsv(t),o=i.col("seq"),s=await l.functions.call("Bio:detectMacromolecule",{col:o});return s&&(o.semType=s),await l.data.detectSemanticTypes(i),n.getSeqHandler(o)}function Me(e,n,i,o){const s=i(e,n);(0,t.E3)(Number(s.toFixed(3)),Number(o.toFixed(3)))}(0,t.L1)("Distance",async()=>{let n;(0,t.gM)(async()=>{n=await(0,u.Q)()});const i=[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]],o={F:0,W:1,R:2,Y:3},s="FWRWY",r="FWRWW",a="FWY",l="FWRWY",c="FWY",h="FWRRRRY";(0,t.t6)("protein-distance-function",async()=>{const e=(await Se("seq\nFWRWYVKHPFWRWYVKHP\nYNRWYVKHPYNRWYVKHP\nMWRSWYCKHPMWRSWYCKHP",n)).getDistanceFunctionName();(0,t.E3)(e,Ee.Z.LEVENSHTEIN)}),(0,t.t6)("DNA-distance-function",async()=>{const e=(await Se("seq\nATAACGATAACG\nATCGAATCGA\nATCGAATCGA",n)).getDistanceFunctionName();(0,t.E3)(e,Ee.Z.LEVENSHTEIN)}),(0,t.t6)("MSA-distance-function",async()=>{const e=(await Se("seq\nATAACATAAC\nATCGAATCGA\nATCGAATCGA",n)).getDistanceFunctionName();(0,t.E3)(e,Ee.Z.HAMMING)}),(0,t.t6)("levenstein-sub",async()=>{const e=Ee.V[Ee.Z.LEVENSHTEIN]();Me(s,r,e,.2)}),(0,t.t6)("levenstein-del",async()=>{const e=Ee.V[Ee.Z.LEVENSHTEIN]();Me(a,l,e,.4)}),(0,t.t6)("hamming",async()=>{const e=Ee.V[Ee.Z.HAMMING]();Me(a,l,e,.6)}),(0,t.t6)("needleman-blosum62",async()=>{const e=Ee.V[Ee.Z.NEEDLEMANN_WUNSCH]({gapOpen:8,gapExtend:2});Me(s,r,e,-6)}),(0,t.t6)("needleman-blosum62-del",async()=>{const e=Ee.V[Ee.Z.NEEDLEMANN_WUNSCH]({gapOpen:8,gapExtend:2});Me(a,l,e,-3.667)}),(0,t.t6)("needleman-custom-sub",async()=>{const e=Ee.V[Ee.Z.NEEDLEMANN_WUNSCH]({scoringMatrix:i,alphabetIndexes:o,gapOpen:1,gapExtend:1});Me(s,r,e,.2)}),(0,t.t6)("needleman-custom-del",async()=>{const e=Ee.V[Ee.Z.NEEDLEMANN_WUNSCH]({scoringMatrix:i,alphabetIndexes:o,gapOpen:1,gapExtend:1});Me(a,l,e,.667)}),(0,t.t6)("needleman-custom-zero-extend",async()=>{const e=Ee.V[Ee.Z.NEEDLEMANN_WUNSCH]({scoringMatrix:i,alphabetIndexes:o,gapOpen:1,gapExtend:0});Me(c,h,e,.333)}),(0,t.t6)("needleman-custom-half-extend",async()=>{const e=Ee.V[Ee.Z.NEEDLEMANN_WUNSCH]({scoringMatrix:i,alphabetIndexes:o,gapOpen:2,gapExtend:1});Me(c,h,e,1.667)}),(0,t.t6)("needleman-custom-same-extend",async()=>{const t=Ee.V[Ee.Z.NEEDLEMANN_WUNSCH]({scoringMatrix:i,alphabetIndexes:o,gapOpen:1,gapExtend:1});e.Test.isInBenchmark?Me(Array(1e3).fill(c).join(""),Array(1e3).fill(h).join(""),t,1.333):Me(c,h,t,1.333)},{benchmark:!0})});var xe=o(684);async function Pe(n,i,o,s,r,a,c,u){await l.data.detectSemanticTypes(n),await l.functions.call("Bio:activityCliffs",{table:n,molecules:n.getCol(o),activities:n.getCol(s),similarity:r,methodName:i,similarityMetric:c,preprocessingFunction:u,options:{[`${xe.vb}`]:!0},demo:!1});const h=Array.from(l.shell.tv.viewers)[1];(0,t.E3)(h?.type===e.VIEWER.SCATTER_PLOT,!0),await(0,t.bk)(()=>{const e=Array.from(h.root.getElementsByClassName("scatter_plot_link"));return!e.length||e[0].innerText.toLowerCase()===`${a} cliffs`},"incorrect cliffs link",3e3)}var Le=o(2780),Ie=o(9039),_e=o(9124);async function Ne(n,i,o){const s=n.getCol(o);n.name="seqSpaceDf";const r=await l.functions.call("Bio:detectMacromolecule",{col:s});r&&(s.semType=r);const a=e.Func.find({package:"Bio",name:"macromoleculePreprocessingFunction"})[0];if(!a)throw new Error("Preprocessing function not found");await l.functions.call("Bio:sequenceSpaceTopMenu",{table:n,molecules:n.col(o),methodName:i,similarityMetric:Ee.Z.LEVENSHTEIN,plotEmbeddings:!0,preprocessingFunction:a,options:{[xe.vb]:!0}});const c=l.shell.tableView(n.name),u=Array.from(c?.viewers??[])[1];(0,t.E3)(null!=u)}(0,t.L1)("activityCliffs",async()=>{let n,i,o;const s=e.Func.find({name:"macromoleculePreprocessingFunction",package:"Bio"})[0],r=e.Func.find({name:"helmPreprocessingFunction",package:"Bio"})[0];(0,t.gM)(async()=>{e.Func.find({package:"Helm",name:"getHelmHelper"}).length&&(n=await(0,_e.b2)()),i=await(0,_.pj)(),o=await(0,D.u)(),await i.loadMonomerLibForTests()}),(0,t.Pl)(async()=>{await(0,D.E)(o),await i.loadMonomerLib(!0)}),(0,t.t6)("activityCliffsOpens",async()=>{const t=e.Test.isInBenchmark?{fileName:"tests/peptides_with_random_motif_1600.csv",tgt:{cliffCount:64}}:{fileName:"tests/100_3_clustests.csv",tgt:{cliffCount:3}},n=await $(t.fileName);l.shell.addTableView(n),await Pe(n,Ie.c.UMAP,"sequence","Activity",90,t.tgt.cliffCount,Ee.Z.LEVENSHTEIN,s)},{benchmark:!0,skipReason:"Fails"}),(0,t.t6)("activityCliffsWithEmptyRows",async()=>{const e=await $("tests/100_3_clustests_empty_vals.csv");l.shell.addTableView(e),await Pe(e,Ie.c.UMAP,"sequence","Activity",90,3,Ee.Z.LEVENSHTEIN,s)}),(0,t.t6)("Helm",async()=>{if(e.Func.find({package:"Helm",name:"getHelmHelper"}).length){const e=await Ge.files.readCsv("samples/HELM_50.csv");l.shell.addTableView(e),await Pe(e,Ie.c.UMAP,"HELM","Activity",65,20,Le.aT.Tanimoto,r)}})}),(0,t.L1)("sequenceSpace",async()=>{let n,i,o,s;(0,t.t6)("sequenceSpaceOpens",async()=>{const t=e.Test.isInBenchmark?{fileName:"tests/peptides_with_random_motif_1600.csv"}:{fileName:"tests/100_3_clustests.csv"};n=await $(t.fileName),i=l.shell.addTableView(n),await Ne(n,Ie.c.UMAP,"sequence")},{benchmark:!0}),(0,t.t6)("sequenceSpaceWithEmptyRows",async()=>{o=await $("tests/100_3_clustests_empty_vals.csv"),s=l.shell.addTableView(o),await Ne(o,Ie.c.UMAP,"sequence")})}),(0,t.L1)("Scoring",()=>{const n="sequence",i="expected_similarity",o="expected_identity",s=e.DataFrame.fromCsv(`${n},${i},${o}\nPEPTIDE1{Aca.Orn.gGlu.Pqa.D-His_1Bn.dH.hHis.4Abz.D-Tic.D-Dap.Y.Iva.meS.F.P.F.D-1Nal}$$$$,1.0,1.0\nPEPTIDE1{Iva.Gly_allyl.gGlu.Pqa.D-Dip.dH.hHis.4Abz.D-aHyp.D-Dap.Y.Iva.I.Tyr_26diMe.P.Asu.meC}$$$$,0.691,0.53\nPEPTIDE1{[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal]}$$$$V2.0,0.37,0.0`),r=s.getCol(n);r.meta.units=c.Hi.HELM,r.semType=e.SEMTYPE.MACROMOLECULE;const a=r.get(0);let u,h;(0,t.gM)(async()=>{u=await(0,_.pj)(),h=await(0,D.u)(),await u.loadMonomerLibForTests()}),(0,t.Pl)(async()=>{await(0,D.E)(h),await u.loadMonomerLib(!0)}),(0,t.t6)("Identity",async()=>{const e=await l.functions.call("Bio:sequenceIdentityScoring",{table:s,macromolecule:r,reference:a});for(let n=0;n<e.length;n++){const i=e.get(n),r=s.get(o,n);(0,t.Wj)(i,r,.01,`Wrong identity score for sequence at position ${n}`)}}),(0,t.t6)("Identity-shortReference",async()=>{const e=await l.functions.call("Bio:sequenceIdentityScoring",{table:s,macromolecule:r,reference:"PEPTIDE1{Iva.Gly_allyl.gGlu.Pqa.D-Dip.dH.hHis.4Abz.D-aHyp.D-Dap.Y.Iva}$$$$"});(0,t.E3)(L().count(0).take(e.length).map(t=>e.get(t)).every(e=>null!=e&&!isNaN(e)),!0)}),(0,t.t6)("Identity-longReference",async()=>{const e=await l.functions.call("Bio:sequenceIdentityScoring",{table:s,macromolecule:r,reference:"PEPTIDE1{Iva.Gly_allyl.gGlu.Pqa.D-Dip.dH.hHis.4Abz.D-aHyp.D-Dap.Y.Iva.I.Tyr_26diMe.P.Asu.meC.I.Tyr_26diMe.P.Asu.meC}$$$$"});(0,t.E3)(L().count(0).take(e.length).map(t=>e.get(t)).every(e=>null!=e&&!isNaN(e)),!0)}),(0,t.t6)("Similarity",async()=>{const e=await l.functions.call("Bio:sequenceSimilarityScoring",{table:s,macromolecule:r,reference:a});for(let n=0;n<e.length;n++){const o=e.get(n),r=s.get(i,n);(0,t.Wj)(o,r,.01,`Wrong similarity score for sequence at position ${n}`)}})}),(0,t.L1)("projects",()=>{let n,i;async function o(n,i,o,s,r,a){let c;r?(await e.Func.find({name:"OpenFile"})[0].prepare({fullPath:`System:AppData/Bio/${n}`}).call(void 0,void 0,{processed:!1}),c=l.shell.tv,await l.data.detectSemanticTypes(c.dataFrame)):c=await async function(e){const t=await $(e);return t.name=e.replace(".csv",""),await l.data.detectSemanticTypes(t),l.shell.addTableView(t)}(n),await(0,t.cb)(100),await i(c),await(0,t.cb)(10),await async function(t,n){const i=e.Project.create();i.name="Test project";const o=t.dataFrame.getTableInfo();n&&(o.tags[e.Tags.DataSync]="sync",o.tags[e.Tags.CreationScript]=l.shell.tv.dataFrame.getTag(e.Tags.CreationScript));const s=t.getInfo();i.addChild(o),i.addChild(s),await l.dapi.tables.uploadDataFrame(t.dataFrame),await l.dapi.tables.save(o),await l.dapi.views.save(s),await l.dapi.projects.save(i);const r=i.id;l.shell.closeAll();const a=await l.dapi.projects.find(r);await a.open()}(c,r),await(0,t.cb)(10),await async function(e){let n="";await(0,t.bk)(()=>{if(!l.shell.tv.dataFrame)return!1;for(const t of e)if(!l.shell.tv.dataFrame.col(t))return n=t,!1;return!0},`${n} hasn't been added to dataframe`,5e3)}(o),s&&await async function(e){await(0,t.bk)(()=>{for(const t of l.shell.tv.viewers)if(t.type===e)return!0;return!1},`${e} hasn't been added`,5e3)}(s),a&&await a(c)}async function s(n){const i=n.dataFrame.col("sequence"),o=await l.functions.call("Bio:detectMacromolecule",{col:i});o&&(i.semType=o),await e.Func.find({package:"Bio",name:"sequenceSpaceTopMenu"})[0].prepare({table:n.dataFrame,molecules:i,methodName:"UMAP",similarityMetric:Ee.Z.LEVENSHTEIN,plotEmbeddings:!0,options:{[xe.vb]:!0},clusterEmbeddings:!0}).call(void 0,void 0,{processed:!1}),await(0,t.cb)(10)}async function r(n){const i=n.dataFrame.col("sequence"),o=await l.functions.call("Bio:detectMacromolecule",{col:i});o&&(i.semType=o),await e.Func.find({package:"Bio",name:"activityCliffs"})[0].prepare({table:n.dataFrame,molecules:i,activities:n.dataFrame.col("Activity"),similarity:90,methodName:"UMAP",similarityMetric:Ee.Z.LEVENSHTEIN,preprocessingFunction:e.Func.find({name:"macromoleculePreprocessingFunction",package:"Bio"})[0],options:{[xe.vb]:!0}}).call(void 0,void 0,{processed:!1}),await(0,t.cb)(10)}async function a(n){let i=null;for(const t of l.shell.tv.viewers)t.type===e.VIEWER.SCATTER_PLOT&&(i=t);await(0,t.bk)(()=>{const e=i?.root.getElementsByClassName("scatter_plot_link");return!(!e||!e.length)&&e[0].innerText.toLowerCase().includes("cliffs")},"Initialization function hasn't been applied on scatter plot",5e3)}(0,t.t6)("sequence_space",async()=>{n=await(0,_.pj)(),i=await(0,D.u)(),await n.loadMonomerLibForTests(),await o("tests/100_3_clustests.csv",s,["sequence","Embed_X_1","Embed_Y_1","Cluster (DBSCAN)"],e.VIEWER.SCATTER_PLOT),await(0,t.cb)(100),await(0,D.E)(i),await n.loadMonomerLib(!0)},{timeout:6e4}),(0,t.t6)("sequence_space_sync",async()=>{n=await(0,_.pj)(),i=await(0,D.u)(),await n.loadMonomerLibForTests(),await o("tests/100_3_clustests.csv",s,["sequence","Embed_X_1","Embed_Y_1","Cluster (DBSCAN)"],e.VIEWER.SCATTER_PLOT,!0),await(0,t.cb)(100),await(0,D.E)(i),await n.loadMonomerLib(!0)},{timeout:6e4}),(0,t.t6)("activity_cliffs",async()=>{n=await(0,_.pj)(),i=await(0,D.u)(),await n.loadMonomerLibForTests(),await o("tests/100_3_clustests.csv",r,["sequence","Activity","Embed_X_1","Embed_Y_1"],e.VIEWER.SCATTER_PLOT,!1,a),await(0,t.cb)(100),await(0,D.E)(i),await n.loadMonomerLib(!0)},{timeout:6e4}),(0,t.t6)("activity_cliffs_sync",async()=>{n=await(0,_.pj)(),i=await(0,D.u)(),await n.loadMonomerLibForTests(),await o("tests/100_3_clustests.csv",r,["sequence","Activity","Embed_X_1","Embed_Y_1"],e.VIEWER.SCATTER_PLOT,!0,a),await(0,t.cb)(100),await(0,D.E)(i),await n.loadMonomerLib(!0)},{timeout:6e4})});var Re=o(3328),$e=o(417),Oe=o(9036);const He="QVQLVQSGAEVKKPGASVKVSCKASGYTFTGYYMHWVRQAPGQGLEWMGWINPNSGGTNYAQKFQGRVTMTRDTSISTAYMELSRLRSDDTAVYYCARVAPGALDYWGQGTLVTVSS",De="DIQMTQSPSSLSASVGDRVTITCRASQDVSTAVAWYQQKPGKAPKLLIYSASFLYSGVPSRFSGSGSGTDFTLTISSLQPEDFATYYCQQSYSTPRTFGQGTKVEIK",Fe="QSALTQPASVSGSPGQSITISCTGTSSDVGGYNYVSWYQQHPGKAPKLMIYDVSNRPSGVSNRFSGSKSGNTASLTISGLQAEDEADYYCSSYTSSSTLVFGGGTKLTVL",ke=["FR1","CDR1","FR2","CDR2","FR3","CDR3","FR4"];(0,t.L1)("antibody numbering (immunum)",()=>{(0,t.t6)("worker: heavy chain (IMGT)",async()=>{const[e]=await(0,$e.m)([He],"imgt");(0,t.E3)(e.chainType,"Heavy"),(0,t.E3)(e.chainCode,"H"),(0,t.E3)(e.confidence>=.5,!0),(0,t.E3)(e.positionNames.length>0,!0),(0,t.E3)(e.numberingDetail.length>0,!0);for(const n of Object.values(e.numberingMap))(0,t.E3)(n>=0&&n<117,!0);(0,t.E3)(e.numberingDetail.length,Object.keys(e.numberingMap).length)}),(0,t.t6)("worker: light kappa chain (IMGT)",async()=>{const[e]=await(0,$e.m)([De],"imgt");(0,t.E3)(e.chainType,"Light"),(0,t.E3)("K"===e.chainCode||"L"===e.chainCode,!0),(0,t.E3)(e.confidence>=.5,!0),(0,t.E3)(e.numberingDetail.length>0,!0)}),(0,t.t6)("worker: light lambda chain (IMGT)",async()=>{const[e]=await(0,$e.m)([Fe],"imgt");(0,t.E3)(e.chainType,"Light"),(0,t.E3)(e.confidence>=.5,!0)}),(0,t.t6)("worker: batch numbering",async()=>{const e=await(0,$e.m)([He,De,"EVQLVESGGGLVQPGGSLRLSCAASGFTFSSYAMSWVRQAPGKGLEWVSAISGSGGSTYYADSVKGRFTISRDNSKNTLYLQMNSLRAEDTAVYYCAKDHYSGSGSYYYYFDYWGQGTLVTVSS",Fe],"imgt");(0,t.E3)(e.length,4),(0,t.E3)(e[0].chainType,"Heavy"),(0,t.E3)(e[1].chainType,"Light"),(0,t.E3)(e[2].chainType,"Heavy"),(0,t.E3)(e[3].chainType,"Light")}),(0,t.t6)("worker: empty / short sequences fail gracefully",async()=>{const e=await(0,$e.m)(["","AAAA"," "],"imgt");(0,t.E3)(e.length,3);for(const n of e)(0,t.E3)(n.positionNames,""),(0,t.E3)(n.numberingDetail.length,0),(0,t.E3)(n.error.length>0,!0)}),(0,t.t6)("worker: kabat scheme returns kabat-style position codes",async()=>{const[e]=await(0,$e.m)([He],"imgt"),[n]=await(0,$e.m)([He],"kabat");(0,t.E3)(e.chainType,"Heavy"),(0,t.E3)(n.chainType,"Heavy");const i=new Set(Object.keys(e.numberingMap)),o=new Set(Object.keys(n.numberingMap));let s=!1;for(const e of o)if(!i.has(e)){s=!0;break}(0,t.E3)(s,!0)}),(0,t.t6)("numberAntibodyColumn: DataFrame shape matches antpack script",async()=>{const n=e.Column.fromStrings("seq",[He,De,""]);n.semType=e.SEMTYPE.MACROMOLECULE;const i=await(0,Oe.C)(n,"imgt");for(const e of["position_names","chain_type","annotations_json","numbering_detail","numbering_map"])(0,t.E3)(null!==i.col(e),!0);(0,t.E3)(i.rowCount,3),(0,t.E3)(i.get("position_names",0).length>0,!0),(0,t.E3)(i.get("chain_type",0),"Heavy");const o=JSON.parse(i.get("annotations_json",0));(0,t.E3)(o.length,7),(0,t.E3)(o.map(e=>e.name).join(","),ke.join(","));for(const e of o)(0,t.E3)(e.visualType,"region"),(0,t.E3)(e.category,"structure"),(0,t.E3)(e.sourceScheme,"IMGT"),(0,t.E3)(e.autoGenerated,!0);(0,t.E3)(i.get("chain_type",1),"Light");const s=JSON.parse(i.get("annotations_json",1));(0,t.E3)(s.length,7),(0,t.E3)(i.get("position_names",2),""),(0,t.E3)(i.get("chain_type",2),""),(0,t.E3)(i.get("annotations_json",2),"[]"),(0,t.E3)(i.get("numbering_detail",2),""),(0,t.E3)(i.get("numbering_map",2),"")}),(0,t.t6)("numberAntibodyColumn: numbering_map indices line up with sequence",async()=>{const n=e.Column.fromStrings("seq",[He]);n.semType=e.SEMTYPE.MACROMOLECULE;const i=await(0,Oe.C)(n,"imgt"),o=JSON.parse(i.get("numbering_detail",0)),s=JSON.parse(i.get("numbering_map",0));for(const e of o){const n=s[e.position];(0,t.E3)("number"==typeof n,!0),(0,t.E3)(He[n],e.aa)}}),(0,t.t6)("numberAntibodyColumn: annotations_json start/end resolve via numbering_map",async()=>{const n=e.Column.fromStrings("seq",[He]);n.semType=e.SEMTYPE.MACROMOLECULE;const i=await(0,Oe.C)(n,"imgt"),o=JSON.parse(i.get("annotations_json",0)),s=JSON.parse(i.get("numbering_map",0)),r=o.find(e=>"FR1"===e.name);(0,t.E3)(void 0!==r,!0);const a=s[r.start];(0,t.E3)("number"==typeof a,!0),(0,t.E3)(a>=0&&a<117,!0)}),(0,t.t6)("numberAntibodyColumn: loads antibodies.csv sample subset",async()=>{let n;try{n=await Re._package.files.readCsv("samples/antibodies.csv")}catch(e){return void console.warn("antibodies.csv not available — skipping",e)}const i=n.col("AntibodyHC")??n.col("HeavyChain")??n.columns.byName("AntibodyHC");if(!i)return;const o=e.Column.fromStrings("seq",Array.from({length:Math.min(10,i.length)},(e,t)=>i.get(t)??""));o.semType=e.SEMTYPE.MACROMOLECULE;const s=await(0,Oe.C)(o,"imgt");(0,t.E3)(s.rowCount,o.length);let r=0;for(let e=0;e<s.rowCount;e++)"Heavy"===s.get("chain_type",e)&&r++;(0,t.E3)(r>=Math.ceil(.6*o.length),!0)})});const Ge=new e.Package;async function Be(n,i,o,s){const r=await(0,t.N$)({category:n,test:i,testContext:o,stressTest:s});return e.DataFrame.fromObjects(r)}async function Ve(){await(0,t.Xb)(Ge,Ge.getModule("package-test.js"))}})(),bio_test=s})();
|
|
7
|
+
deps: ${n}}`};const r={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(e){const[t,n]=function({schema:e}){const t={},n={};for(const i in e)"__proto__"!==i&&((Array.isArray(e[i])?t:n)[i]=e[i]);return[t,n]}(e);a(e,t),l(e,n)}};function a(e,t=e.schema){const{gen:n,data:o,it:r}=e;if(0===Object.keys(t).length)return;const a=n.let("missing");for(const l in t){const c=t[l];if(0===c.length)continue;const u=(0,s.propertyInData)(n,o,l,r.opts.ownProperties);e.setParams({property:l,depsCount:c.length,deps:c.join(", ")}),r.allErrors?n.if(u,()=>{for(const t of c)(0,s.checkReportMissingProp)(e,t)}):(n.if(i._`${u} && (${(0,s.checkMissingProp)(e,c,a)})`),(0,s.reportMissingProp)(e,a),n.else())}}function l(e,t=e.schema){const{gen:n,data:i,keyword:r,it:a}=e,l=n.name("valid");for(const c in t)(0,o.alwaysValidSchema)(a,t[c])||(n.if((0,s.propertyInData)(n,i,c,a.opts.ownProperties),()=>{const t=e.subschema({keyword:r,schemaProp:c},l);e.mergeValidEvaluated(t,l)},()=>n.var(l,!0)),e.ok(l))}t.validatePropertyDeps=a,t.validateSchemaDeps=l,t.default=r},4845(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(3025),o={keyword:"dependentSchemas",type:"object",schemaType:"object",code:e=>(0,i.validateSchemaDeps)(e)};t.default=o},1239(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(4227),s={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:e})=>i.str`must match "${e.ifClause}" schema`,params:({params:e})=>i._`{failingKeyword: ${e.ifClause}}`},code(e){const{gen:t,parentSchema:n,it:s}=e;void 0===n.then&&void 0===n.else&&(0,o.checkStrictMode)(s,'"if" without "then" and "else" is ignored');const a=r(s,"then"),l=r(s,"else");if(!a&&!l)return;const c=t.let("valid",!0),u=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}(),e.reset(),a&&l){const n=t.let("ifClause");e.setParams({ifClause:n}),t.if(u,h("then",n),h("else",n))}else a?t.if(u,h("then")):t.if((0,i.not)(u),h("else"));function h(n,o){return()=>{const s=e.subschema({keyword:n},u);t.assign(c,u),e.mergeValidEvaluated(s,c),o?t.assign(o,i._`${n}`):e.setParams({ifClause:n})}}e.pass(c,()=>e.error(!0))}};function r(e,t){const n=e.schema[t];return void 0!==n&&!(0,o.alwaysValidSchema)(e,n)}t.default=s},6378(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(5457),o=n(5354),s=n(494),r=n(3966),a=n(2661),l=n(3025),c=n(2094),u=n(8660),h=n(117),d=n(5333),m=n(7923),p=n(6505),g=n(6163),f=n(5844),y=n(1239),b=n(4426);t.default=function(e=!1){const t=[m.default,p.default,g.default,f.default,y.default,b.default,c.default,u.default,l.default,h.default,d.default];return e?t.push(o.default,r.default):t.push(i.default,s.default),t.push(a.default),t}},494(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateTuple=void 0;const i=n(9029),o=n(4227),s=n(5765),r={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:n}=e;if(Array.isArray(t))return a(e,"additionalItems",t);n.items=!0,(0,o.alwaysValidSchema)(n,t)||e.ok((0,s.validateArray)(e))}};function a(e,t,n=e.schema){const{gen:s,parentSchema:r,data:a,keyword:l,it:c}=e;!function(e){const{opts:i,errSchemaPath:s}=c,r=n.length,a=r===e.minItems&&(r===e.maxItems||!1===e[t]);if(i.strictTuples&&!a){const e=`"${l}" is ${r}-tuple, but minItems or maxItems/${t} are not specified or different at path "${s}"`;(0,o.checkStrictMode)(c,e,i.strictTuples)}}(r),c.opts.unevaluated&&n.length&&!0!==c.items&&(c.items=o.mergeEvaluated.items(s,n.length,c.items));const u=s.name("valid"),h=s.const("len",i._`${a}.length`);n.forEach((t,n)=>{(0,o.alwaysValidSchema)(c,t)||(s.if(i._`${h} > ${n}`,()=>e.subschema({keyword:l,schemaProp:n,dataProp:n},u)),e.ok(u))})}t.validateTuple=a,t.default=r},3966(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(4227),s=n(5765),r=n(5457),a={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>i.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>i._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:n,it:i}=e,{prefixItems:a}=n;i.items=!0,(0,o.alwaysValidSchema)(i,t)||(a?(0,r.validateAdditionalItems)(e,a):e.ok((0,s.validateArray)(e)))}};t.default=a},7923(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(4227),o={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:n,it:o}=e;if((0,i.alwaysValidSchema)(o,n))return void e.fail();const s=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),e.failResult(s,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};t.default=o},6163(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(4227),s={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:e})=>i._`{passingSchemas: ${e.passing}}`},code(e){const{gen:t,schema:n,parentSchema:s,it:r}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(r.opts.discriminator&&s.discriminator)return;const a=n,l=t.let("valid",!1),c=t.let("passing",null),u=t.name("_valid");e.setParams({passing:c}),t.block(function(){a.forEach((n,s)=>{let a;(0,o.alwaysValidSchema)(r,n)?t.var(u,!0):a=e.subschema({keyword:"oneOf",schemaProp:s,compositeRule:!0},u),s>0&&t.if(i._`${u} && ${l}`).assign(l,!1).assign(c,i._`[${c}, ${s}]`).else(),t.if(u,()=>{t.assign(l,!0),t.assign(c,s),a&&e.mergeEvaluated(a,i.Name)})})}),e.result(l,()=>e.reset(),()=>e.error(!0))}};t.default=s},5333(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(5765),o=n(9029),s=n(4227),r=n(4227),a={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,data:a,parentSchema:l,it:c}=e,{opts:u}=c,h=(0,i.allSchemaProperties)(n),d=h.filter(e=>(0,s.alwaysValidSchema)(c,n[e]));if(0===h.length||d.length===h.length&&(!c.opts.unevaluated||!0===c.props))return;const m=u.strictSchema&&!u.allowMatchingProperties&&l.properties,p=t.name("valid");!0===c.props||c.props instanceof o.Name||(c.props=(0,r.evaluatedPropsToName)(t,c.props));const{props:g}=c;function f(e){for(const t in m)new RegExp(e).test(t)&&(0,s.checkStrictMode)(c,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function y(n){t.forIn("key",a,s=>{t.if(o._`${(0,i.usePattern)(e,n)}.test(${s})`,()=>{const i=d.includes(n);i||e.subschema({keyword:"patternProperties",schemaProp:n,dataProp:s,dataPropType:r.Type.Str},p),c.opts.unevaluated&&!0!==g?t.assign(o._`${g}[${s}]`,!0):i||c.allErrors||t.if((0,o.not)(p),()=>t.break())})})}!function(){for(const e of h)m&&f(e),c.allErrors?y(e):(t.var(p,!0),y(e),t.if(p))}()}};t.default=a},5354(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(494),o={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,i.validateTuple)(e,"items")};t.default=o},117(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(2586),o=n(5765),s=n(4227),r=n(8660),a={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,parentSchema:a,data:l,it:c}=e;"all"===c.opts.removeAdditional&&void 0===a.additionalProperties&&r.default.code(new i.KeywordCxt(c,r.default,"additionalProperties"));const u=(0,o.allSchemaProperties)(n);for(const e of u)c.definedProperties.add(e);c.opts.unevaluated&&u.length&&!0!==c.props&&(c.props=s.mergeEvaluated.props(t,(0,s.toHash)(u),c.props));const h=u.filter(e=>!(0,s.alwaysValidSchema)(c,n[e]));if(0===h.length)return;const d=t.name("valid");for(const n of h)m(n)?p(n):(t.if((0,o.propertyInData)(t,l,n,c.opts.ownProperties)),p(n),c.allErrors||t.else().var(d,!0),t.endIf()),e.it.definedProperties.add(n),e.ok(d);function m(e){return c.opts.useDefaults&&!c.compositeRule&&void 0!==n[e].default}function p(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},d)}}};t.default=a},2094(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(4227),s={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:e})=>i._`{propertyName: ${e.propertyName}}`},code(e){const{gen:t,schema:n,data:s,it:r}=e;if((0,o.alwaysValidSchema)(r,n))return;const a=t.name("valid");t.forIn("key",s,n=>{e.setParams({propertyName:n}),e.subschema({keyword:"propertyNames",data:n,dataTypes:["string"],propertyName:n,compositeRule:!0},a),t.if((0,i.not)(a),()=>{e.error(!0),r.allErrors||t.break()})}),e.ok(a)}};t.default=s},4426(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(4227),o={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){void 0===t.if&&(0,i.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};t.default=o},5765(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateUnion=t.validateArray=t.usePattern=t.callValidateCode=t.schemaProperties=t.allSchemaProperties=t.noPropertyInData=t.propertyInData=t.isOwnProperty=t.hasPropFunc=t.reportMissingProp=t.checkMissingProp=t.checkReportMissingProp=void 0;const i=n(9029),o=n(4227),s=n(2023),r=n(4227);function a(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:i._`Object.prototype.hasOwnProperty`})}function l(e,t,n){return i._`${a(e)}.call(${t}, ${n})`}function c(e,t,n,o){const s=i._`${t}${(0,i.getProperty)(n)} === undefined`;return o?(0,i.or)(s,(0,i.not)(l(e,t,n))):s}function u(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}t.checkReportMissingProp=function(e,t){const{gen:n,data:o,it:s}=e;n.if(c(n,o,t,s.opts.ownProperties),()=>{e.setParams({missingProperty:i._`${t}`},!0),e.error()})},t.checkMissingProp=function({gen:e,data:t,it:{opts:n}},o,s){return(0,i.or)(...o.map(o=>(0,i.and)(c(e,t,o,n.ownProperties),i._`${s} = ${o}`)))},t.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},t.hasPropFunc=a,t.isOwnProperty=l,t.propertyInData=function(e,t,n,o){const s=i._`${t}${(0,i.getProperty)(n)} !== undefined`;return o?i._`${s} && ${l(e,t,n)}`:s},t.noPropertyInData=c,t.allSchemaProperties=u,t.schemaProperties=function(e,t){return u(t).filter(n=>!(0,o.alwaysValidSchema)(e,t[n]))},t.callValidateCode=function({schemaCode:e,data:t,it:{gen:n,topSchemaRef:o,schemaPath:r,errorPath:a},it:l},c,u,h){const d=h?i._`${e}, ${t}, ${o}${r}`:t,m=[[s.default.instancePath,(0,i.strConcat)(s.default.instancePath,a)],[s.default.parentData,l.parentData],[s.default.parentDataProperty,l.parentDataProperty],[s.default.rootData,s.default.rootData]];l.opts.dynamicRef&&m.push([s.default.dynamicAnchors,s.default.dynamicAnchors]);const p=i._`${d}, ${n.object(...m)}`;return u!==i.nil?i._`${c}.call(${u}, ${p})`:i._`${c}(${p})`};const h=i._`new RegExp`;t.usePattern=function({gen:e,it:{opts:t}},n){const o=t.unicodeRegExp?"u":"",{regExp:s}=t.code,a=s(n,o);return e.scopeValue("pattern",{key:a.toString(),ref:a,code:i._`${"new RegExp"===s.code?h:(0,r.useFunc)(e,s)}(${n}, ${o})`})},t.validateArray=function(e){const{gen:t,data:n,keyword:s,it:r}=e,a=t.name("valid");if(r.allErrors){const e=t.let("valid",!0);return l(()=>t.assign(e,!1)),e}return t.var(a,!0),l(()=>t.break()),a;function l(r){const l=t.const("len",i._`${n}.length`);t.forRange("i",0,l,n=>{e.subschema({keyword:s,dataProp:n,dataPropType:o.Type.Num},a),t.if((0,i.not)(a),r)})}},t.validateUnion=function(e){const{gen:t,schema:n,keyword:s,it:r}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(e=>(0,o.alwaysValidSchema)(r,e))&&!r.opts.unevaluated)return;const a=t.let("valid",!1),l=t.name("_valid");t.block(()=>n.forEach((n,o)=>{const r=e.subschema({keyword:s,schemaProp:o,compositeRule:!0},l);t.assign(a,i._`${a} || ${l}`),e.mergeValidEvaluated(r,l)||t.if((0,i.not)(a))})),e.result(a,()=>e.reset(),()=>e.error(!0))}},3463(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};t.default=n},2128(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(3463),o=n(3693),s=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",i.default,o.default];t.default=s},3693(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.callRef=t.getValidate=void 0;const i=n(4551),o=n(5765),s=n(9029),r=n(2023),a=n(3835),l=n(4227),c={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:n,it:o}=e,{baseId:r,schemaEnv:l,validateName:c,opts:d,self:m}=o,{root:p}=l;if(("#"===n||"#/"===n)&&r===p.baseId)return function(){if(l===p)return h(e,c,l,l.$async);const n=t.scopeValue("root",{ref:p});return h(e,s._`${n}.validate`,p,p.$async)}();const g=a.resolveRef.call(m,p,r,n);if(void 0===g)throw new i.default(o.opts.uriResolver,r,n);return g instanceof a.SchemaEnv?function(t){const n=u(e,t);h(e,n,t,t.$async)}(g):function(i){const o=t.scopeValue("schema",!0===d.code.source?{ref:i,code:(0,s.stringify)(i)}:{ref:i}),r=t.name("valid"),a=e.subschema({schema:i,dataTypes:[],schemaPath:s.nil,topSchemaRef:o,errSchemaPath:n},r);e.mergeEvaluated(a),e.ok(r)}(g)}};function u(e,t){const{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):s._`${n.scopeValue("wrapper",{ref:t})}.validate`}function h(e,t,n,i){const{gen:a,it:c}=e,{allErrors:u,schemaEnv:h,opts:d}=c,m=d.passContext?r.default.this:s.nil;function p(e){const t=s._`${e}.errors`;a.assign(r.default.vErrors,s._`${r.default.vErrors} === null ? ${t} : ${r.default.vErrors}.concat(${t})`),a.assign(r.default.errors,s._`${r.default.vErrors}.length`)}function g(e){var t;if(!c.opts.unevaluated)return;const i=null===(t=null==n?void 0:n.validate)||void 0===t?void 0:t.evaluated;if(!0!==c.props)if(i&&!i.dynamicProps)void 0!==i.props&&(c.props=l.mergeEvaluated.props(a,i.props,c.props));else{const t=a.var("props",s._`${e}.evaluated.props`);c.props=l.mergeEvaluated.props(a,t,c.props,s.Name)}if(!0!==c.items)if(i&&!i.dynamicItems)void 0!==i.items&&(c.items=l.mergeEvaluated.items(a,i.items,c.items));else{const t=a.var("items",s._`${e}.evaluated.items`);c.items=l.mergeEvaluated.items(a,t,c.items,s.Name)}}i?function(){if(!h.$async)throw new Error("async schema referenced by sync schema");const n=a.let("valid");a.try(()=>{a.code(s._`await ${(0,o.callValidateCode)(e,t,m)}`),g(t),u||a.assign(n,!0)},e=>{a.if(s._`!(${e} instanceof ${c.ValidationError})`,()=>a.throw(e)),p(e),u||a.assign(n,!1)}),e.ok(n)}():e.result((0,o.callValidateCode)(e,t,m),()=>g(t),()=>p(t))}t.getValidate=u,t.callRef=h,t.default=c},6653(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(7652),s=n(3835),r=n(4551),a=n(4227),l={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===o.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>i._`{error: ${e}, tag: ${n}, tagValue: ${t}}`},code(e){const{gen:t,data:n,schema:l,parentSchema:c,it:u}=e,{oneOf:h}=c;if(!u.opts.discriminator)throw new Error("discriminator: requires discriminator option");const d=l.propertyName;if("string"!=typeof d)throw new Error("discriminator: requires propertyName");if(l.mapping)throw new Error("discriminator: mapping is not supported");if(!h)throw new Error("discriminator: requires oneOf keyword");const m=t.let("valid",!1),p=t.const("tag",i._`${n}${(0,i.getProperty)(d)}`);function g(n){const o=t.name("valid"),s=e.subschema({keyword:"oneOf",schemaProp:n},o);return e.mergeEvaluated(s,i.Name),o}t.if(i._`typeof ${p} == "string"`,()=>function(){const n=function(){var e;const t={},n=o(c);let i=!0;for(let t=0;t<h.length;t++){let c=h[t];if((null==c?void 0:c.$ref)&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){const e=c.$ref;if(c=s.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof s.SchemaEnv&&(c=c.schema),void 0===c)throw new r.default(u.opts.uriResolver,u.baseId,e)}const m=null===(e=null==c?void 0:c.properties)||void 0===e?void 0:e[d];if("object"!=typeof m)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${d}"`);i=i&&(n||o(c)),l(m,t)}if(!i)throw new Error(`discriminator: "${d}" must be required`);return t;function o({required:e}){return Array.isArray(e)&&e.includes(d)}function l(e,t){if(e.const)m(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${d}" must have "const" or "enum"`);for(const n of e.enum)m(n,t)}}function m(e,n){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${d}" values must be unique strings`);t[e]=n}}();t.if(!1);for(const e in n)t.elseIf(i._`${p} === ${e}`),t.assign(m,g(n[e]));t.else(),e.error(!1,{discrError:o.DiscrError.Mapping,tag:p,tagName:d}),t.endIf()}(),()=>e.error(!1,{discrError:o.DiscrError.Tag,tag:p,tagName:d})),e.ok(m)}};t.default=l},7652(e,t){"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(n||(t.DiscrError=n={}))},6105(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(2128),o=n(7060),s=n(6378),r=n(5520),a=n(5413),l=n(3265),c=n(7532),u=n(9857),h=[r.default,i.default,o.default,(0,s.default)(!0),c.default,u.metadataVocabulary,u.contentVocabulary,a.default,l.default];t.default=h},6144(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(2128),o=n(7060),s=n(6378),r=n(7532),a=n(9857),l=[i.default,o.default,(0,s.default)(),r.default,a.metadataVocabulary,a.contentVocabulary];t.default=l},2476(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dynamicAnchor=void 0;const i=n(9029),o=n(2023),s=n(3835),r=n(3693),a={keyword:"$dynamicAnchor",schemaType:"string",code:e=>l(e,e.schema)};function l(e,t){const{gen:n,it:a}=e;a.schemaEnv.root.dynamicAnchors[t]=!0;const l=i._`${o.default.dynamicAnchors}${(0,i.getProperty)(t)}`,c="#"===a.errSchemaPath?a.validateName:function(e){const{schemaEnv:t,schema:n,self:i}=e.it,{root:o,baseId:a,localRefs:l,meta:c}=t.root,{schemaId:u}=i.opts,h=new s.SchemaEnv({schema:n,schemaId:u,root:o,baseId:a,localRefs:l,meta:c});return s.compileSchema.call(i,h),(0,r.getValidate)(e,h)}(e);n.if(i._`!${l}`,()=>n.assign(l,c))}t.dynamicAnchor=l,t.default=a},3252(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.dynamicRef=void 0;const i=n(9029),o=n(2023),s=n(3693),r={keyword:"$dynamicRef",schemaType:"string",code:e=>a(e,e.schema)};function a(e,t){const{gen:n,keyword:r,it:a}=e;if("#"!==t[0])throw new Error(`"${r}" only supports hash fragment reference`);const l=t.slice(1);if(a.allErrors)c();else{const t=n.let("valid",!1);c(t),e.ok(t)}function c(e){if(a.schemaEnv.root.dynamicAnchors[l]){const t=n.let("_v",i._`${o.default.dynamicAnchors}${(0,i.getProperty)(l)}`);n.if(t,u(t,e),u(a.validateName,e))}else u(a.validateName,e)()}function u(t,i){return i?()=>n.block(()=>{(0,s.callRef)(e,t),n.let(i,!0)}):()=>(0,s.callRef)(e,t)}}t.dynamicRef=a,t.default=r},5520(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(2476),o=n(3252),s=n(2721),r=n(3799),a=[i.default,o.default,s.default,r.default];t.default=a},2721(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(2476),o=n(4227),s={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){e.schema?(0,i.dynamicAnchor)(e,""):(0,o.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};t.default=s},3799(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(3252),o={keyword:"$recursiveRef",schemaType:"string",code:e=>(0,i.dynamicRef)(e,e.schema)};t.default=o},4737(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>i.str`must match format "${e}"`,params:({schemaCode:e})=>i._`{format: ${e}}`},code(e,t){const{gen:n,data:o,$data:s,schema:r,schemaCode:a,it:l}=e,{opts:c,errSchemaPath:u,schemaEnv:h,self:d}=l;c.validateFormats&&(s?function(){const s=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),r=n.const("fDef",i._`${s}[${a}]`),l=n.let("fType"),u=n.let("format");n.if(i._`typeof ${r} == "object" && !(${r} instanceof RegExp)`,()=>n.assign(l,i._`${r}.type || "string"`).assign(u,i._`${r}.validate`),()=>n.assign(l,i._`"string"`).assign(u,r)),e.fail$data((0,i.or)(!1===c.strictSchema?i.nil:i._`${a} && !${u}`,function(){const e=h.$async?i._`(${r}.async ? await ${u}(${o}) : ${u}(${o}))`:i._`${u}(${o})`,n=i._`(typeof ${u} == "function" ? ${e} : ${u}.test(${o}))`;return i._`${u} && ${u} !== true && ${l} === ${t} && !${n}`}()))}():function(){const s=d.formats[r];if(!s)return void function(){if(!1!==c.strictSchema)throw new Error(e());function e(){return`unknown format "${r}" ignored in schema at path "${u}"`}d.logger.warn(e())}();if(!0===s)return;const[a,l,m]=function(e){const t=e instanceof RegExp?(0,i.regexpCode)(e):c.code.formats?i._`${c.code.formats}${(0,i.getProperty)(r)}`:void 0,o=n.scopeValue("formats",{key:r,ref:e,code:t});return"object"!=typeof e||e instanceof RegExp?["string",e,o]:[e.type||"string",e.validate,i._`${o}.validate`]}(s);a===t&&e.pass(function(){if("object"==typeof s&&!(s instanceof RegExp)&&s.async){if(!h.$async)throw new Error("async format in sync schema");return i._`await ${m}(${o})`}return"function"==typeof l?i._`${m}(${o})`:i._`${m}.test(${o})`}())}())}};t.default=o},7532(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=[n(4737).default];t.default=i},9857(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.contentVocabulary=t.metadataVocabulary=void 0,t.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],t.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]},5413(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(1846),o=n(4845),s=n(2626),r=[i.default,o.default,s.default];t.default=r},3265(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(392),o=n(3445),s=[i.default,o.default];t.default=s},3445(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(4227),s={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:{message:({params:{len:e}})=>i.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>i._`{limit: ${e}}`},code(e){const{gen:t,schema:n,data:s,it:r}=e,a=r.items||0;if(!0===a)return;const l=t.const("len",i._`${s}.length`);if(!1===n)e.setParams({len:a}),e.fail(i._`${l} > ${a}`);else if("object"==typeof n&&!(0,o.alwaysValidSchema)(r,n)){const n=t.var("valid",i._`${l} <= ${a}`);t.if((0,i.not)(n),()=>function(n,s){t.forRange("i",s,l,s=>{e.subschema({keyword:"unevaluatedItems",dataProp:s,dataPropType:o.Type.Num},n),r.allErrors||t.if((0,i.not)(n),()=>t.break())})}(n,a)),e.ok(n)}r.items=!0}};t.default=s},392(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(4227),s=n(2023),r={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:{message:"must NOT have unevaluated properties",params:({params:e})=>i._`{unevaluatedProperty: ${e.unevaluatedProperty}}`},code(e){const{gen:t,schema:n,data:r,errsCount:a,it:l}=e;if(!a)throw new Error("ajv implementation error");const{allErrors:c,props:u}=l;function h(s){if(!1===n)return e.setParams({unevaluatedProperty:s}),e.error(),void(c||t.break());if(!(0,o.alwaysValidSchema)(l,n)){const n=t.name("valid");e.subschema({keyword:"unevaluatedProperties",dataProp:s,dataPropType:o.Type.Str},n),c||t.if((0,i.not)(n),()=>t.break())}}u instanceof i.Name?t.if(i._`${u} !== true`,()=>t.forIn("key",r,e=>t.if(function(e,t){return i._`!${e} || !${e}[${t}]`}(u,e),()=>h(e)))):!0!==u&&t.forIn("key",r,e=>void 0===u?h(e):t.if(function(e,t){const n=[];for(const o in e)!0===e[o]&&n.push(i._`${t} !== ${o}`);return(0,i.and)(...n)}(u,e),()=>h(e))),l.props=!0,e.ok(i._`${a} === ${s.default.errors}`)}};t.default=r},7935(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(4227),s=n(6250),r={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>i._`{allowedValue: ${e}}`},code(e){const{gen:t,data:n,$data:r,schemaCode:a,schema:l}=e;r||l&&"object"==typeof l?e.fail$data(i._`!${(0,o.useFunc)(t,s.default)}(${n}, ${a})`):e.fail(i._`${l} !== ${n}`)}};t.default=r},1846(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(3025),o={keyword:"dependentRequired",type:"object",schemaType:"object",error:i.error,code:e=>(0,i.validatePropertyDeps)(e)};t.default=o},8643(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(4227),s=n(6250),r={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>i._`{allowedValues: ${e}}`},code(e){const{gen:t,data:n,$data:r,schema:a,schemaCode:l,it:c}=e;if(!r&&0===a.length)throw new Error("enum must have non-empty array");const u=a.length>=c.opts.loopEnum;let h;const d=()=>null!=h?h:h=(0,o.useFunc)(t,s.default);let m;if(u||r)m=t.let("valid"),e.block$data(m,function(){t.assign(m,!1),t.forOf("v",l,e=>t.if(i._`${d()}(${n}, ${e})`,()=>t.assign(m,!0).break()))});else{if(!Array.isArray(a))throw new Error("ajv implementation error");const e=t.const("vSchema",l);m=(0,i.or)(...a.map((t,o)=>function(e,t){const o=a[t];return"object"==typeof o&&null!==o?i._`${d()}(${n}, ${e}[${t}])`:i._`${n} === ${o}`}(e,o)))}e.pass(m)}};t.default=r},7060(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(5882),o=n(3439),s=n(7307),r=n(422),a=n(4486),l=n(4003),c=n(1163),u=n(617),h=n(7935),d=n(8643),m=[i.default,o.default,s.default,r.default,a.default,l.default,c.default,u.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},h.default,d.default];t.default=m},2626(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(4227),o={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:n}){void 0===t.contains&&(0,i.checkStrictMode)(n,`"${e}" without "contains" is ignored`)}};t.default=o},1163(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n="maxItems"===e?"more":"fewer";return i.str`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>i._`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:o}=e,s="maxItems"===t?i.operators.GT:i.operators.LT;e.fail$data(i._`${n}.length ${s} ${o}`)}};t.default=o},7307(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=n(4227),s=n(3853),r={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n="maxLength"===e?"more":"fewer";return i.str`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>i._`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:r,it:a}=e,l="maxLength"===t?i.operators.GT:i.operators.LT,c=!1===a.opts.unicode?i._`${n}.length`:i._`${(0,o.useFunc)(e.gen,s.default)}(${n})`;e.fail$data(i._`${c} ${l} ${r}`)}};t.default=r},5882(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o=i.operators,s={maximum:{okStr:"<=",ok:o.LTE,fail:o.GT},minimum:{okStr:">=",ok:o.GTE,fail:o.LT},exclusiveMaximum:{okStr:"<",ok:o.LT,fail:o.GTE},exclusiveMinimum:{okStr:">",ok:o.GT,fail:o.LTE}},r={message:({keyword:e,schemaCode:t})=>i.str`must be ${s[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>i._`{comparison: ${s[e].okStr}, limit: ${t}}`},a={keyword:Object.keys(s),type:"number",schemaType:"number",$data:!0,error:r,code(e){const{keyword:t,data:n,schemaCode:o}=e;e.fail$data(i._`${n} ${s[t].fail} ${o} || isNaN(${n})`)}};t.default=a},4486(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n="maxProperties"===e?"more":"fewer";return i.str`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>i._`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:o}=e,s="maxProperties"===t?i.operators.GT:i.operators.LT;e.fail$data(i._`Object.keys(${n}).length ${s} ${o}`)}};t.default=o},3439(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(9029),o={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>i.str`must be multiple of ${e}`,params:({schemaCode:e})=>i._`{multipleOf: ${e}}`},code(e){const{gen:t,data:n,schemaCode:o,it:s}=e,r=s.opts.multipleOfPrecision,a=t.let("res"),l=r?i._`Math.abs(Math.round(${a}) - ${a}) > 1e-${r}`:i._`${a} !== parseInt(${a})`;e.fail$data(i._`(${o} === 0 || (${a} = ${n}/${o}, ${l}))`)}};t.default=o},422(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(5765),o=n(9029),s={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>o.str`must match pattern "${e}"`,params:({schemaCode:e})=>o._`{pattern: ${e}}`},code(e){const{data:t,$data:n,schema:s,schemaCode:r,it:a}=e,l=a.opts.unicodeRegExp?"u":"",c=n?o._`(new RegExp(${r}, ${l}))`:(0,i.usePattern)(e,s);e.fail$data(o._`!${c}.test(${t})`)}};t.default=s},4003(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(5765),o=n(9029),s=n(4227),r={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>o.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>o._`{missingProperty: ${e}}`},code(e){const{gen:t,schema:n,schemaCode:r,data:a,$data:l,it:c}=e,{opts:u}=c;if(!l&&0===n.length)return;const h=n.length>=u.loopRequired;if(c.allErrors?function(){if(h||l)e.block$data(o.nil,d);else for(const t of n)(0,i.checkReportMissingProp)(e,t)}():function(){const s=t.let("missing");if(h||l){const n=t.let("valid",!0);e.block$data(n,()=>function(n,s){e.setParams({missingProperty:n}),t.forOf(n,r,()=>{t.assign(s,(0,i.propertyInData)(t,a,n,u.ownProperties)),t.if((0,o.not)(s),()=>{e.error(),t.break()})},o.nil)}(s,n)),e.ok(n)}else t.if((0,i.checkMissingProp)(e,n,s)),(0,i.reportMissingProp)(e,s),t.else()}(),u.strictRequired){const t=e.parentSchema.properties,{definedProperties:i}=e.it;for(const e of n)if(void 0===(null==t?void 0:t[e])&&!i.has(e)){const t=`required property "${e}" is not defined at "${c.schemaEnv.baseId+c.errSchemaPath}" (strictRequired)`;(0,s.checkStrictMode)(c,t,c.opts.strictRequired)}}function d(){t.forOf("prop",r,n=>{e.setParams({missingProperty:n}),t.if((0,i.noPropertyInData)(t,a,n,u.ownProperties),()=>e.error())})}}};t.default=r},617(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const i=n(208),o=n(9029),s=n(4227),r=n(6250),a={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>o.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>o._`{i: ${e}, j: ${t}}`},code(e){const{gen:t,data:n,$data:a,schema:l,parentSchema:c,schemaCode:u,it:h}=e;if(!a&&!l)return;const d=t.let("valid"),m=c.items?(0,i.getSchemaTypes)(c.items):[];function p(s,r){const a=t.name("item"),l=(0,i.checkDataTypes)(m,a,h.opts.strictNumbers,i.DataType.Wrong),c=t.const("indices",o._`{}`);t.for(o._`;${s}--;`,()=>{t.let(a,o._`${n}[${s}]`),t.if(l,o._`continue`),m.length>1&&t.if(o._`typeof ${a} == "string"`,o._`${a} += "_"`),t.if(o._`typeof ${c}[${a}] == "number"`,()=>{t.assign(r,o._`${c}[${a}]`),e.error(),t.assign(d,!1).break()}).code(o._`${c}[${a}] = ${s}`)})}function g(i,a){const l=(0,s.useFunc)(t,r.default),c=t.name("outer");t.label(c).for(o._`;${i}--;`,()=>t.for(o._`${a} = ${i}; ${a}--;`,()=>t.if(o._`${l}(${n}[${i}], ${n}[${a}])`,()=>{e.error(),t.assign(d,!1).break(c)})))}e.block$data(d,function(){const i=t.let("i",o._`${n}.length`),s=t.let("j");e.setParams({i,j:s}),t.assign(d,!0),t.if(o._`${i} > 1`,()=>(m.length>0&&!m.some(e=>"object"===e||"array"===e)?p:g)(i,s))},o._`${u} === false`),e.ok(d)}};t.default=a},5488(e,t,n){"use strict";n.d(t,{A:()=>a});var i=n(1354),o=n.n(i),s=n(6314),r=n.n(s)()(o());r.push([e.id,"\n.ui-form.ui-tooltip .ui-input-root > label.ui-input-label:not(:empty) {\n /* min-width: 30px; /* Breaks right margin /**/\n}\n\n.ui-form.ui-tooltip .ui-input-root > div.ui-input-text:not(:empty) {\n margin-top: 6px;\n}","",{version:3,sources:["webpack://./css/cell-renderer.css"],names:[],mappings:";AACA;IACI,8CAA8C;AAClD;;AAEA;IACI,eAAe;AACnB",sourcesContent:["\n.ui-form.ui-tooltip .ui-input-root > label.ui-input-label:not(:empty) {\n /* min-width: 30px; /* Breaks right margin /**/\n}\n\n.ui-form.ui-tooltip .ui-input-root > div.ui-input-text:not(:empty) {\n margin-top: 6px;\n}"],sourceRoot:""}]);const a=r},5999(e,t,n){"use strict";n.d(t,{A:()=>a});var i=n(1354),o=n.n(i),s=n(6314),r=n.n(s)()(o());r.push([e.id,".macromolecule-cell-comp-analysis-host{\n max-height: 250px;\n overflow-y: scroll;\n}\n\n.macromolecule-cell-comp-analysis-bar{\n height: inherit;\n display: block;\n margin-top: 1.5px;\n margin-bottom: 1.5px;\n margin-right: 3px;\n}\n\n.macromolecule-cell-comp-analysis-value{\n display: flex;\n}","",{version:3,sources:["webpack://./css/composition-analysis.css"],names:[],mappings:"AAAA;IACI,iBAAiB;IACjB,kBAAkB;AACtB;;AAEA;IACI,eAAe;IACf,cAAc;IACd,iBAAiB;IACjB,oBAAoB;IACpB,iBAAiB;AACrB;;AAEA;IACI,aAAa;AACjB",sourcesContent:[".macromolecule-cell-comp-analysis-host{\n max-height: 250px;\n overflow-y: scroll;\n}\n\n.macromolecule-cell-comp-analysis-bar{\n height: inherit;\n display: block;\n margin-top: 1.5px;\n margin-bottom: 1.5px;\n margin-right: 3px;\n}\n\n.macromolecule-cell-comp-analysis-value{\n display: flex;\n}"],sourceRoot:""}]);const a=r},6520(e,t,n){"use strict";n.d(t,{A:()=>a});var i=n(1354),o=n.n(i),s=n(6314),r=n.n(s)()(o());r.push([e.id,".monomer-collections-view {\n padding: 16px;\n overflow-y: auto;\n height: 100%;\n}\n\n.monomer-collections-grid {\n display: flex;\n flex-wrap: wrap;\n gap: 16px;\n align-content: flex-start;\n}\n\n.monomer-collection-card {\n width: 20%;\n min-width: 240px;\n height: 300px;\n border: 1px solid var(--grey-2);\n border-radius: 8px;\n background: var(--white);\n display: flex;\n flex-direction: column;\n overflow: hidden;\n transition: box-shadow 0.2s ease;\n}\n\n.monomer-collection-card:hover {\n box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12);\n}\n\n.monomer-collection-card-selected {\n border-color: #ff8c00;\n box-shadow: 0 0 0 1px #ff8c00;\n}\n\n.monomer-collection-card-selected:hover {\n box-shadow: 0 0 0 1px #ff8c00, 0 2px 12px rgba(0, 0, 0, 0.12);\n}\n\n.monomer-collection-card-header {\n padding: 12px 14px 8px 14px;\n border-bottom: 1px solid var(--grey-2);\n flex-shrink: 0;\n}\n\n.monomer-collection-card-title {\n font-size: 14px;\n font-weight: 600;\n color: var(--grey-6);\n margin: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n.monomer-collection-card-description {\n font-size: 11px;\n color: var(--grey-4);\n margin: 4px 0 0 0;\n overflow: hidden;\n text-overflow: ellipsis;\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n}\n\n.monomer-collection-card-tags {\n display: flex;\n flex-wrap: wrap;\n gap: 3px;\n margin: 4px 0 0 0;\n}\n\n.monomer-collection-card-tag {\n display: inline-block;\n padding: 1px 6px;\n border-radius: 3px;\n background: #e8f0fe;\n border: 1px solid var(--blue-2, #aecbfa);\n font-size: 10px;\n color: var(--blue-3, #4285f4);\n}\n\n.monomer-collection-card-meta {\n font-size: 10px;\n color: var(--grey-3);\n margin: 4px 0 0 0;\n}\n\n.monomer-collections-search {\n margin-bottom: 12px;\n}\n\n.monomer-collections-search input {\n width: 100%;\n max-width: 400px;\n}\n\n.monomer-collection-card-body {\n flex: 1;\n overflow-y: auto;\n padding: 10px 14px;\n min-height: 0;\n}\n\n.monomer-collection-card-actions {\n padding: 0px 14px;\n border-top: 1px solid var(--grey-2);\n display: flex;\n gap: 8px;\n justify-content: flex-end;\n flex-shrink: 0;\n}\n\n.monomer-collection-card-actions .ui-btn {\n font-size: 11px;\n padding: 2px 10px;\n margin: 0;\n}\n\n.monomer-collection-tags {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n}\n\n.monomer-collection-tag {\n display: inline-block;\n padding: 2px 8px;\n border-radius: 4px;\n background: var(--grey-1);\n border: 1px solid var(--grey-2);\n font-size: 11px;\n color: var(--grey-5);\n cursor: pointer;\n transition: background 0.15s ease;\n}\n\n.monomer-collection-tag:hover {\n background: var(--blue-1, #e8f0fe);\n border-color: var(--blue-2, #aecbfa);\n}\n\n.monomer-collection-add-card {\n width: 20%;\n min-width: 240px;\n height: 300px;\n border: 2px dashed var(--grey-3);\n border-radius: 8px;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n transition: border-color 0.2s ease, background 0.2s ease;\n}\n\n.monomer-collection-add-card:hover {\n border-color: var(--blue-2, #aecbfa);\n background: var(--blue-1, #e8f0fe);\n}\n\n.monomer-collection-add-card-content {\n text-align: center;\n color: var(--grey-4);\n}\n\n.monomer-collection-add-card-content .grok-icon {\n font-size: 32px;\n margin-bottom: 8px;\n}\n\n.monomer-collection-add-card-content span {\n display: block;\n font-size: 13px;\n}\n\n.monomer-collections-load-more {\n width: 100%;\n display: flex;\n justify-content: center;\n padding: 16px 0;\n}\n\n.monomer-collections-load-more .ui-btn {\n min-width: 200px;\n}\n\n.monomer-collection-empty-state {\n width: 100%;\n text-align: center;\n padding: 60px 20px;\n color: var(--grey-4);\n font-size: 14px;\n}\n","",{version:3,sources:["webpack://./css/monomer-collections.css"],names:[],mappings:"AAAA;EACE,aAAa;EACb,gBAAgB;EAChB,YAAY;AACd;;AAEA;EACE,aAAa;EACb,eAAe;EACf,SAAS;EACT,yBAAyB;AAC3B;;AAEA;EACE,UAAU;EACV,gBAAgB;EAChB,aAAa;EACb,+BAA+B;EAC/B,kBAAkB;EAClB,wBAAwB;EACxB,aAAa;EACb,sBAAsB;EACtB,gBAAgB;EAChB,gCAAgC;AAClC;;AAEA;EACE,0CAA0C;AAC5C;;AAEA;EACE,qBAAqB;EACrB,6BAA6B;AAC/B;;AAEA;EACE,6DAA6D;AAC/D;;AAEA;EACE,2BAA2B;EAC3B,sCAAsC;EACtC,cAAc;AAChB;;AAEA;EACE,eAAe;EACf,gBAAgB;EAChB,oBAAoB;EACpB,SAAS;EACT,gBAAgB;EAChB,uBAAuB;EACvB,mBAAmB;AACrB;;AAEA;EACE,eAAe;EACf,oBAAoB;EACpB,iBAAiB;EACjB,gBAAgB;EAChB,uBAAuB;EACvB,oBAAoB;EACpB,qBAAqB;EACrB,4BAA4B;AAC9B;;AAEA;EACE,aAAa;EACb,eAAe;EACf,QAAQ;EACR,iBAAiB;AACnB;;AAEA;EACE,qBAAqB;EACrB,gBAAgB;EAChB,kBAAkB;EAClB,mBAAmB;EACnB,wCAAwC;EACxC,eAAe;EACf,6BAA6B;AAC/B;;AAEA;EACE,eAAe;EACf,oBAAoB;EACpB,iBAAiB;AACnB;;AAEA;EACE,mBAAmB;AACrB;;AAEA;EACE,WAAW;EACX,gBAAgB;AAClB;;AAEA;EACE,OAAO;EACP,gBAAgB;EAChB,kBAAkB;EAClB,aAAa;AACf;;AAEA;EACE,iBAAiB;EACjB,mCAAmC;EACnC,aAAa;EACb,QAAQ;EACR,yBAAyB;EACzB,cAAc;AAChB;;AAEA;EACE,eAAe;EACf,iBAAiB;EACjB,SAAS;AACX;;AAEA;EACE,aAAa;EACb,eAAe;EACf,QAAQ;AACV;;AAEA;EACE,qBAAqB;EACrB,gBAAgB;EAChB,kBAAkB;EAClB,yBAAyB;EACzB,+BAA+B;EAC/B,eAAe;EACf,oBAAoB;EACpB,eAAe;EACf,iCAAiC;AACnC;;AAEA;EACE,kCAAkC;EAClC,oCAAoC;AACtC;;AAEA;EACE,UAAU;EACV,gBAAgB;EAChB,aAAa;EACb,gCAAgC;EAChC,kBAAkB;EAClB,aAAa;EACb,mBAAmB;EACnB,uBAAuB;EACvB,eAAe;EACf,wDAAwD;AAC1D;;AAEA;EACE,oCAAoC;EACpC,kCAAkC;AACpC;;AAEA;EACE,kBAAkB;EAClB,oBAAoB;AACtB;;AAEA;EACE,eAAe;EACf,kBAAkB;AACpB;;AAEA;EACE,cAAc;EACd,eAAe;AACjB;;AAEA;EACE,WAAW;EACX,aAAa;EACb,uBAAuB;EACvB,eAAe;AACjB;;AAEA;EACE,gBAAgB;AAClB;;AAEA;EACE,WAAW;EACX,kBAAkB;EAClB,kBAAkB;EAClB,oBAAoB;EACpB,eAAe;AACjB",sourcesContent:[".monomer-collections-view {\n padding: 16px;\n overflow-y: auto;\n height: 100%;\n}\n\n.monomer-collections-grid {\n display: flex;\n flex-wrap: wrap;\n gap: 16px;\n align-content: flex-start;\n}\n\n.monomer-collection-card {\n width: 20%;\n min-width: 240px;\n height: 300px;\n border: 1px solid var(--grey-2);\n border-radius: 8px;\n background: var(--white);\n display: flex;\n flex-direction: column;\n overflow: hidden;\n transition: box-shadow 0.2s ease;\n}\n\n.monomer-collection-card:hover {\n box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12);\n}\n\n.monomer-collection-card-selected {\n border-color: #ff8c00;\n box-shadow: 0 0 0 1px #ff8c00;\n}\n\n.monomer-collection-card-selected:hover {\n box-shadow: 0 0 0 1px #ff8c00, 0 2px 12px rgba(0, 0, 0, 0.12);\n}\n\n.monomer-collection-card-header {\n padding: 12px 14px 8px 14px;\n border-bottom: 1px solid var(--grey-2);\n flex-shrink: 0;\n}\n\n.monomer-collection-card-title {\n font-size: 14px;\n font-weight: 600;\n color: var(--grey-6);\n margin: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n.monomer-collection-card-description {\n font-size: 11px;\n color: var(--grey-4);\n margin: 4px 0 0 0;\n overflow: hidden;\n text-overflow: ellipsis;\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n}\n\n.monomer-collection-card-tags {\n display: flex;\n flex-wrap: wrap;\n gap: 3px;\n margin: 4px 0 0 0;\n}\n\n.monomer-collection-card-tag {\n display: inline-block;\n padding: 1px 6px;\n border-radius: 3px;\n background: #e8f0fe;\n border: 1px solid var(--blue-2, #aecbfa);\n font-size: 10px;\n color: var(--blue-3, #4285f4);\n}\n\n.monomer-collection-card-meta {\n font-size: 10px;\n color: var(--grey-3);\n margin: 4px 0 0 0;\n}\n\n.monomer-collections-search {\n margin-bottom: 12px;\n}\n\n.monomer-collections-search input {\n width: 100%;\n max-width: 400px;\n}\n\n.monomer-collection-card-body {\n flex: 1;\n overflow-y: auto;\n padding: 10px 14px;\n min-height: 0;\n}\n\n.monomer-collection-card-actions {\n padding: 0px 14px;\n border-top: 1px solid var(--grey-2);\n display: flex;\n gap: 8px;\n justify-content: flex-end;\n flex-shrink: 0;\n}\n\n.monomer-collection-card-actions .ui-btn {\n font-size: 11px;\n padding: 2px 10px;\n margin: 0;\n}\n\n.monomer-collection-tags {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n}\n\n.monomer-collection-tag {\n display: inline-block;\n padding: 2px 8px;\n border-radius: 4px;\n background: var(--grey-1);\n border: 1px solid var(--grey-2);\n font-size: 11px;\n color: var(--grey-5);\n cursor: pointer;\n transition: background 0.15s ease;\n}\n\n.monomer-collection-tag:hover {\n background: var(--blue-1, #e8f0fe);\n border-color: var(--blue-2, #aecbfa);\n}\n\n.monomer-collection-add-card {\n width: 20%;\n min-width: 240px;\n height: 300px;\n border: 2px dashed var(--grey-3);\n border-radius: 8px;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n transition: border-color 0.2s ease, background 0.2s ease;\n}\n\n.monomer-collection-add-card:hover {\n border-color: var(--blue-2, #aecbfa);\n background: var(--blue-1, #e8f0fe);\n}\n\n.monomer-collection-add-card-content {\n text-align: center;\n color: var(--grey-4);\n}\n\n.monomer-collection-add-card-content .grok-icon {\n font-size: 32px;\n margin-bottom: 8px;\n}\n\n.monomer-collection-add-card-content span {\n display: block;\n font-size: 13px;\n}\n\n.monomer-collections-load-more {\n width: 100%;\n display: flex;\n justify-content: center;\n padding: 16px 0;\n}\n\n.monomer-collections-load-more .ui-btn {\n min-width: 200px;\n}\n\n.monomer-collection-empty-state {\n width: 100%;\n text-align: center;\n padding: 60px 20px;\n color: var(--grey-4);\n font-size: 14px;\n}\n"],sourceRoot:""}]);const a=r},857(e,t,n){"use strict";n.d(t,{A:()=>a});var i=n(1354),o=n.n(i),s=n(6314),r=n.n(s)()(o());r.push([e.id,".monomer-manager-root .grok-sketcher {\n min-width: unset !important;\n}\n\n.monomer-manager-root {\n width: 100% !important;\n height: 100% !important;\n}\n\n.monomer-manager-sketcher .ketcher-host {\n height: 100% !important;\n width: unset !important;\n} \n\n.monomer-manager-root > div:first-child {\n flex-basis: 40% !important;\n}\n.monomer-manager-root > div:nth-child(2) {\n flex-basis: 60% !important;\n}\n\n.monomer-manager-root > div:first-child > .ui-form {\n max-width: unset !important;\n}\n\n.monomer-card-info-row {\n width: 100%;\n overflow: hidden;\n text-overflow: ellipsis;\n margin-bottom: 10px;\n}\n\n.monomer-card-info-row > div:nth-child(2) {\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.monomer-card-info-row > div:nth-child(1) {\n font-weight: bold;\n margin-right: 5px;\n text-wrap: nowrap;\n}\n\n.duplicate-monomer-symbol-row {\n visibility: visible !important;\n}\n\n.monomer-card-root {\n border: 2px solid var(--grey-2);\n border-radius: 5px;\n padding: 5px;\n margin: 5px;\n overflow: hidden;\n align-items: center;\n cursor: pointer;\n width: 200px;\n height: 300px;\n min-width: 200px;\n min-height: 300px;\n}\n\n.duplicate-monomers-virtual-view {\n width: 100% !important;\n overflow-x: clip;\n overflow-y: auto;\n}\n\n.monomer-manager-form-tab-control input.d4-invalid {\n background: #ff000030;\n}\n\n.monomer-lib-controls-form .ui-input-root {\n flex-wrap: nowrap !important;\n}","",{version:3,sources:["webpack://./css/monomer-manager.css"],names:[],mappings:"AAAA;IACI,2BAA2B;AAC/B;;AAEA;IACI,sBAAsB;IACtB,uBAAuB;AAC3B;;AAEA;IACI,uBAAuB;IACvB,uBAAuB;AAC3B;;AAEA;IACI,0BAA0B;AAC9B;AACA;IACI,0BAA0B;AAC9B;;AAEA;IACI,2BAA2B;AAC/B;;AAEA;IACI,WAAW;IACX,gBAAgB;IAChB,uBAAuB;IACvB,mBAAmB;AACvB;;AAEA;IACI,mBAAmB;IACnB,gBAAgB;IAChB,uBAAuB;AAC3B;;AAEA;IACI,iBAAiB;IACjB,iBAAiB;IACjB,iBAAiB;AACrB;;AAEA;IACI,8BAA8B;AAClC;;AAEA;IACI,+BAA+B;IAC/B,kBAAkB;IAClB,YAAY;IACZ,WAAW;IACX,gBAAgB;IAChB,mBAAmB;IACnB,eAAe;IACf,YAAY;IACZ,aAAa;IACb,gBAAgB;IAChB,iBAAiB;AACrB;;AAEA;IACI,sBAAsB;IACtB,gBAAgB;IAChB,gBAAgB;AACpB;;AAEA;IACI,qBAAqB;AACzB;;AAEA;IACI,4BAA4B;AAChC",sourcesContent:[".monomer-manager-root .grok-sketcher {\n min-width: unset !important;\n}\n\n.monomer-manager-root {\n width: 100% !important;\n height: 100% !important;\n}\n\n.monomer-manager-sketcher .ketcher-host {\n height: 100% !important;\n width: unset !important;\n} \n\n.monomer-manager-root > div:first-child {\n flex-basis: 40% !important;\n}\n.monomer-manager-root > div:nth-child(2) {\n flex-basis: 60% !important;\n}\n\n.monomer-manager-root > div:first-child > .ui-form {\n max-width: unset !important;\n}\n\n.monomer-card-info-row {\n width: 100%;\n overflow: hidden;\n text-overflow: ellipsis;\n margin-bottom: 10px;\n}\n\n.monomer-card-info-row > div:nth-child(2) {\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.monomer-card-info-row > div:nth-child(1) {\n font-weight: bold;\n margin-right: 5px;\n text-wrap: nowrap;\n}\n\n.duplicate-monomer-symbol-row {\n visibility: visible !important;\n}\n\n.monomer-card-root {\n border: 2px solid var(--grey-2);\n border-radius: 5px;\n padding: 5px;\n margin: 5px;\n overflow: hidden;\n align-items: center;\n cursor: pointer;\n width: 200px;\n height: 300px;\n min-width: 200px;\n min-height: 300px;\n}\n\n.duplicate-monomers-virtual-view {\n width: 100% !important;\n overflow-x: clip;\n overflow-y: auto;\n}\n\n.monomer-manager-form-tab-control input.d4-invalid {\n background: #ff000030;\n}\n\n.monomer-lib-controls-form .ui-input-root {\n flex-wrap: nowrap !important;\n}"],sourceRoot:""}]);const a=r},6369(e,t,n){"use strict";n.d(t,{A:()=>a});var i=n(1354),o=n.n(i),s=n(6314),r=n.n(s)()(o());r.push([e.id,".kalign-version {\n margin-bottom: 0;\n text-align: end;\n font-size: 12px;\n opacity: 0.8;\n}\nbutton.msa-params-button.ui-btn {\n justify-content: end;\n}","",{version:3,sources:["webpack://./css/msa.css"],names:[],mappings:"AAAA;IACI,gBAAgB;IAChB,eAAe;IACf,eAAe;IACf,YAAY;AAChB;AACA;IACI,oBAAoB;AACxB",sourcesContent:[".kalign-version {\n margin-bottom: 0;\n text-align: end;\n font-size: 12px;\n opacity: 0.8;\n}\nbutton.msa-params-button.ui-btn {\n justify-content: end;\n}"],sourceRoot:""}]);const a=r},7939(e,t,n){"use strict";n.d(t,{A:()=>a});var i=n(1354),o=n.n(i),s=n(6314),r=n.n(s)()(o());r.push([e.id,".scatter_plot_link {\n right: 10px;\n}\n\n.cliffs_div {\n flex-grow: initial!important;\n justify-content: flex-end;\n flex-wrap: wrap;\n}\n\n.cliffs_grid {\n margin: 0!important;\n}\n\n.ml-dim-reduction-settings-input i.grok-icon.grok-font-icon-settings {\n font-size: 18px;\n position: absolute;\n height: 28px;\n}\n\n.ml-dim-reduction-settings-input i.grok-icon.grok-font-icon-settings:not(.ml-dim-reduction-column-editor-input-root i) {\n left: -20px;\n}\n.dlg-dimensionality-reduction.ui-form, .dlg-markov-clustering.ui-form, .dlg-markov-clustering.ui-form .ui-form, .dlg-dimensionality-reduction.ui-form .ui-form {\n max-width: unset;\n}\n\n.ml-dim-reduction-column-editor-input-root label {\n display: none !important;\n}\n\n.dim-reduction-dialog-form > .ui-input-root, .dim-reduction-dialog-form > div > .ui-input-root {\n margin-left: 10px;\n}\n\n.ml-dim-reduction-column-editor-input-root input, .ml-dim-reduction-column-editor-input-root select {\n margin-left: 20px !important;\n}\n\nh3.ml-dim-reduction-column-editor-input-root {\n margin: 0 !important;\n}\n\n.ml-dim-reduction-column-editor-root, .ml-dim-reduction-column-editor-header-root {\n display: flex;\n flex-direction: row;\n align-items: center;\n margin-bottom: 10px !important;\n width: 700px !important;\n}\n\n.ml-dim-reduction-column-editor-column-title {\n text-overflow: ellipsis;\n overflow: hidden;\n}\n\n.ml-dim-reduction-column-editor-header-root > h1:not(:first-child) {\n margin-left: 20px !important;\n}\n\n.ml-dim-reduction-column-editor-table-root .header > td:not(:first-child) {\n padding-left: 32px;\n}","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/ml/css/styles.css"],names:[],mappings:"AAAA;IACI,WAAW;AACf;;AAEA;IACI,4BAA4B;IAC5B,yBAAyB;IACzB,eAAe;AACnB;;AAEA;GACG,mBAAmB;AACtB;;AAEA;IACI,eAAe;IACf,kBAAkB;IAClB,YAAY;AAChB;;AAEA;IACI,WAAW;AACf;AACA;IACI,gBAAgB;AACpB;;AAEA;IACI,wBAAwB;AAC5B;;AAEA;IACI,iBAAiB;AACrB;;AAEA;IACI,4BAA4B;AAChC;;AAEA;IACI,oBAAoB;AACxB;;AAEA;IACI,aAAa;IACb,mBAAmB;IACnB,mBAAmB;IACnB,8BAA8B;IAC9B,uBAAuB;AAC3B;;AAEA;IACI,uBAAuB;IACvB,gBAAgB;AACpB;;AAEA;IACI,4BAA4B;AAChC;;AAEA;IACI,kBAAkB;AACtB",sourcesContent:[".scatter_plot_link {\n right: 10px;\n}\n\n.cliffs_div {\n flex-grow: initial!important;\n justify-content: flex-end;\n flex-wrap: wrap;\n}\n\n.cliffs_grid {\n margin: 0!important;\n}\n\n.ml-dim-reduction-settings-input i.grok-icon.grok-font-icon-settings {\n font-size: 18px;\n position: absolute;\n height: 28px;\n}\n\n.ml-dim-reduction-settings-input i.grok-icon.grok-font-icon-settings:not(.ml-dim-reduction-column-editor-input-root i) {\n left: -20px;\n}\n.dlg-dimensionality-reduction.ui-form, .dlg-markov-clustering.ui-form, .dlg-markov-clustering.ui-form .ui-form, .dlg-dimensionality-reduction.ui-form .ui-form {\n max-width: unset;\n}\n\n.ml-dim-reduction-column-editor-input-root label {\n display: none !important;\n}\n\n.dim-reduction-dialog-form > .ui-input-root, .dim-reduction-dialog-form > div > .ui-input-root {\n margin-left: 10px;\n}\n\n.ml-dim-reduction-column-editor-input-root input, .ml-dim-reduction-column-editor-input-root select {\n margin-left: 20px !important;\n}\n\nh3.ml-dim-reduction-column-editor-input-root {\n margin: 0 !important;\n}\n\n.ml-dim-reduction-column-editor-root, .ml-dim-reduction-column-editor-header-root {\n display: flex;\n flex-direction: row;\n align-items: center;\n margin-bottom: 10px !important;\n width: 700px !important;\n}\n\n.ml-dim-reduction-column-editor-column-title {\n text-overflow: ellipsis;\n overflow: hidden;\n}\n\n.ml-dim-reduction-column-editor-header-root > h1:not(:first-child) {\n margin-left: 20px !important;\n}\n\n.ml-dim-reduction-column-editor-table-root .header > td:not(:first-child) {\n padding-left: 32px;\n}"],sourceRoot:""}]);const a=r},3017(e,t,n){"use strict";n.d(t,{A:()=>a});var i=n(1354),o=n.n(i),s=n(6314),r=n.n(s)()(o());r.push([e.id,".monomer-lib-controls-form {\n margin-left: auto;\n margin-right: auto;\n display: flex;\n flex-direction: column;\n align-items: center;\n min-width: 220px;\n width: 100%;\n\n}\n","",{version:3,sources:["webpack://./src/utils/monomer-lib/library-file-manager/style.css"],names:[],mappings:"AAAA;EACE,iBAAiB;EACjB,kBAAkB;EAClB,aAAa;EACb,sBAAsB;EACtB,mBAAmB;EACnB,gBAAgB;EAChB,WAAW;;AAEb",sourcesContent:[".monomer-lib-controls-form {\n margin-left: auto;\n margin-right: auto;\n display: flex;\n flex-direction: column;\n align-items: center;\n min-width: 220px;\n width: 100%;\n\n}\n"],sourceRoot:""}]);const a=r},6314(e){"use strict";e.exports=function(e){var t=[];return t.toString=function(){return this.map(function(t){var n="",i=void 0!==t[5];return t[4]&&(n+="@supports (".concat(t[4],") {")),t[2]&&(n+="@media ".concat(t[2]," {")),i&&(n+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),n+=e(t),i&&(n+="}"),t[2]&&(n+="}"),t[4]&&(n+="}"),n}).join("")},t.i=function(e,n,i,o,s){"string"==typeof e&&(e=[[null,e,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 c=0;c<e.length;c++){var u=[].concat(e[c]);i&&r[u[0]]||(void 0!==s&&(void 0===u[5]||(u[1]="@layer".concat(u[5].length>0?" ".concat(u[5]):""," {").concat(u[1],"}")),u[5]=s),n&&(u[2]?(u[1]="@media ".concat(u[2]," {").concat(u[1],"}"),u[2]=n):u[2]=n),o&&(u[4]?(u[1]="@supports (".concat(u[4],") {").concat(u[1],"}"),u[4]=o):u[4]="".concat(o)),t.push(u))}},t}},1354(e){"use strict";e.exports=function(e){var t=e[1],n=e[3];if(!n)return t;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[t].concat([s]).join("\n")}return[t].join("\n")}},2017(e){"use strict";e.exports=function e(t,n){if(t===n)return!0;if(t&&n&&"object"==typeof t&&"object"==typeof n){if(t.constructor!==n.constructor)return!1;var i,o,s;if(Array.isArray(t)){if((i=t.length)!=n.length)return!1;for(o=i;0!==o--;)if(!e(t[o],n[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if((i=(s=Object.keys(t)).length)!==Object.keys(n).length)return!1;for(o=i;0!==o--;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=i;0!==o--;){var r=s[o];if(!e(t[r],n[r]))return!1}return!0}return t!=t&&n!=n}},9982(e,t,n){var i;!function(){var t={};!function(e){"use strict";e.__esModule=!0,e.digestLength=32,e.blockSize=64;var t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function n(e,n,i,o,s){for(var r,a,l,c,u,h,d,m,p,g,f,y,b;s>=64;){for(r=n[0],a=n[1],l=n[2],c=n[3],u=n[4],h=n[5],d=n[6],m=n[7],g=0;g<16;g++)f=o+4*g,e[g]=(255&i[f])<<24|(255&i[f+1])<<16|(255&i[f+2])<<8|255&i[f+3];for(g=16;g<64;g++)y=((p=e[g-2])>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,b=((p=e[g-15])>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,e[g]=(y+e[g-7]|0)+(b+e[g-16]|0);for(g=0;g<64;g++)y=(((u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7))+(u&h^~u&d)|0)+(m+(t[g]+e[g]|0)|0)|0,b=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&a^r&l^a&l)|0,m=d,d=h,h=u,u=c+y|0,c=l,l=a,a=r,r=y+b|0;n[0]+=r,n[1]+=a,n[2]+=l,n[3]+=c,n[4]+=u,n[5]+=h,n[6]+=d,n[7]+=m,o+=64,s-=64}return o}var i=function(){function t(){this.digestLength=e.digestLength,this.blockSize=e.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return t.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},t.prototype.clean=function(){for(var e=0;e<this.buffer.length;e++)this.buffer[e]=0;for(e=0;e<this.temp.length;e++)this.temp[e]=0;this.reset()},t.prototype.update=function(e,t){if(void 0===t&&(t=e.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var i=0;if(this.bytesHashed+=t,this.bufferLength>0){for(;this.bufferLength<64&&t>0;)this.buffer[this.bufferLength++]=e[i++],t--;64===this.bufferLength&&(n(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(t>=64&&(i=n(this.temp,this.state,e,i,t),t%=64);t>0;)this.buffer[this.bufferLength++]=e[i++],t--;return this},t.prototype.finish=function(e){if(!this.finished){var t=this.bytesHashed,i=this.bufferLength,o=t/536870912|0,s=t<<3,r=t%64<56?64:128;this.buffer[i]=128;for(var a=i+1;a<r-8;a++)this.buffer[a]=0;this.buffer[r-8]=o>>>24&255,this.buffer[r-7]=o>>>16&255,this.buffer[r-6]=o>>>8&255,this.buffer[r-5]=o>>>0&255,this.buffer[r-4]=s>>>24&255,this.buffer[r-3]=s>>>16&255,this.buffer[r-2]=s>>>8&255,this.buffer[r-1]=s>>>0&255,n(this.temp,this.state,this.buffer,0,r),this.finished=!0}for(a=0;a<8;a++)e[4*a+0]=this.state[a]>>>24&255,e[4*a+1]=this.state[a]>>>16&255,e[4*a+2]=this.state[a]>>>8&255,e[4*a+3]=this.state[a]>>>0&255;return this},t.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},t.prototype._saveState=function(e){for(var t=0;t<this.state.length;t++)e[t]=this.state[t]},t.prototype._restoreState=function(e,t){for(var n=0;n<this.state.length;n++)this.state[n]=e[n];this.bytesHashed=t,this.finished=!1,this.bufferLength=0},t}();e.Hash=i;var o=function(){function e(e){this.inner=new i,this.outer=new i,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var t=new Uint8Array(this.blockSize);if(e.length>this.blockSize)(new i).update(e).finish(t).clean();else for(var n=0;n<e.length;n++)t[n]=e[n];for(n=0;n<t.length;n++)t[n]^=54;for(this.inner.update(t),n=0;n<t.length;n++)t[n]^=106;for(this.outer.update(t),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate),n=0;n<t.length;n++)t[n]=0}return e.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},e.prototype.clean=function(){for(var e=0;e<this.istate.length;e++)this.ostate[e]=this.istate[e]=0;this.inner.clean(),this.outer.clean()},e.prototype.update=function(e){return this.inner.update(e),this},e.prototype.finish=function(e){return this.outer.finished?this.outer.finish(e):(this.inner.finish(e),this.outer.update(e,this.digestLength).finish(e)),this},e.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},e}();function s(e){var t=(new i).update(e),n=t.digest();return t.clean(),n}function r(e,t){var n=new o(e).update(t),i=n.digest();return n.clean(),i}function a(e,t,n,i){var o=i[0];if(0===o)throw new Error("hkdf: cannot expand more");t.reset(),o>1&&t.update(e),n&&t.update(n),t.update(i),t.finish(e),i[0]++}e.HMAC=o,e.hash=s,e.default=s,e.hmac=r;var l=new Uint8Array(e.digestLength);e.hkdf=function(e,t,n,i){void 0===t&&(t=l),void 0===i&&(i=32);for(var s=new Uint8Array([1]),c=r(t,e),u=new o(c),h=new Uint8Array(u.digestLength),d=h.length,m=new Uint8Array(i),p=0;p<i;p++)d===h.length&&(a(h,u,n,s),d=0),m[p]=h[d++];return u.clean(),h.fill(0),s.fill(0),m},e.pbkdf2=function(e,t,n,i){for(var s=new o(e),r=s.digestLength,a=new Uint8Array(4),l=new Uint8Array(r),c=new Uint8Array(r),u=new Uint8Array(i),h=0;h*r<i;h++){var d=h+1;a[0]=d>>>24&255,a[1]=d>>>16&255,a[2]=d>>>8&255,a[3]=d>>>0&255,s.reset(),s.update(t),s.update(a),s.finish(c);for(var m=0;m<r;m++)l[m]=c[m];for(m=2;m<=n;m++){s.reset(),s.update(c).finish(c);for(var p=0;p<r;p++)l[p]^=c[p]}for(m=0;m<r&&h*r+m<i;m++)u[h*r+m]=l[m]}for(h=0;h<r;h++)l[h]=c[h]=0;for(h=0;h<4;h++)a[h]=0;return s.clean(),u}}(t);var o=t.default;for(var s in t)o[s]=t[s];"object"==typeof e.exports?e.exports=o:void 0===(i=function(){return o}.call(t,n,t,e))||(e.exports=i)}()},2787(e,t,n){"use strict";n.d(t,{I:()=>o});const i=new Uint32Array(65536),o=(e,t)=>{if(e.length<t.length){const n=t;t=e,e=n}return 0===t.length?e.length:e.length<=32?((e,t)=>{const n=e.length,o=t.length,s=1<<n-1;let r=-1,a=0,l=n,c=n;for(;c--;)i[e.charCodeAt(c)]|=1<<c;for(c=0;c<o;c++){let e=i[t.charCodeAt(c)];const n=e|a;e|=(e&r)+r^r,a|=~(e|r),r&=e,a&s&&l++,r&s&&l--,a=a<<1|1,r=r<<1|~(n|a),a&=n}for(c=n;c--;)i[e.charCodeAt(c)]=0;return l})(e,t):((e,t)=>{const n=t.length,o=e.length,s=[],r=[],a=Math.ceil(n/32),l=Math.ceil(o/32);for(let e=0;e<a;e++)r[e]=-1,s[e]=0;let c=0;for(;c<l-1;c++){let a=0,l=-1;const u=32*c,h=Math.min(32,o)+u;for(let t=u;t<h;t++)i[e.charCodeAt(t)]|=1<<t;for(let e=0;e<n;e++){const n=i[t.charCodeAt(e)],o=r[e/32|0]>>>e&1,c=s[e/32|0]>>>e&1,u=n|a,h=((n|c)&l)+l^l|n|c;let d=a|~(h|l),m=l&h;d>>>31^o&&(r[e/32|0]^=1<<e),m>>>31^c&&(s[e/32|0]^=1<<e),d=d<<1|o,m=m<<1|c,l=m|~(u|d),a=d&u}for(let t=u;t<h;t++)i[e.charCodeAt(t)]=0}let u=0,h=-1;const d=32*c,m=Math.min(32,o-d)+d;for(let t=d;t<m;t++)i[e.charCodeAt(t)]|=1<<t;let p=o;for(let e=0;e<n;e++){const n=i[t.charCodeAt(e)],a=r[e/32|0]>>>e&1,l=s[e/32|0]>>>e&1,c=n|u,d=((n|l)&h)+h^h|n|l;let m=u|~(d|h),g=h&d;p+=m>>>o-1&1,p-=g>>>o-1&1,m>>>31^a&&(r[e/32|0]^=1<<e),g>>>31^l&&(s[e/32|0]^=1<<e),m=m<<1|a,g=g<<1|l,h=g|~(c|m),u=m&c}for(let t=d;t<m;t++)i[e.charCodeAt(t)]=0;return p})(e,t)}},9937(e){e.exports={linLogMode:!1,outboundAttractionDistribution:!1,adjustSizes:!1,edgeWeightInfluence:1,scalingRatio:1,strongGravityMode:!1,gravity:1,slowDown:1,barnesHutOptimize:!1,barnesHutTheta:.5}},1782(e,t){t.assign=function(e){e=e||{};var t,n,i,o=Array.prototype.slice.call(arguments).slice(1);for(t=0,i=o.length;t<i;t++)if(o[t])for(n in o[t])e[n]=o[t][n];return e},t.validateSettings=function(e){return"linLogMode"in e&&"boolean"!=typeof e.linLogMode?{message:"the `linLogMode` setting should be a boolean."}:"outboundAttractionDistribution"in e&&"boolean"!=typeof e.outboundAttractionDistribution?{message:"the `outboundAttractionDistribution` setting should be a boolean."}:"adjustSizes"in e&&"boolean"!=typeof e.adjustSizes?{message:"the `adjustSizes` setting should be a boolean."}:"edgeWeightInfluence"in e&&"number"!=typeof e.edgeWeightInfluence?{message:"the `edgeWeightInfluence` setting should be a number."}:!("scalingRatio"in e)||"number"==typeof e.scalingRatio&&e.scalingRatio>=0?"strongGravityMode"in e&&"boolean"!=typeof e.strongGravityMode?{message:"the `strongGravityMode` setting should be a boolean."}:!("gravity"in e)||"number"==typeof e.gravity&&e.gravity>=0?"slowDown"in e&&!("number"==typeof e.slowDown||e.slowDown>=0)?{message:"the `slowDown` setting should be a number >= 0."}:"barnesHutOptimize"in e&&"boolean"!=typeof e.barnesHutOptimize?{message:"the `barnesHutOptimize` setting should be a boolean."}:!("barnesHutTheta"in e)||"number"==typeof e.barnesHutTheta&&e.barnesHutTheta>=0?null:{message:"the `barnesHutTheta` setting should be a number >= 0."}:{message:"the `gravity` setting should be a number >= 0."}:{message:"the `scalingRatio` setting should be a number >= 0."}},t.graphToByteArrays=function(e,t){var n,i=e.order,o=e.size,s={},r=new Float32Array(10*i),a=new Float32Array(3*o);return n=0,e.forEachNode(function(e,t){s[e]=n,r[n]=t.x,r[n+1]=t.y,r[n+2]=0,r[n+3]=0,r[n+4]=0,r[n+5]=0,r[n+6]=1,r[n+7]=1,r[n+8]=t.size||1,r[n+9]=t.fixed?1:0,n+=10}),n=0,e.forEachEdge(function(e,i,o,l,c,u,h){var d=s[o],m=s[l],p=t(e,i,o,l,c,u,h);r[d+6]+=p,r[m+6]+=p,a[n]=d,a[n+1]=m,a[n+2]=p,n+=3}),{nodes:r,edges:a}},t.assignLayoutChanges=function(e,t,n){var i=0;e.updateEachNodeAttributes(function(e,o){return o.x=t[i],o.y=t[i+1],i+=10,n?n(e,o):o})},t.readGraphPositions=function(e,t){var n=0;e.forEachNode(function(e,i){t[n]=i.x,t[n+1]=i.y,n+=10})},t.collectLayoutChanges=function(e,t,n){for(var i=e.nodes(),o={},s=0,r=0,a=t.length;s<a;s+=10){if(n){var l=Object.assign({},e.getNodeAttributes(i[r]));l.x=t[s],l.y=t[s+1],l=n(i[r],l),o[i[r]]={x:l.x,y:l.y}}else o[i[r]]={x:t[s],y:t[s+1]};r++}return o},t.createWorker=function(e){var t=window.URL||window.webkitURL,n=e.toString(),i=t.createObjectURL(new Blob(["("+n+").call(this);"],{type:"text/javascript"})),o=new Worker(i);return t.revokeObjectURL(i),o}},8903(e,t,n){var i=n(1736),o=n(8153).Fd,s=n(2561),r=n(1782),a=n(9937);function l(e,t,n){if(!i(t))throw new Error("graphology-layout-forceatlas2: the given graph is not a valid graphology instance.");"number"==typeof n&&(n={iterations:n});var l=n.iterations;if("number"!=typeof l)throw new Error("graphology-layout-forceatlas2: invalid number of iterations.");if(l<=0)throw new Error("graphology-layout-forceatlas2: you should provide a positive number of iterations.");var c=o("getEdgeWeight"in n?n.getEdgeWeight:"weight").fromEntry,u="function"==typeof n.outputReducer?n.outputReducer:null,h=r.assign({},a,n.settings),d=r.validateSettings(h);if(d)throw new Error("graphology-layout-forceatlas2: "+d.message);var m,p=r.graphToByteArrays(t,c);for(m=0;m<l;m++)s(h,p.nodes,p.edges);if(!e)return r.collectLayoutChanges(t,p.nodes);r.assignLayoutChanges(t,p.nodes,u)}var c=l.bind(null,!1);c.assign=l.bind(null,!0),c.inferSettings=function(e){var t="number"==typeof e?e:e.order;return{barnesHutOptimize:t>2e3,strongGravityMode:!0,gravity:.05,scalingRatio:10,slowDown:1+Math.log(t)}},e.exports=c},2561(e){var t=10;e.exports=function(e,n,i){var o,s,r,a,l,c,u,h,d,m,p,g,f,y,b,w,v,C,A,T,E,S,M,x=n.length,P=i.length,L=e.adjustSizes,I=e.barnesHutTheta*e.barnesHutTheta,_=[];for(r=0;r<x;r+=t)n[r+4]=n[r+2],n[r+5]=n[r+3],n[r+2]=0,n[r+3]=0;if(e.outboundAttractionDistribution){for(p=0,r=0;r<x;r+=t)p+=n[r+6];p/=x/t}if(e.barnesHutOptimize){var N,R,$,O=1/0,H=-1/0,D=1/0,F=-1/0;for(r=0;r<x;r+=t)O=Math.min(O,n[r+0]),H=Math.max(H,n[r+0]),D=Math.min(D,n[r+1]),F=Math.max(F,n[r+1]);var k=H-O,G=F-D;for(k>G?F=(D-=(k-G)/2)+k:H=(O-=(G-k)/2)+G,_[0]=-1,_[1]=(O+H)/2,_[2]=(D+F)/2,_[3]=Math.max(H-O,F-D),_[4]=-1,_[5]=-1,_[6]=0,_[7]=0,_[8]=0,o=1,r=0;r<x;r+=t)for(s=0,$=3;;){if(!(_[s+5]>=0)){if(_[s+0]<0){_[s+0]=r;break}if(_[s+5]=9*o,h=_[s+3]/2,_[(d=_[s+5])+0]=-1,_[d+1]=_[s+1]-h,_[d+2]=_[s+2]-h,_[d+3]=h,_[d+4]=d+9,_[d+5]=-1,_[d+6]=0,_[d+7]=0,_[d+8]=0,_[(d+=9)+0]=-1,_[d+1]=_[s+1]-h,_[d+2]=_[s+2]+h,_[d+3]=h,_[d+4]=d+9,_[d+5]=-1,_[d+6]=0,_[d+7]=0,_[d+8]=0,_[(d+=9)+0]=-1,_[d+1]=_[s+1]+h,_[d+2]=_[s+2]-h,_[d+3]=h,_[d+4]=d+9,_[d+5]=-1,_[d+6]=0,_[d+7]=0,_[d+8]=0,_[(d+=9)+0]=-1,_[d+1]=_[s+1]+h,_[d+2]=_[s+2]+h,_[d+3]=h,_[d+4]=_[s+4],_[d+5]=-1,_[d+6]=0,_[d+7]=0,_[d+8]=0,o+=4,N=n[_[s+0]+0]<_[s+1]?n[_[s+0]+1]<_[s+2]?_[s+5]:_[s+5]+9:n[_[s+0]+1]<_[s+2]?_[s+5]+18:_[s+5]+27,_[s+6]=n[_[s+0]+6],_[s+7]=n[_[s+0]+0],_[s+8]=n[_[s+0]+1],_[N+0]=_[s+0],_[s+0]=-1,N===(R=n[r+0]<_[s+1]?n[r+1]<_[s+2]?_[s+5]:_[s+5]+9:n[r+1]<_[s+2]?_[s+5]+18:_[s+5]+27)){if($--){s=N;continue}$=3;break}_[R+0]=r;break}N=n[r+0]<_[s+1]?n[r+1]<_[s+2]?_[s+5]:_[s+5]+9:n[r+1]<_[s+2]?_[s+5]+18:_[s+5]+27,_[s+7]=(_[s+7]*_[s+6]+n[r+0]*n[r+6])/(_[s+6]+n[r+6]),_[s+8]=(_[s+8]*_[s+6]+n[r+1]*n[r+6])/(_[s+6]+n[r+6]),_[s+6]+=n[r+6],s=N}}if(e.barnesHutOptimize){for(g=e.scalingRatio,r=0;r<x;r+=t)for(s=0;;)if(_[s+5]>=0){if(w=Math.pow(n[r+0]-_[s+7],2)+Math.pow(n[r+1]-_[s+8],2),4*(m=_[s+3])*m/w<I){if(f=n[r+0]-_[s+7],y=n[r+1]-_[s+8],!0===L?w>0?(v=g*n[r+6]*_[s+6]/w,n[r+2]+=f*v,n[r+3]+=y*v):w<0&&(v=-g*n[r+6]*_[s+6]/Math.sqrt(w),n[r+2]+=f*v,n[r+3]+=y*v):w>0&&(v=g*n[r+6]*_[s+6]/w,n[r+2]+=f*v,n[r+3]+=y*v),(s=_[s+4])<0)break;continue}s=_[s+5]}else if((c=_[s+0])>=0&&c!==r&&(w=(f=n[r+0]-n[c+0])*f+(y=n[r+1]-n[c+1])*y,!0===L?w>0?(v=g*n[r+6]*n[c+6]/w,n[r+2]+=f*v,n[r+3]+=y*v):w<0&&(v=-g*n[r+6]*n[c+6]/Math.sqrt(w),n[r+2]+=f*v,n[r+3]+=y*v):w>0&&(v=g*n[r+6]*n[c+6]/w,n[r+2]+=f*v,n[r+3]+=y*v)),(s=_[s+4])<0)break}else for(g=e.scalingRatio,a=0;a<x;a+=t)for(l=0;l<a;l+=t)f=n[a+0]-n[l+0],y=n[a+1]-n[l+1],!0===L?(w=Math.sqrt(f*f+y*y)-n[a+8]-n[l+8])>0?(v=g*n[a+6]*n[l+6]/w/w,n[a+2]+=f*v,n[a+3]+=y*v,n[l+2]-=f*v,n[l+3]-=y*v):w<0&&(v=100*g*n[a+6]*n[l+6],n[a+2]+=f*v,n[a+3]+=y*v,n[l+2]-=f*v,n[l+3]-=y*v):(w=Math.sqrt(f*f+y*y))>0&&(v=g*n[a+6]*n[l+6]/w/w,n[a+2]+=f*v,n[a+3]+=y*v,n[l+2]-=f*v,n[l+3]-=y*v);for(d=e.gravity/e.scalingRatio,g=e.scalingRatio,r=0;r<x;r+=t)v=0,f=n[r+0],y=n[r+1],w=Math.sqrt(Math.pow(f,2)+Math.pow(y,2)),e.strongGravityMode?w>0&&(v=g*n[r+6]*d):w>0&&(v=g*n[r+6]*d/w),n[r+2]-=f*v,n[r+3]-=y*v;for(g=1*(e.outboundAttractionDistribution?p:1),u=0;u<P;u+=3)a=i[u+0],l=i[u+1],h=i[u+2],b=Math.pow(h,e.edgeWeightInfluence),f=n[a+0]-n[l+0],y=n[a+1]-n[l+1],!0===L?(w=Math.sqrt(f*f+y*y)-n[a+8]-n[l+8],e.linLogMode?e.outboundAttractionDistribution?w>0&&(v=-g*b*Math.log(1+w)/w/n[a+6]):w>0&&(v=-g*b*Math.log(1+w)/w):e.outboundAttractionDistribution?w>0&&(v=-g*b/n[a+6]):w>0&&(v=-g*b)):(w=Math.sqrt(Math.pow(f,2)+Math.pow(y,2)),e.linLogMode?e.outboundAttractionDistribution?w>0&&(v=-g*b*Math.log(1+w)/w/n[a+6]):w>0&&(v=-g*b*Math.log(1+w)/w):e.outboundAttractionDistribution?(w=1,v=-g*b/n[a+6]):(w=1,v=-g*b)),w>0&&(n[a+2]+=f*v,n[a+3]+=y*v,n[l+2]-=f*v,n[l+3]-=y*v);if(!0===L)for(r=0;r<x;r+=t)1!==n[r+9]&&((C=Math.sqrt(Math.pow(n[r+2],2)+Math.pow(n[r+3],2)))>10&&(n[r+2]=10*n[r+2]/C,n[r+3]=10*n[r+3]/C),A=n[r+6]*Math.sqrt((n[r+4]-n[r+2])*(n[r+4]-n[r+2])+(n[r+5]-n[r+3])*(n[r+5]-n[r+3])),T=Math.sqrt((n[r+4]+n[r+2])*(n[r+4]+n[r+2])+(n[r+5]+n[r+3])*(n[r+5]+n[r+3]))/2,E=.1*Math.log(1+T)/(1+Math.sqrt(A)),S=n[r+0]+n[r+2]*(E/e.slowDown),n[r+0]=S,M=n[r+1]+n[r+3]*(E/e.slowDown),n[r+1]=M);else for(r=0;r<x;r+=t)1!==n[r+9]&&(A=n[r+6]*Math.sqrt((n[r+4]-n[r+2])*(n[r+4]-n[r+2])+(n[r+5]-n[r+3])*(n[r+5]-n[r+3])),T=Math.sqrt((n[r+4]+n[r+2])*(n[r+4]+n[r+2])+(n[r+5]+n[r+3])*(n[r+5]+n[r+3]))/2,E=n[r+7]*Math.log(1+T)/(1+Math.sqrt(A)),n[r+7]=Math.min(1,Math.sqrt(E*(Math.pow(n[r+2],2)+Math.pow(n[r+3],2))/(1+Math.sqrt(A)))),S=n[r+0]+n[r+2]*(E/e.slowDown),n[r+0]=S,M=n[r+1]+n[r+3]*(E/e.slowDown),n[r+1]=M);return{}}},8153(e,t){function n(e){return"number"!=typeof e||isNaN(e)?1:e}t.Fd=function(e){return function(e,t){var n={},i=function(e){return void 0===e?t:e};"function"==typeof t&&(i=t);var o=function(t){return i(t[e])},s=function(){return i(void 0)};return"string"==typeof e?(n.fromAttributes=o,n.fromGraph=function(e,t){return o(e.getEdgeAttributes(t))},n.fromEntry=function(e,t){return o(t)},n.fromPartialEntry=n.fromEntry,n.fromMinimalEntry=n.fromEntry):"function"==typeof e?(n.fromAttributes=function(){throw new Error("graphology-utils/getters/createEdgeValueGetter: irrelevant usage.")},n.fromGraph=function(t,n){var o=t.extremities(n);return i(e(n,t.getEdgeAttributes(n),o[0],o[1],t.getNodeAttributes(o[0]),t.getNodeAttributes(o[1]),t.isUndirected(n)))},n.fromEntry=function(t,n,o,s,r,a,l){return i(e(t,n,o,s,r,a,l))},n.fromPartialEntry=function(t,n,o,s){return i(e(t,n,o,s))},n.fromMinimalEntry=function(t,n){return i(e(t,n))}):(n.fromAttributes=s,n.fromGraph=s,n.fromEntry=s,n.fromMinimalEntry=s),n}(e,n)}},1736(e){e.exports=function(e){return null!==e&&"object"==typeof e&&"function"==typeof e.addUndirectedEdgeWithKey&&"function"==typeof e.dropNode&&"boolean"==typeof e.multi}},934(e){e.exports=function(){"use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,i(e,t)}function n(e){return n=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},n(e)}function i(e,t){return i=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},i(e,t)}function o(e,t,n){return o=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}()?Reflect.construct.bind():function(e,t,n){var o=[null];o.push.apply(o,t);var s=new(Function.bind.apply(e,o));return n&&i(s,n.prototype),s},o.apply(null,arguments)}function s(e){var t="function"==typeof Map?new Map:void 0;return s=function(e){if(null===e||(s=e,-1===Function.toString.call(s).indexOf("[native code]")))return e;var s;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return o(e,arguments,n(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),i(r,e)},s(e)}function r(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}var a=function(){for(var e=arguments[0],t=1,n=arguments.length;t<n;t++)if(arguments[t])for(var i in arguments[t])e[i]=arguments[t][i];return e};function l(e,t,n,i){var o=e._nodes.get(t),s=null;return o?s="mixed"===i?o.out&&o.out[n]||o.undirected&&o.undirected[n]:"directed"===i?o.out&&o.out[n]:o.undirected&&o.undirected[n]:s}function c(t){return"object"===e(t)&&null!==t}function u(e){var t;for(t in e)return!1;return!0}function h(e,t,n){Object.defineProperty(e,t,{enumerable:!1,configurable:!1,writable:!0,value:n})}function d(e,t,n){var i={enumerable:!0,configurable:!0};"function"==typeof n?i.get=n:(i.value=n,i.writable=!1),Object.defineProperty(e,t,i)}function m(e){return!(!c(e)||e.attributes&&!Array.isArray(e.attributes))}"function"==typeof Object.assign&&(a=Object.assign);var p,g={exports:{}},f="object"==typeof Reflect?Reflect:null,y=f&&"function"==typeof f.apply?f.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};p=f&&"function"==typeof f.ownKeys?f.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var b=Number.isNaN||function(e){return e!=e};function w(){w.init.call(this)}g.exports=w,g.exports.once=function(e,t){return new Promise(function(n,i){function o(n){e.removeListener(t,s),i(n)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",o),n([].slice.call(arguments))}L(e,t,s,{once:!0}),"error"!==t&&function(e,t){"function"==typeof e.on&&L(e,"error",t,{once:!0})}(e,o)})},w.EventEmitter=w,w.prototype._events=void 0,w.prototype._eventsCount=0,w.prototype._maxListeners=void 0;var v=10;function C(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function A(e){return void 0===e._maxListeners?w.defaultMaxListeners:e._maxListeners}function T(e,t,n,i){var o,s,r,a;if(C(n),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),r=s[t]),void 0===r)r=s[t]=n,++e._eventsCount;else if("function"==typeof r?r=s[t]=i?[n,r]:[r,n]:i?r.unshift(n):r.push(n),(o=A(e))>0&&r.length>o&&!r.warned){r.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+r.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=r.length,a=l,console&&console.warn&&console.warn(a)}return e}function E(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function S(e,t,n){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},o=E.bind(i);return o.listener=n,i.wrapFn=o,o}function M(e,t,n){var i=e._events;if(void 0===i)return[];var o=i[t];return void 0===o?[]:"function"==typeof o?n?[o.listener||o]:[o]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(o):P(o,o.length)}function x(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function P(e,t){for(var n=new Array(t),i=0;i<t;++i)n[i]=e[i];return n}function L(e,t,n,i){if("function"==typeof e.on)i.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function o(s){i.once&&e.removeEventListener(t,o),n(s)})}}function I(e){if("function"!=typeof e)throw new Error("obliterator/iterator: expecting a function!");this.next=e}Object.defineProperty(w,"defaultMaxListeners",{enumerable:!0,get:function(){return v},set:function(e){if("number"!=typeof e||e<0||b(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");v=e}}),w.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},w.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||b(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},w.prototype.getMaxListeners=function(){return A(this)},w.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i="error"===e,o=this._events;if(void 0!==o)i=i&&void 0===o.error;else if(!i)return!1;if(i){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var r=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw r.context=s,r}var a=o[e];if(void 0===a)return!1;if("function"==typeof a)y(a,this,t);else{var l=a.length,c=P(a,l);for(n=0;n<l;++n)y(c[n],this,t)}return!0},w.prototype.addListener=function(e,t){return T(this,e,t,!1)},w.prototype.on=w.prototype.addListener,w.prototype.prependListener=function(e,t){return T(this,e,t,!0)},w.prototype.once=function(e,t){return C(t),this.on(e,S(this,e,t)),this},w.prototype.prependOnceListener=function(e,t){return C(t),this.prependListener(e,S(this,e,t)),this},w.prototype.removeListener=function(e,t){var n,i,o,s,r;if(C(t),void 0===(i=this._events))return this;if(void 0===(n=i[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(o=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){r=n[s].listener,o=s;break}if(o<0)return this;0===o?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,o),1===n.length&&(i[e]=n[0]),void 0!==i.removeListener&&this.emit("removeListener",e,r||t)}return this},w.prototype.off=w.prototype.removeListener,w.prototype.removeAllListeners=function(e){var t,n,i;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var o,s=Object.keys(n);for(i=0;i<s.length;++i)"removeListener"!==(o=s[i])&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},w.prototype.listeners=function(e){return M(this,e,!0)},w.prototype.rawListeners=function(e){return M(this,e,!1)},w.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):x.call(e,t)},w.prototype.listenerCount=x,w.prototype.eventNames=function(){return this._eventsCount>0?p(this._events):[]},"undefined"!=typeof Symbol&&(I.prototype[Symbol.iterator]=function(){return this}),I.of=function(){var e=arguments,t=e.length,n=0;return new I(function(){return n>=t?{done:!0}:{done:!1,value:e[n++]}})},I.empty=function(){return new I(function(){return{done:!0}})},I.fromSequence=function(e){var t=0,n=e.length;return new I(function(){return t>=n?{done:!0}:{done:!1,value:e[t++]}})},I.is=function(e){return e instanceof I||"object"==typeof e&&null!==e&&"function"==typeof e.next};var _=I,N={};N.ARRAY_BUFFER_SUPPORT="undefined"!=typeof ArrayBuffer,N.SYMBOL_SUPPORT="undefined"!=typeof Symbol;var R=_,$=N,O=$.ARRAY_BUFFER_SUPPORT,H=$.SYMBOL_SUPPORT,D=function(e){var t=function(e){return"string"==typeof e||Array.isArray(e)||O&&ArrayBuffer.isView(e)?R.fromSequence(e):"object"!=typeof e||null===e?null:H&&"function"==typeof e[Symbol.iterator]?e[Symbol.iterator]():"function"==typeof e.next?e:null}(e);if(!t)throw new Error("obliterator: target is not iterable nor a valid iterator.");return t},F=D,k=function(e,t){for(var n,i=arguments.length>1?t:1/0,o=i!==1/0?new Array(i):[],s=0,r=F(e);;){if(s===i)return o;if((n=r.next()).done)return s!==t&&(o.length=s),o;o[s++]=n.value}},G=function(e){function n(t){var n;return(n=e.call(this)||this).name="GraphError",n.message=t,n}return t(n,e),n}(s(Error)),B=function(e){function n(t){var i;return(i=e.call(this,t)||this).name="InvalidArgumentsGraphError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(r(i),n.prototype.constructor),i}return t(n,e),n}(G),V=function(e){function n(t){var i;return(i=e.call(this,t)||this).name="NotFoundGraphError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(r(i),n.prototype.constructor),i}return t(n,e),n}(G),U=function(e){function n(t){var i;return(i=e.call(this,t)||this).name="UsageGraphError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(r(i),n.prototype.constructor),i}return t(n,e),n}(G);function q(e,t){this.key=e,this.attributes=t,this.clear()}function W(e,t){this.key=e,this.attributes=t,this.clear()}function Y(e,t){this.key=e,this.attributes=t,this.clear()}function j(e,t,n,i,o){this.key=t,this.attributes=o,this.undirected=e,this.source=n,this.target=i}function K(e,t,n,i,o,s,r){var a,l,c,u;if(i=""+i,0===n){if(!(a=e._nodes.get(i)))throw new V("Graph.".concat(t,': could not find the "').concat(i,'" node in the graph.'));c=o,u=s}else if(3===n){if(o=""+o,!(l=e._edges.get(o)))throw new V("Graph.".concat(t,': could not find the "').concat(o,'" edge in the graph.'));var h=l.source.key,d=l.target.key;if(i===h)a=l.target;else{if(i!==d)throw new V("Graph.".concat(t,': the "').concat(i,'" node is not attached to the "').concat(o,'" edge (').concat(h,", ").concat(d,")."));a=l.source}c=s,u=r}else{if(!(l=e._edges.get(i)))throw new V("Graph.".concat(t,': could not find the "').concat(i,'" edge in the graph.'));a=1===n?l.source:l.target,c=o,u=s}return[a,c,u]}q.prototype.clear=function(){this.inDegree=0,this.outDegree=0,this.undirectedDegree=0,this.undirectedLoops=0,this.directedLoops=0,this.in={},this.out={},this.undirected={}},W.prototype.clear=function(){this.inDegree=0,this.outDegree=0,this.directedLoops=0,this.in={},this.out={}},Y.prototype.clear=function(){this.undirectedDegree=0,this.undirectedLoops=0,this.undirected={}},j.prototype.attach=function(){var e="out",t="in";this.undirected&&(e=t="undirected");var n=this.source.key,i=this.target.key;this.source[e][i]=this,this.undirected&&n===i||(this.target[t][n]=this)},j.prototype.attachMulti=function(){var e="out",t="in",n=this.source.key,i=this.target.key;this.undirected&&(e=t="undirected");var o=this.source[e],s=o[i];if(void 0===s)return o[i]=this,void(this.undirected&&n===i||(this.target[t][n]=this));s.previous=this,this.next=s,o[i]=this,this.target[t][n]=this},j.prototype.detach=function(){var e=this.source.key,t=this.target.key,n="out",i="in";this.undirected&&(n=i="undirected"),delete this.source[n][t],delete this.target[i][e]},j.prototype.detachMulti=function(){var e=this.source.key,t=this.target.key,n="out",i="in";this.undirected&&(n=i="undirected"),void 0===this.previous?void 0===this.next?(delete this.source[n][t],delete this.target[i][e]):(this.next.previous=void 0,this.source[n][t]=this.next,this.target[i][e]=this.next):(this.previous.next=this.next,void 0!==this.next&&(this.next.previous=this.previous))};var z=[{name:function(e){return"get".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o){var s=K(this,t,n,e,i,o),r=s[0],a=s[1];return r.attributes[a]}}},{name:function(e){return"get".concat(e,"Attributes")},attacher:function(e,t,n){e.prototype[t]=function(e,i){return K(this,t,n,e,i)[0].attributes}}},{name:function(e){return"has".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o){var s=K(this,t,n,e,i,o),r=s[0],a=s[1];return r.attributes.hasOwnProperty(a)}}},{name:function(e){return"set".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o,s){var r=K(this,t,n,e,i,o,s),a=r[0],l=r[1],c=r[2];return a.attributes[l]=c,this.emit("nodeAttributesUpdated",{key:a.key,type:"set",attributes:a.attributes,name:l}),this}}},{name:function(e){return"update".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o,s){var r=K(this,t,n,e,i,o,s),a=r[0],l=r[1],c=r[2];if("function"!=typeof c)throw new B("Graph.".concat(t,": updater should be a function."));var u=a.attributes,h=c(u[l]);return u[l]=h,this.emit("nodeAttributesUpdated",{key:a.key,type:"set",attributes:a.attributes,name:l}),this}}},{name:function(e){return"remove".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o){var s=K(this,t,n,e,i,o),r=s[0],a=s[1];return delete r.attributes[a],this.emit("nodeAttributesUpdated",{key:r.key,type:"remove",attributes:r.attributes,name:a}),this}}},{name:function(e){return"replace".concat(e,"Attributes")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o){var s=K(this,t,n,e,i,o),r=s[0],a=s[1];if(!c(a))throw new B("Graph.".concat(t,": provided attributes are not a plain object."));return r.attributes=a,this.emit("nodeAttributesUpdated",{key:r.key,type:"replace",attributes:r.attributes}),this}}},{name:function(e){return"merge".concat(e,"Attributes")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o){var s=K(this,t,n,e,i,o),r=s[0],l=s[1];if(!c(l))throw new B("Graph.".concat(t,": provided attributes are not a plain object."));return a(r.attributes,l),this.emit("nodeAttributesUpdated",{key:r.key,type:"merge",attributes:r.attributes,data:l}),this}}},{name:function(e){return"update".concat(e,"Attributes")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o){var s=K(this,t,n,e,i,o),r=s[0],a=s[1];if("function"!=typeof a)throw new B("Graph.".concat(t,": provided updater is not a function."));return r.attributes=a(r.attributes),this.emit("nodeAttributesUpdated",{key:r.key,type:"update",attributes:r.attributes}),this}}}],Z=[{name:function(e){return"get".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i){var o;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new U("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>2){if(this.multi)throw new U("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var s=""+e,r=""+i;if(i=arguments[2],!(o=l(this,s,r,n)))throw new V("Graph.".concat(t,': could not find an edge for the given path ("').concat(s,'" - "').concat(r,'").'))}else{if("mixed"!==n)throw new U("Graph.".concat(t,": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type."));if(e=""+e,!(o=this._edges.get(e)))throw new V("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'))}return o.attributes[i]}}},{name:function(e){return"get".concat(e,"Attributes")},attacher:function(e,t,n){e.prototype[t]=function(e){var i;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new U("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>1){if(this.multi)throw new U("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var o=""+e,s=""+arguments[1];if(!(i=l(this,o,s,n)))throw new V("Graph.".concat(t,': could not find an edge for the given path ("').concat(o,'" - "').concat(s,'").'))}else{if("mixed"!==n)throw new U("Graph.".concat(t,": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type."));if(e=""+e,!(i=this._edges.get(e)))throw new V("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'))}return i.attributes}}},{name:function(e){return"has".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i){var o;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new U("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>2){if(this.multi)throw new U("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var s=""+e,r=""+i;if(i=arguments[2],!(o=l(this,s,r,n)))throw new V("Graph.".concat(t,': could not find an edge for the given path ("').concat(s,'" - "').concat(r,'").'))}else{if("mixed"!==n)throw new U("Graph.".concat(t,": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type."));if(e=""+e,!(o=this._edges.get(e)))throw new V("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'))}return o.attributes.hasOwnProperty(i)}}},{name:function(e){return"set".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o){var s;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new U("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>3){if(this.multi)throw new U("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var r=""+e,a=""+i;if(i=arguments[2],o=arguments[3],!(s=l(this,r,a,n)))throw new V("Graph.".concat(t,': could not find an edge for the given path ("').concat(r,'" - "').concat(a,'").'))}else{if("mixed"!==n)throw new U("Graph.".concat(t,": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type."));if(e=""+e,!(s=this._edges.get(e)))throw new V("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'))}return s.attributes[i]=o,this.emit("edgeAttributesUpdated",{key:s.key,type:"set",attributes:s.attributes,name:i}),this}}},{name:function(e){return"update".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i,o){var s;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new U("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>3){if(this.multi)throw new U("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var r=""+e,a=""+i;if(i=arguments[2],o=arguments[3],!(s=l(this,r,a,n)))throw new V("Graph.".concat(t,': could not find an edge for the given path ("').concat(r,'" - "').concat(a,'").'))}else{if("mixed"!==n)throw new U("Graph.".concat(t,": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type."));if(e=""+e,!(s=this._edges.get(e)))throw new V("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'))}if("function"!=typeof o)throw new B("Graph.".concat(t,": updater should be a function."));return s.attributes[i]=o(s.attributes[i]),this.emit("edgeAttributesUpdated",{key:s.key,type:"set",attributes:s.attributes,name:i}),this}}},{name:function(e){return"remove".concat(e,"Attribute")},attacher:function(e,t,n){e.prototype[t]=function(e,i){var o;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new U("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>2){if(this.multi)throw new U("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var s=""+e,r=""+i;if(i=arguments[2],!(o=l(this,s,r,n)))throw new V("Graph.".concat(t,': could not find an edge for the given path ("').concat(s,'" - "').concat(r,'").'))}else{if("mixed"!==n)throw new U("Graph.".concat(t,": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type."));if(e=""+e,!(o=this._edges.get(e)))throw new V("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'))}return delete o.attributes[i],this.emit("edgeAttributesUpdated",{key:o.key,type:"remove",attributes:o.attributes,name:i}),this}}},{name:function(e){return"replace".concat(e,"Attributes")},attacher:function(e,t,n){e.prototype[t]=function(e,i){var o;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new U("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>2){if(this.multi)throw new U("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var s=""+e,r=""+i;if(i=arguments[2],!(o=l(this,s,r,n)))throw new V("Graph.".concat(t,': could not find an edge for the given path ("').concat(s,'" - "').concat(r,'").'))}else{if("mixed"!==n)throw new U("Graph.".concat(t,": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type."));if(e=""+e,!(o=this._edges.get(e)))throw new V("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'))}if(!c(i))throw new B("Graph.".concat(t,": provided attributes are not a plain object."));return o.attributes=i,this.emit("edgeAttributesUpdated",{key:o.key,type:"replace",attributes:o.attributes}),this}}},{name:function(e){return"merge".concat(e,"Attributes")},attacher:function(e,t,n){e.prototype[t]=function(e,i){var o;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new U("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>2){if(this.multi)throw new U("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var s=""+e,r=""+i;if(i=arguments[2],!(o=l(this,s,r,n)))throw new V("Graph.".concat(t,': could not find an edge for the given path ("').concat(s,'" - "').concat(r,'").'))}else{if("mixed"!==n)throw new U("Graph.".concat(t,": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type."));if(e=""+e,!(o=this._edges.get(e)))throw new V("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'))}if(!c(i))throw new B("Graph.".concat(t,": provided attributes are not a plain object."));return a(o.attributes,i),this.emit("edgeAttributesUpdated",{key:o.key,type:"merge",attributes:o.attributes,data:i}),this}}},{name:function(e){return"update".concat(e,"Attributes")},attacher:function(e,t,n){e.prototype[t]=function(e,i){var o;if("mixed"!==this.type&&"mixed"!==n&&n!==this.type)throw new U("Graph.".concat(t,": cannot find this type of edges in your ").concat(this.type," graph."));if(arguments.length>2){if(this.multi)throw new U("Graph.".concat(t,": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about."));var s=""+e,r=""+i;if(i=arguments[2],!(o=l(this,s,r,n)))throw new V("Graph.".concat(t,': could not find an edge for the given path ("').concat(s,'" - "').concat(r,'").'))}else{if("mixed"!==n)throw new U("Graph.".concat(t,": calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type."));if(e=""+e,!(o=this._edges.get(e)))throw new V("Graph.".concat(t,': could not find the "').concat(e,'" edge in the graph.'))}if("function"!=typeof i)throw new B("Graph.".concat(t,": provided updater is not a function."));return o.attributes=i(o.attributes),this.emit("edgeAttributesUpdated",{key:o.key,type:"update",attributes:o.attributes}),this}}}],X=_,Q=D,J=function(){var e=arguments,t=null,n=-1;return new X(function(){for(var i=null;;){if(null===t){if(++n>=e.length)return{done:!0};t=Q(e[n])}if(!0!==(i=t.next()).done)break;t=null}return i})},ee=[{name:"edges",type:"mixed"},{name:"inEdges",type:"directed",direction:"in"},{name:"outEdges",type:"directed",direction:"out"},{name:"inboundEdges",type:"mixed",direction:"in"},{name:"outboundEdges",type:"mixed",direction:"out"},{name:"directedEdges",type:"directed"},{name:"undirectedEdges",type:"undirected"}];function te(e,t,n,i){var o=!1;for(var s in t)if(s!==i){var r=t[s];if(o=n(r.key,r.attributes,r.source.key,r.target.key,r.source.attributes,r.target.attributes,r.undirected),e&&o)return r.key}}function ne(e,t,n,i){var o,s,r,a=!1;for(var l in t)if(l!==i){o=t[l];do{if(s=o.source,r=o.target,a=n(o.key,o.attributes,s.key,r.key,s.attributes,r.attributes,o.undirected),e&&a)return o.key;o=o.next}while(void 0!==o)}}function ie(e,t){var n,i=Object.keys(e),o=i.length,s=0;return new _(function(){do{if(n)n=n.next;else{if(s>=o)return{done:!0};var r=i[s++];if(r===t){n=void 0;continue}n=e[r]}}while(!n);return{done:!1,value:{edge:n.key,attributes:n.attributes,source:n.source.key,target:n.target.key,sourceAttributes:n.source.attributes,targetAttributes:n.target.attributes,undirected:n.undirected}}})}function oe(e,t,n,i){var o=t[n];if(o){var s=o.source,r=o.target;return i(o.key,o.attributes,s.key,r.key,s.attributes,r.attributes,o.undirected)&&e?o.key:void 0}}function se(e,t,n,i){var o=t[n];if(o){var s=!1;do{if(s=i(o.key,o.attributes,o.source.key,o.target.key,o.source.attributes,o.target.attributes,o.undirected),e&&s)return o.key;o=o.next}while(void 0!==o)}}function re(e,t){var n=e[t];return void 0!==n.next?new _(function(){if(!n)return{done:!0};var e={edge:n.key,attributes:n.attributes,source:n.source.key,target:n.target.key,sourceAttributes:n.source.attributes,targetAttributes:n.target.attributes,undirected:n.undirected};return n=n.next,{done:!1,value:e}}):_.of({edge:n.key,attributes:n.attributes,source:n.source.key,target:n.target.key,sourceAttributes:n.source.attributes,targetAttributes:n.target.attributes,undirected:n.undirected})}function ae(e,t,n,i){if(0!==t.size)for(var o,s,r="mixed"!==n&&n!==t.type,a="undirected"===n,l=!1,c=t._edges.values();!0!==(o=c.next()).done;)if(s=o.value,!r||s.undirected===a){var u=s,h=u.key,d=u.attributes,m=u.source,p=u.target;if(l=i(h,d,m.key,p.key,m.attributes,p.attributes,s.undirected),e&&l)return h}}function le(e,t,n,i,o,s){var r,a=t?ne:te;if("undirected"!==n){if("out"!==i&&(r=a(e,o.in,s),e&&r))return r;if("in"!==i&&(r=a(e,o.out,s,i?void 0:o.key),e&&r))return r}if("directed"!==n&&(r=a(e,o.undirected,s),e&&r))return r}function ce(e,t,n,i,o,s,r){var a,l=n?se:oe;if("undirected"!==t){if(void 0!==o.in&&"out"!==i&&(a=l(e,o.in,s,r),e&&a))return a;if(void 0!==o.out&&"in"!==i&&(i||o.key!==s)&&(a=l(e,o.out,s,r),e&&a))return a}if("directed"!==t&&void 0!==o.undirected&&(a=l(e,o.undirected,s,r),e&&a))return a}var ue=[{name:"neighbors",type:"mixed"},{name:"inNeighbors",type:"directed",direction:"in"},{name:"outNeighbors",type:"directed",direction:"out"},{name:"inboundNeighbors",type:"mixed",direction:"in"},{name:"outboundNeighbors",type:"mixed",direction:"out"},{name:"directedNeighbors",type:"directed"},{name:"undirectedNeighbors",type:"undirected"}];function he(){this.A=null,this.B=null}function de(e,t,n,i,o){for(var s in i){var r=i[s],a=r.source,l=r.target,c=a===n?l:a;if(!t||!t.has(c.key)){var u=o(c.key,c.attributes);if(e&&u)return c.key}}}function me(e,t,n,i,o){if("mixed"!==t){if("undirected"===t)return de(e,null,i,i.undirected,o);if("string"==typeof n)return de(e,null,i,i[n],o)}var s,r=new he;if("undirected"!==t){if("out"!==n){if(s=de(e,null,i,i.in,o),e&&s)return s;r.wrap(i.in)}if("in"!==n){if(s=de(e,r,i,i.out,o),e&&s)return s;r.wrap(i.out)}}if("directed"!==t&&(s=de(e,r,i,i.undirected,o),e&&s))return s}function pe(e,t,n){var i=Object.keys(n),o=i.length,s=0;return new _(function(){var r=null;do{if(s>=o)return e&&e.wrap(n),{done:!0};var a=n[i[s++]],l=a.source,c=a.target;r=l===t?c:l,e&&e.has(r.key)&&(r=null)}while(null===r);return{done:!1,value:{neighbor:r.key,attributes:r.attributes}}})}function ge(e,t,n,i,o){for(var s,r,a,l,c,u,h,d=i._nodes.values(),m=i.type;!0!==(s=d.next()).done;){var p=!1;if(r=s.value,"undirected"!==m)for(a in l=r.out){c=l[a];do{if(u=c.target,p=!0,h=o(r.key,u.key,r.attributes,u.attributes,c.key,c.attributes,c.undirected),e&&h)return c;c=c.next}while(c)}if("directed"!==m)for(a in l=r.undirected)if(!(t&&r.key>a)){c=l[a];do{if((u=c.target).key!==a&&(u=c.source),p=!0,h=o(r.key,u.key,r.attributes,u.attributes,c.key,c.attributes,c.undirected),e&&h)return c;c=c.next}while(c)}if(n&&!p&&(h=o(r.key,null,r.attributes,null,null,null,null),e&&h))return null}}function fe(e){if(!c(e))throw new B('Graph.import: invalid serialized node. A serialized node should be a plain object with at least a "key" property.');if(!("key"in e))throw new B("Graph.import: serialized node is missing its key.");if("attributes"in e&&(!c(e.attributes)||null===e.attributes))throw new B("Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.")}function ye(e){if(!c(e))throw new B('Graph.import: invalid serialized edge. A serialized edge should be a plain object with at least a "source" & "target" property.');if(!("source"in e))throw new B("Graph.import: serialized edge is missing its source.");if(!("target"in e))throw new B("Graph.import: serialized edge is missing its target.");if("attributes"in e&&(!c(e.attributes)||null===e.attributes))throw new B("Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.");if("undirected"in e&&"boolean"!=typeof e.undirected)throw new B("Graph.import: invalid undirectedness information. Undirected should be boolean or omitted.")}he.prototype.wrap=function(e){null===this.A?this.A=e:null===this.B&&(this.B=e)},he.prototype.has=function(e){return null!==this.A&&e in this.A||null!==this.B&&e in this.B};var be,we=(be=255&Math.floor(256*Math.random()),function(){return be++}),ve=new Set(["directed","undirected","mixed"]),Ce=new Set(["domain","_events","_eventsCount","_maxListeners"]),Ae={allowSelfLoops:!0,multi:!1,type:"mixed"};function Te(e,t,n){var i=new e.NodeDataClass(t,n);return e._nodes.set(t,i),e.emit("nodeAdded",{key:t,attributes:n}),i}function Ee(e,t,n,i,o,s,r,a){if(!i&&"undirected"===e.type)throw new U("Graph.".concat(t,": you cannot add a directed edge to an undirected graph. Use the #.addEdge or #.addUndirectedEdge instead."));if(i&&"directed"===e.type)throw new U("Graph.".concat(t,": you cannot add an undirected edge to a directed graph. Use the #.addEdge or #.addDirectedEdge instead."));if(a&&!c(a))throw new B("Graph.".concat(t,': invalid attributes. Expecting an object but got "').concat(a,'"'));if(s=""+s,r=""+r,a=a||{},!e.allowSelfLoops&&s===r)throw new U("Graph.".concat(t,': source & target are the same ("').concat(s,"\"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false."));var l=e._nodes.get(s),u=e._nodes.get(r);if(!l)throw new V("Graph.".concat(t,': source node "').concat(s,'" not found.'));if(!u)throw new V("Graph.".concat(t,': target node "').concat(r,'" not found.'));var h={key:null,undirected:i,source:s,target:r,attributes:a};if(n)o=e._edgeKeyGenerator();else if(o=""+o,e._edges.has(o))throw new U("Graph.".concat(t,': the "').concat(o,'" edge already exists in the graph.'));if(!e.multi&&(i?void 0!==l.undirected[r]:void 0!==l.out[r]))throw new U("Graph.".concat(t,': an edge linking "').concat(s,'" to "').concat(r,"\" already exists. If you really want to add multiple edges linking those nodes, you should create a multi graph by using the 'multi' option."));var d=new j(i,o,l,u,a);e._edges.set(o,d);var m=s===r;return i?(l.undirectedDegree++,u.undirectedDegree++,m&&(l.undirectedLoops++,e._undirectedSelfLoopCount++)):(l.outDegree++,u.inDegree++,m&&(l.directedLoops++,e._directedSelfLoopCount++)),e.multi?d.attachMulti():d.attach(),i?e._undirectedSize++:e._directedSize++,h.key=o,e.emit("edgeAdded",h),o}function Se(e,t,n,i,o,s,r,l,u){if(!i&&"undirected"===e.type)throw new U("Graph.".concat(t,": you cannot merge/update a directed edge to an undirected graph. Use the #.mergeEdge/#.updateEdge or #.addUndirectedEdge instead."));if(i&&"directed"===e.type)throw new U("Graph.".concat(t,": you cannot merge/update an undirected edge to a directed graph. Use the #.mergeEdge/#.updateEdge or #.addDirectedEdge instead."));if(l)if(u){if("function"!=typeof l)throw new B("Graph.".concat(t,': invalid updater function. Expecting a function but got "').concat(l,'"'))}else if(!c(l))throw new B("Graph.".concat(t,': invalid attributes. Expecting an object but got "').concat(l,'"'));var h;if(s=""+s,r=""+r,u&&(h=l,l=void 0),!e.allowSelfLoops&&s===r)throw new U("Graph.".concat(t,': source & target are the same ("').concat(s,"\"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false."));var d,m,p=e._nodes.get(s),g=e._nodes.get(r);if(!n&&(d=e._edges.get(o))){if(!(d.source.key===s&&d.target.key===r||i&&d.source.key===r&&d.target.key===s))throw new U("Graph.".concat(t,': inconsistency detected when attempting to merge the "').concat(o,'" edge with "').concat(s,'" source & "').concat(r,'" target vs. ("').concat(d.source.key,'", "').concat(d.target.key,'").'));m=d}if(m||e.multi||!p||(m=i?p.undirected[r]:p.out[r]),m){var f=[m.key,!1,!1,!1];if(u?!h:!l)return f;if(u){var y=m.attributes;m.attributes=h(y),e.emit("edgeAttributesUpdated",{type:"replace",key:m.key,attributes:m.attributes})}else a(m.attributes,l),e.emit("edgeAttributesUpdated",{type:"merge",key:m.key,attributes:m.attributes,data:l});return f}l=l||{},u&&h&&(l=h(l));var b={key:null,undirected:i,source:s,target:r,attributes:l};if(n)o=e._edgeKeyGenerator();else if(o=""+o,e._edges.has(o))throw new U("Graph.".concat(t,': the "').concat(o,'" edge already exists in the graph.'));var w=!1,v=!1;p||(p=Te(e,s,{}),w=!0,s===r&&(g=p,v=!0)),g||(g=Te(e,r,{}),v=!0),d=new j(i,o,p,g,l),e._edges.set(o,d);var C=s===r;return i?(p.undirectedDegree++,g.undirectedDegree++,C&&(p.undirectedLoops++,e._undirectedSelfLoopCount++)):(p.outDegree++,g.inDegree++,C&&(p.directedLoops++,e._directedSelfLoopCount++)),e.multi?d.attachMulti():d.attach(),i?e._undirectedSize++:e._directedSize++,b.key=o,e.emit("edgeAdded",b),[o,!0,w,v]}function Me(e,t){e._edges.delete(t.key);var n=t.source,i=t.target,o=t.attributes,s=t.undirected,r=n===i;s?(n.undirectedDegree--,i.undirectedDegree--,r&&(n.undirectedLoops--,e._undirectedSelfLoopCount--)):(n.outDegree--,i.inDegree--,r&&(n.directedLoops--,e._directedSelfLoopCount--)),e.multi?t.detachMulti():t.detach(),s?e._undirectedSize--:e._directedSize--,e.emit("edgeDropped",{key:t.key,attributes:o,source:n.key,target:i.key,undirected:s})}var xe=function(n){function i(e){var t;if(t=n.call(this)||this,"boolean"!=typeof(e=a({},Ae,e)).multi)throw new B("Graph.constructor: invalid 'multi' option. Expecting a boolean but got \"".concat(e.multi,'".'));if(!ve.has(e.type))throw new B('Graph.constructor: invalid \'type\' option. Should be one of "mixed", "directed" or "undirected" but got "'.concat(e.type,'".'));if("boolean"!=typeof e.allowSelfLoops)throw new B("Graph.constructor: invalid 'allowSelfLoops' option. Expecting a boolean but got \"".concat(e.allowSelfLoops,'".'));var i="mixed"===e.type?q:"directed"===e.type?W:Y;h(r(t),"NodeDataClass",i);var o="geid_"+we()+"_",s=0;return h(r(t),"_attributes",{}),h(r(t),"_nodes",new Map),h(r(t),"_edges",new Map),h(r(t),"_directedSize",0),h(r(t),"_undirectedSize",0),h(r(t),"_directedSelfLoopCount",0),h(r(t),"_undirectedSelfLoopCount",0),h(r(t),"_edgeKeyGenerator",function(){var e;do{e=o+s++}while(t._edges.has(e));return e}),h(r(t),"_options",e),Ce.forEach(function(e){return h(r(t),e,t[e])}),d(r(t),"order",function(){return t._nodes.size}),d(r(t),"size",function(){return t._edges.size}),d(r(t),"directedSize",function(){return t._directedSize}),d(r(t),"undirectedSize",function(){return t._undirectedSize}),d(r(t),"selfLoopCount",function(){return t._directedSelfLoopCount+t._undirectedSelfLoopCount}),d(r(t),"directedSelfLoopCount",function(){return t._directedSelfLoopCount}),d(r(t),"undirectedSelfLoopCount",function(){return t._undirectedSelfLoopCount}),d(r(t),"multi",t._options.multi),d(r(t),"type",t._options.type),d(r(t),"allowSelfLoops",t._options.allowSelfLoops),d(r(t),"implementation",function(){return"graphology"}),t}t(i,n);var o=i.prototype;return o._resetInstanceCounters=function(){this._directedSize=0,this._undirectedSize=0,this._directedSelfLoopCount=0,this._undirectedSelfLoopCount=0},o.hasNode=function(e){return this._nodes.has(""+e)},o.hasDirectedEdge=function(e,t){if("undirected"===this.type)return!1;if(1===arguments.length){var n=""+e,i=this._edges.get(n);return!!i&&!i.undirected}if(2===arguments.length){e=""+e,t=""+t;var o=this._nodes.get(e);return!!o&&o.out.hasOwnProperty(t)}throw new B("Graph.hasDirectedEdge: invalid arity (".concat(arguments.length,", instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target."))},o.hasUndirectedEdge=function(e,t){if("directed"===this.type)return!1;if(1===arguments.length){var n=""+e,i=this._edges.get(n);return!!i&&i.undirected}if(2===arguments.length){e=""+e,t=""+t;var o=this._nodes.get(e);return!!o&&o.undirected.hasOwnProperty(t)}throw new B("Graph.hasDirectedEdge: invalid arity (".concat(arguments.length,", instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target."))},o.hasEdge=function(e,t){if(1===arguments.length){var n=""+e;return this._edges.has(n)}if(2===arguments.length){e=""+e,t=""+t;var i=this._nodes.get(e);return!!i&&(void 0!==i.out&&i.out.hasOwnProperty(t)||void 0!==i.undirected&&i.undirected.hasOwnProperty(t))}throw new B("Graph.hasEdge: invalid arity (".concat(arguments.length,", instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target."))},o.directedEdge=function(e,t){if("undirected"!==this.type){if(e=""+e,t=""+t,this.multi)throw new U("Graph.directedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.directedEdges instead.");var n=this._nodes.get(e);if(!n)throw new V('Graph.directedEdge: could not find the "'.concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new V('Graph.directedEdge: could not find the "'.concat(t,'" target node in the graph.'));var i=n.out&&n.out[t]||void 0;return i?i.key:void 0}},o.undirectedEdge=function(e,t){if("directed"!==this.type){if(e=""+e,t=""+t,this.multi)throw new U("Graph.undirectedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.undirectedEdges instead.");var n=this._nodes.get(e);if(!n)throw new V('Graph.undirectedEdge: could not find the "'.concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new V('Graph.undirectedEdge: could not find the "'.concat(t,'" target node in the graph.'));var i=n.undirected&&n.undirected[t]||void 0;return i?i.key:void 0}},o.edge=function(e,t){if(this.multi)throw new U("Graph.edge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.edges instead.");e=""+e,t=""+t;var n=this._nodes.get(e);if(!n)throw new V('Graph.edge: could not find the "'.concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new V('Graph.edge: could not find the "'.concat(t,'" target node in the graph.'));var i=n.out&&n.out[t]||n.undirected&&n.undirected[t]||void 0;if(i)return i.key},o.areDirectedNeighbors=function(e,t){e=""+e,t=""+t;var n=this._nodes.get(e);if(!n)throw new V('Graph.areDirectedNeighbors: could not find the "'.concat(e,'" node in the graph.'));return"undirected"!==this.type&&(t in n.in||t in n.out)},o.areOutNeighbors=function(e,t){e=""+e,t=""+t;var n=this._nodes.get(e);if(!n)throw new V('Graph.areOutNeighbors: could not find the "'.concat(e,'" node in the graph.'));return"undirected"!==this.type&&t in n.out},o.areInNeighbors=function(e,t){e=""+e,t=""+t;var n=this._nodes.get(e);if(!n)throw new V('Graph.areInNeighbors: could not find the "'.concat(e,'" node in the graph.'));return"undirected"!==this.type&&t in n.in},o.areUndirectedNeighbors=function(e,t){e=""+e,t=""+t;var n=this._nodes.get(e);if(!n)throw new V('Graph.areUndirectedNeighbors: could not find the "'.concat(e,'" node in the graph.'));return"directed"!==this.type&&t in n.undirected},o.areNeighbors=function(e,t){e=""+e,t=""+t;var n=this._nodes.get(e);if(!n)throw new V('Graph.areNeighbors: could not find the "'.concat(e,'" node in the graph.'));return"undirected"!==this.type&&(t in n.in||t in n.out)||"directed"!==this.type&&t in n.undirected},o.areInboundNeighbors=function(e,t){e=""+e,t=""+t;var n=this._nodes.get(e);if(!n)throw new V('Graph.areInboundNeighbors: could not find the "'.concat(e,'" node in the graph.'));return"undirected"!==this.type&&t in n.in||"directed"!==this.type&&t in n.undirected},o.areOutboundNeighbors=function(e,t){e=""+e,t=""+t;var n=this._nodes.get(e);if(!n)throw new V('Graph.areOutboundNeighbors: could not find the "'.concat(e,'" node in the graph.'));return"undirected"!==this.type&&t in n.out||"directed"!==this.type&&t in n.undirected},o.inDegree=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.inDegree: could not find the "'.concat(e,'" node in the graph.'));return"undirected"===this.type?0:t.inDegree},o.outDegree=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.outDegree: could not find the "'.concat(e,'" node in the graph.'));return"undirected"===this.type?0:t.outDegree},o.directedDegree=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.directedDegree: could not find the "'.concat(e,'" node in the graph.'));return"undirected"===this.type?0:t.inDegree+t.outDegree},o.undirectedDegree=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.undirectedDegree: could not find the "'.concat(e,'" node in the graph.'));return"directed"===this.type?0:t.undirectedDegree},o.inboundDegree=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.inboundDegree: could not find the "'.concat(e,'" node in the graph.'));var n=0;return"directed"!==this.type&&(n+=t.undirectedDegree),"undirected"!==this.type&&(n+=t.inDegree),n},o.outboundDegree=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.outboundDegree: could not find the "'.concat(e,'" node in the graph.'));var n=0;return"directed"!==this.type&&(n+=t.undirectedDegree),"undirected"!==this.type&&(n+=t.outDegree),n},o.degree=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.degree: could not find the "'.concat(e,'" node in the graph.'));var n=0;return"directed"!==this.type&&(n+=t.undirectedDegree),"undirected"!==this.type&&(n+=t.inDegree+t.outDegree),n},o.inDegreeWithoutSelfLoops=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.inDegreeWithoutSelfLoops: could not find the "'.concat(e,'" node in the graph.'));return"undirected"===this.type?0:t.inDegree-t.directedLoops},o.outDegreeWithoutSelfLoops=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.outDegreeWithoutSelfLoops: could not find the "'.concat(e,'" node in the graph.'));return"undirected"===this.type?0:t.outDegree-t.directedLoops},o.directedDegreeWithoutSelfLoops=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.directedDegreeWithoutSelfLoops: could not find the "'.concat(e,'" node in the graph.'));return"undirected"===this.type?0:t.inDegree+t.outDegree-2*t.directedLoops},o.undirectedDegreeWithoutSelfLoops=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.undirectedDegreeWithoutSelfLoops: could not find the "'.concat(e,'" node in the graph.'));return"directed"===this.type?0:t.undirectedDegree-2*t.undirectedLoops},o.inboundDegreeWithoutSelfLoops=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.inboundDegreeWithoutSelfLoops: could not find the "'.concat(e,'" node in the graph.'));var n=0,i=0;return"directed"!==this.type&&(n+=t.undirectedDegree,i+=2*t.undirectedLoops),"undirected"!==this.type&&(n+=t.inDegree,i+=t.directedLoops),n-i},o.outboundDegreeWithoutSelfLoops=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.outboundDegreeWithoutSelfLoops: could not find the "'.concat(e,'" node in the graph.'));var n=0,i=0;return"directed"!==this.type&&(n+=t.undirectedDegree,i+=2*t.undirectedLoops),"undirected"!==this.type&&(n+=t.outDegree,i+=t.directedLoops),n-i},o.degreeWithoutSelfLoops=function(e){e=""+e;var t=this._nodes.get(e);if(!t)throw new V('Graph.degreeWithoutSelfLoops: could not find the "'.concat(e,'" node in the graph.'));var n=0,i=0;return"directed"!==this.type&&(n+=t.undirectedDegree,i+=2*t.undirectedLoops),"undirected"!==this.type&&(n+=t.inDegree+t.outDegree,i+=2*t.directedLoops),n-i},o.source=function(e){e=""+e;var t=this._edges.get(e);if(!t)throw new V('Graph.source: could not find the "'.concat(e,'" edge in the graph.'));return t.source.key},o.target=function(e){e=""+e;var t=this._edges.get(e);if(!t)throw new V('Graph.target: could not find the "'.concat(e,'" edge in the graph.'));return t.target.key},o.extremities=function(e){e=""+e;var t=this._edges.get(e);if(!t)throw new V('Graph.extremities: could not find the "'.concat(e,'" edge in the graph.'));return[t.source.key,t.target.key]},o.opposite=function(e,t){e=""+e,t=""+t;var n=this._edges.get(t);if(!n)throw new V('Graph.opposite: could not find the "'.concat(t,'" edge in the graph.'));var i=n.source.key,o=n.target.key;if(e===i)return o;if(e===o)return i;throw new V('Graph.opposite: the "'.concat(e,'" node is not attached to the "').concat(t,'" edge (').concat(i,", ").concat(o,")."))},o.hasExtremity=function(e,t){e=""+e,t=""+t;var n=this._edges.get(e);if(!n)throw new V('Graph.hasExtremity: could not find the "'.concat(e,'" edge in the graph.'));return n.source.key===t||n.target.key===t},o.isUndirected=function(e){e=""+e;var t=this._edges.get(e);if(!t)throw new V('Graph.isUndirected: could not find the "'.concat(e,'" edge in the graph.'));return t.undirected},o.isDirected=function(e){e=""+e;var t=this._edges.get(e);if(!t)throw new V('Graph.isDirected: could not find the "'.concat(e,'" edge in the graph.'));return!t.undirected},o.isSelfLoop=function(e){e=""+e;var t=this._edges.get(e);if(!t)throw new V('Graph.isSelfLoop: could not find the "'.concat(e,'" edge in the graph.'));return t.source===t.target},o.addNode=function(e,t){var n=function(e,t,n){if(n&&!c(n))throw new B('Graph.addNode: invalid attributes. Expecting an object but got "'.concat(n,'"'));if(t=""+t,n=n||{},e._nodes.has(t))throw new U('Graph.addNode: the "'.concat(t,'" node already exist in the graph.'));var i=new e.NodeDataClass(t,n);return e._nodes.set(t,i),e.emit("nodeAdded",{key:t,attributes:n}),i}(this,e,t);return n.key},o.mergeNode=function(e,t){if(t&&!c(t))throw new B('Graph.mergeNode: invalid attributes. Expecting an object but got "'.concat(t,'"'));e=""+e,t=t||{};var n=this._nodes.get(e);return n?(t&&(a(n.attributes,t),this.emit("nodeAttributesUpdated",{type:"merge",key:e,attributes:n.attributes,data:t})),[e,!1]):(n=new this.NodeDataClass(e,t),this._nodes.set(e,n),this.emit("nodeAdded",{key:e,attributes:t}),[e,!0])},o.updateNode=function(e,t){if(t&&"function"!=typeof t)throw new B('Graph.updateNode: invalid updater function. Expecting a function but got "'.concat(t,'"'));e=""+e;var n=this._nodes.get(e);if(n){if(t){var i=n.attributes;n.attributes=t(i),this.emit("nodeAttributesUpdated",{type:"replace",key:e,attributes:n.attributes})}return[e,!1]}var o=t?t({}):{};return n=new this.NodeDataClass(e,o),this._nodes.set(e,n),this.emit("nodeAdded",{key:e,attributes:o}),[e,!0]},o.dropNode=function(e){e=""+e;var t,n=this._nodes.get(e);if(!n)throw new V('Graph.dropNode: could not find the "'.concat(e,'" node in the graph.'));if("undirected"!==this.type){for(var i in n.out){t=n.out[i];do{Me(this,t),t=t.next}while(t)}for(var o in n.in){t=n.in[o];do{Me(this,t),t=t.next}while(t)}}if("directed"!==this.type)for(var s in n.undirected){t=n.undirected[s];do{Me(this,t),t=t.next}while(t)}this._nodes.delete(e),this.emit("nodeDropped",{key:e,attributes:n.attributes})},o.dropEdge=function(e){var t;if(arguments.length>1){var n=""+arguments[0],i=""+arguments[1];if(!(t=l(this,n,i,this.type)))throw new V('Graph.dropEdge: could not find the "'.concat(n,'" -> "').concat(i,'" edge in the graph.'))}else if(e=""+e,!(t=this._edges.get(e)))throw new V('Graph.dropEdge: could not find the "'.concat(e,'" edge in the graph.'));return Me(this,t),this},o.dropDirectedEdge=function(e,t){if(arguments.length<2)throw new U("Graph.dropDirectedEdge: it does not make sense to try and drop a directed edge by key. What if the edge with this key is undirected? Use #.dropEdge for this purpose instead.");if(this.multi)throw new U("Graph.dropDirectedEdge: cannot use a {source,target} combo when dropping an edge in a MultiGraph since we cannot infer the one you want to delete as there could be multiple ones.");var n=l(this,e=""+e,t=""+t,"directed");if(!n)throw new V('Graph.dropDirectedEdge: could not find a "'.concat(e,'" -> "').concat(t,'" edge in the graph.'));return Me(this,n),this},o.dropUndirectedEdge=function(e,t){if(arguments.length<2)throw new U("Graph.dropUndirectedEdge: it does not make sense to drop a directed edge by key. What if the edge with this key is undirected? Use #.dropEdge for this purpose instead.");if(this.multi)throw new U("Graph.dropUndirectedEdge: cannot use a {source,target} combo when dropping an edge in a MultiGraph since we cannot infer the one you want to delete as there could be multiple ones.");var n=l(this,e,t,"undirected");if(!n)throw new V('Graph.dropUndirectedEdge: could not find a "'.concat(e,'" -> "').concat(t,'" edge in the graph.'));return Me(this,n),this},o.clear=function(){this._edges.clear(),this._nodes.clear(),this._resetInstanceCounters(),this.emit("cleared")},o.clearEdges=function(){for(var e,t=this._nodes.values();!0!==(e=t.next()).done;)e.value.clear();this._edges.clear(),this._resetInstanceCounters(),this.emit("edgesCleared")},o.getAttribute=function(e){return this._attributes[e]},o.getAttributes=function(){return this._attributes},o.hasAttribute=function(e){return this._attributes.hasOwnProperty(e)},o.setAttribute=function(e,t){return this._attributes[e]=t,this.emit("attributesUpdated",{type:"set",attributes:this._attributes,name:e}),this},o.updateAttribute=function(e,t){if("function"!=typeof t)throw new B("Graph.updateAttribute: updater should be a function.");var n=this._attributes[e];return this._attributes[e]=t(n),this.emit("attributesUpdated",{type:"set",attributes:this._attributes,name:e}),this},o.removeAttribute=function(e){return delete this._attributes[e],this.emit("attributesUpdated",{type:"remove",attributes:this._attributes,name:e}),this},o.replaceAttributes=function(e){if(!c(e))throw new B("Graph.replaceAttributes: provided attributes are not a plain object.");return this._attributes=e,this.emit("attributesUpdated",{type:"replace",attributes:this._attributes}),this},o.mergeAttributes=function(e){if(!c(e))throw new B("Graph.mergeAttributes: provided attributes are not a plain object.");return a(this._attributes,e),this.emit("attributesUpdated",{type:"merge",attributes:this._attributes,data:e}),this},o.updateAttributes=function(e){if("function"!=typeof e)throw new B("Graph.updateAttributes: provided updater is not a function.");return this._attributes=e(this._attributes),this.emit("attributesUpdated",{type:"update",attributes:this._attributes}),this},o.updateEachNodeAttributes=function(e,t){if("function"!=typeof e)throw new B("Graph.updateEachNodeAttributes: expecting an updater function.");if(t&&!m(t))throw new B("Graph.updateEachNodeAttributes: invalid hints. Expecting an object having the following shape: {attributes?: [string]}");for(var n,i,o=this._nodes.values();!0!==(n=o.next()).done;)(i=n.value).attributes=e(i.key,i.attributes);this.emit("eachNodeAttributesUpdated",{hints:t||null})},o.updateEachEdgeAttributes=function(e,t){if("function"!=typeof e)throw new B("Graph.updateEachEdgeAttributes: expecting an updater function.");if(t&&!m(t))throw new B("Graph.updateEachEdgeAttributes: invalid hints. Expecting an object having the following shape: {attributes?: [string]}");for(var n,i,o,s,r=this._edges.values();!0!==(n=r.next()).done;)o=(i=n.value).source,s=i.target,i.attributes=e(i.key,i.attributes,o.key,s.key,o.attributes,s.attributes,i.undirected);this.emit("eachEdgeAttributesUpdated",{hints:t||null})},o.forEachAdjacencyEntry=function(e){if("function"!=typeof e)throw new B("Graph.forEachAdjacencyEntry: expecting a callback.");ge(!1,!1,!1,this,e)},o.forEachAdjacencyEntryWithOrphans=function(e){if("function"!=typeof e)throw new B("Graph.forEachAdjacencyEntryWithOrphans: expecting a callback.");ge(!1,!1,!0,this,e)},o.forEachAssymetricAdjacencyEntry=function(e){if("function"!=typeof e)throw new B("Graph.forEachAssymetricAdjacencyEntry: expecting a callback.");ge(!1,!0,!1,this,e)},o.forEachAssymetricAdjacencyEntryWithOrphans=function(e){if("function"!=typeof e)throw new B("Graph.forEachAssymetricAdjacencyEntryWithOrphans: expecting a callback.");ge(!1,!0,!0,this,e)},o.nodes=function(){return"function"==typeof Array.from?Array.from(this._nodes.keys()):k(this._nodes.keys(),this._nodes.size)},o.forEachNode=function(e){if("function"!=typeof e)throw new B("Graph.forEachNode: expecting a callback.");for(var t,n,i=this._nodes.values();!0!==(t=i.next()).done;)e((n=t.value).key,n.attributes)},o.findNode=function(e){if("function"!=typeof e)throw new B("Graph.findNode: expecting a callback.");for(var t,n,i=this._nodes.values();!0!==(t=i.next()).done;)if(e((n=t.value).key,n.attributes))return n.key},o.mapNodes=function(e){if("function"!=typeof e)throw new B("Graph.mapNode: expecting a callback.");for(var t,n,i=this._nodes.values(),o=new Array(this.order),s=0;!0!==(t=i.next()).done;)n=t.value,o[s++]=e(n.key,n.attributes);return o},o.someNode=function(e){if("function"!=typeof e)throw new B("Graph.someNode: expecting a callback.");for(var t,n,i=this._nodes.values();!0!==(t=i.next()).done;)if(e((n=t.value).key,n.attributes))return!0;return!1},o.everyNode=function(e){if("function"!=typeof e)throw new B("Graph.everyNode: expecting a callback.");for(var t,n,i=this._nodes.values();!0!==(t=i.next()).done;)if(!e((n=t.value).key,n.attributes))return!1;return!0},o.filterNodes=function(e){if("function"!=typeof e)throw new B("Graph.filterNodes: expecting a callback.");for(var t,n,i=this._nodes.values(),o=[];!0!==(t=i.next()).done;)e((n=t.value).key,n.attributes)&&o.push(n.key);return o},o.reduceNodes=function(e,t){if("function"!=typeof e)throw new B("Graph.reduceNodes: expecting a callback.");if(arguments.length<2)throw new B("Graph.reduceNodes: missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array.");for(var n,i,o=t,s=this._nodes.values();!0!==(n=s.next()).done;)o=e(o,(i=n.value).key,i.attributes);return o},o.nodeEntries=function(){var e=this._nodes.values();return new _(function(){var t=e.next();if(t.done)return t;var n=t.value;return{value:{node:n.key,attributes:n.attributes},done:!1}})},o.export=function(){var e=this,t=new Array(this._nodes.size),n=0;this._nodes.forEach(function(e,i){t[n++]=function(e,t){var n={key:e};return u(t.attributes)||(n.attributes=a({},t.attributes)),n}(i,e)});var i=new Array(this._edges.size);return n=0,this._edges.forEach(function(t,o){i[n++]=function(e,t,n){var i={key:t,source:n.source.key,target:n.target.key};return u(n.attributes)||(i.attributes=a({},n.attributes)),"mixed"===e&&n.undirected&&(i.undirected=!0),i}(e.type,o,t)}),{options:{type:this.type,multi:this.multi,allowSelfLoops:this.allowSelfLoops},attributes:this.getAttributes(),nodes:t,edges:i}},o.import=function(e){var t,n,o,s,r,a=this,l=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(e instanceof i)return e.forEachNode(function(e,t){l?a.mergeNode(e,t):a.addNode(e,t)}),e.forEachEdge(function(e,t,n,i,o,s,r){l?r?a.mergeUndirectedEdgeWithKey(e,n,i,t):a.mergeDirectedEdgeWithKey(e,n,i,t):r?a.addUndirectedEdgeWithKey(e,n,i,t):a.addDirectedEdgeWithKey(e,n,i,t)}),this;if(!c(e))throw new B("Graph.import: invalid argument. Expecting a serialized graph or, alternatively, a Graph instance.");if(e.attributes){if(!c(e.attributes))throw new B("Graph.import: invalid attributes. Expecting a plain object.");l?this.mergeAttributes(e.attributes):this.replaceAttributes(e.attributes)}if(e.nodes){if(o=e.nodes,!Array.isArray(o))throw new B("Graph.import: invalid nodes. Expecting an array.");for(t=0,n=o.length;t<n;t++){fe(s=o[t]);var u=s,h=u.key,d=u.attributes;l?this.mergeNode(h,d):this.addNode(h,d)}}if(e.edges){var m=!1;if("undirected"===this.type&&(m=!0),o=e.edges,!Array.isArray(o))throw new B("Graph.import: invalid edges. Expecting an array.");for(t=0,n=o.length;t<n;t++){ye(r=o[t]);var p=r,g=p.source,f=p.target,y=p.attributes,b=p.undirected,w=void 0===b?m:b;"key"in r?(l?w?this.mergeUndirectedEdgeWithKey:this.mergeDirectedEdgeWithKey:w?this.addUndirectedEdgeWithKey:this.addDirectedEdgeWithKey).call(this,r.key,g,f,y):(l?w?this.mergeUndirectedEdge:this.mergeDirectedEdge:w?this.addUndirectedEdge:this.addDirectedEdge).call(this,g,f,y)}}return this},o.nullCopy=function(e){var t=new i(a({},this._options,e));return t.replaceAttributes(a({},this.getAttributes())),t},o.emptyCopy=function(e){var t=this.nullCopy(e);return this._nodes.forEach(function(e,n){var i=a({},e.attributes);e=new t.NodeDataClass(n,i),t._nodes.set(n,e)}),t},o.copy=function(e){if("string"==typeof(e=e||{}).type&&e.type!==this.type&&"mixed"!==e.type)throw new U('Graph.copy: cannot create an incompatible copy from "'.concat(this.type,'" type to "').concat(e.type,'" because this would mean losing information about the current graph.'));if("boolean"==typeof e.multi&&e.multi!==this.multi&&!0!==e.multi)throw new U("Graph.copy: cannot create an incompatible copy by downgrading a multi graph to a simple one because this would mean losing information about the current graph.");if("boolean"==typeof e.allowSelfLoops&&e.allowSelfLoops!==this.allowSelfLoops&&!0!==e.allowSelfLoops)throw new U("Graph.copy: cannot create an incompatible copy from a graph allowing self loops to one that does not because this would mean losing information about the current graph.");for(var t,n,i=this.emptyCopy(e),o=this._edges.values();!0!==(t=o.next()).done;)Ee(i,"copy",!1,(n=t.value).undirected,n.key,n.source.key,n.target.key,a({},n.attributes));return i},o.toJSON=function(){return this.export()},o.toString=function(){return"[object Graph]"},o.inspect=function(){var t=this,n={};this._nodes.forEach(function(e,t){n[t]=e.attributes});var i={},o={};this._edges.forEach(function(e,n){var s,r=e.undirected?"--":"->",a="",l=e.source.key,c=e.target.key;e.undirected&&l>c&&(s=l,l=c,c=s);var u="(".concat(l,")").concat(r,"(").concat(c,")");n.startsWith("geid_")?t.multi&&(void 0===o[u]?o[u]=0:o[u]++,a+="".concat(o[u],". ")):a+="[".concat(n,"]: "),i[a+=u]=e.attributes});var s={};for(var r in this)this.hasOwnProperty(r)&&!Ce.has(r)&&"function"!=typeof this[r]&&"symbol"!==e(r)&&(s[r]=this[r]);return s.attributes=this._attributes,s.nodes=n,s.edges=i,h(s,"constructor",this.constructor),s},i}(g.exports.EventEmitter);"undefined"!=typeof Symbol&&(xe.prototype[Symbol.for("nodejs.util.inspect.custom")]=xe.prototype.inspect),[{name:function(e){return"".concat(e,"Edge")},generateKey:!0},{name:function(e){return"".concat(e,"DirectedEdge")},generateKey:!0,type:"directed"},{name:function(e){return"".concat(e,"UndirectedEdge")},generateKey:!0,type:"undirected"},{name:function(e){return"".concat(e,"EdgeWithKey")}},{name:function(e){return"".concat(e,"DirectedEdgeWithKey")},type:"directed"},{name:function(e){return"".concat(e,"UndirectedEdgeWithKey")},type:"undirected"}].forEach(function(e){["add","merge","update"].forEach(function(t){var n=e.name(t),i="add"===t?Ee:Se;e.generateKey?xe.prototype[n]=function(o,s,r){return i(this,n,!0,"undirected"===(e.type||this.type),null,o,s,r,"update"===t)}:xe.prototype[n]=function(o,s,r,a){return i(this,n,!1,"undirected"===(e.type||this.type),o,s,r,a,"update"===t)}})}),function(e){z.forEach(function(t){var n=t.name,i=t.attacher;i(e,n("Node"),0),i(e,n("Source"),1),i(e,n("Target"),2),i(e,n("Opposite"),3)})}(xe),function(e){Z.forEach(function(t){var n=t.name,i=t.attacher;i(e,n("Edge"),"mixed"),i(e,n("DirectedEdge"),"directed"),i(e,n("UndirectedEdge"),"undirected")})}(xe),function(e){ee.forEach(function(t){!function(e,t){var n=t.name,i=t.type,o=t.direction;e.prototype[n]=function(e,t){if("mixed"!==i&&"mixed"!==this.type&&i!==this.type)return[];if(!arguments.length)return function(e,t){if(0===e.size)return[];if("mixed"===t||t===e.type)return"function"==typeof Array.from?Array.from(e._edges.keys()):k(e._edges.keys(),e._edges.size);for(var n,i,o="undirected"===t?e.undirectedSize:e.directedSize,s=new Array(o),r="undirected"===t,a=e._edges.values(),l=0;!0!==(n=a.next()).done;)(i=n.value).undirected===r&&(s[l++]=i.key);return s}(this,i);if(1===arguments.length){e=""+e;var s=this._nodes.get(e);if(void 0===s)throw new V("Graph.".concat(n,': could not find the "').concat(e,'" node in the graph.'));return function(e,t,n,i){var o=[];return le(!1,e,t,n,i,function(e){o.push(e)}),o}(this.multi,"mixed"===i?this.type:i,o,s)}if(2===arguments.length){e=""+e,t=""+t;var r=this._nodes.get(e);if(!r)throw new V("Graph.".concat(n,': could not find the "').concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new V("Graph.".concat(n,': could not find the "').concat(t,'" target node in the graph.'));return function(e,t,n,i,o){var s=[];return ce(!1,e,t,n,i,o,function(e){s.push(e)}),s}(i,this.multi,o,r,t)}throw new B("Graph.".concat(n,": too many arguments (expecting 0, 1 or 2 and got ").concat(arguments.length,")."))}}(e,t),function(e,t){var n=t.name,i=t.type,o=t.direction,s="forEach"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[s]=function(e,t,n){if("mixed"===i||"mixed"===this.type||i===this.type){if(1===arguments.length)return ae(!1,this,i,n=e);if(2===arguments.length){e=""+e,n=t;var r=this._nodes.get(e);if(void 0===r)throw new V("Graph.".concat(s,': could not find the "').concat(e,'" node in the graph.'));return le(!1,this.multi,"mixed"===i?this.type:i,o,r,n)}if(3===arguments.length){e=""+e,t=""+t;var a=this._nodes.get(e);if(!a)throw new V("Graph.".concat(s,': could not find the "').concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new V("Graph.".concat(s,': could not find the "').concat(t,'" target node in the graph.'));return ce(!1,i,this.multi,o,a,t,n)}throw new B("Graph.".concat(s,": too many arguments (expecting 1, 2 or 3 and got ").concat(arguments.length,")."))}};var r="map"+n[0].toUpperCase()+n.slice(1);e.prototype[r]=function(){var e,t=Array.prototype.slice.call(arguments),n=t.pop();if(0===t.length){var o=0;"directed"!==i&&(o+=this.undirectedSize),"undirected"!==i&&(o+=this.directedSize),e=new Array(o);var r=0;t.push(function(t,i,o,s,a,l,c){e[r++]=n(t,i,o,s,a,l,c)})}else e=[],t.push(function(t,i,o,s,r,a,l){e.push(n(t,i,o,s,r,a,l))});return this[s].apply(this,t),e};var a="filter"+n[0].toUpperCase()+n.slice(1);e.prototype[a]=function(){var e=Array.prototype.slice.call(arguments),t=e.pop(),n=[];return e.push(function(e,i,o,s,r,a,l){t(e,i,o,s,r,a,l)&&n.push(e)}),this[s].apply(this,e),n};var l="reduce"+n[0].toUpperCase()+n.slice(1);e.prototype[l]=function(){var e,t,n=Array.prototype.slice.call(arguments);if(n.length<2||n.length>4)throw new B("Graph.".concat(l,": invalid number of arguments (expecting 2, 3 or 4 and got ").concat(n.length,")."));if("function"==typeof n[n.length-1]&&"function"!=typeof n[n.length-2])throw new B("Graph.".concat(l,": missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array."));2===n.length?(e=n[0],t=n[1],n=[]):3===n.length?(e=n[1],t=n[2],n=[n[0]]):4===n.length&&(e=n[2],t=n[3],n=[n[0],n[1]]);var i=t;return n.push(function(t,n,o,s,r,a,l){i=e(i,t,n,o,s,r,a,l)}),this[s].apply(this,n),i}}(e,t),function(e,t){var n=t.name,i=t.type,o=t.direction,s="find"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[s]=function(e,t,n){if("mixed"!==i&&"mixed"!==this.type&&i!==this.type)return!1;if(1===arguments.length)return ae(!0,this,i,n=e);if(2===arguments.length){e=""+e,n=t;var r=this._nodes.get(e);if(void 0===r)throw new V("Graph.".concat(s,': could not find the "').concat(e,'" node in the graph.'));return le(!0,this.multi,"mixed"===i?this.type:i,o,r,n)}if(3===arguments.length){e=""+e,t=""+t;var a=this._nodes.get(e);if(!a)throw new V("Graph.".concat(s,': could not find the "').concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new V("Graph.".concat(s,': could not find the "').concat(t,'" target node in the graph.'));return ce(!0,i,this.multi,o,a,t,n)}throw new B("Graph.".concat(s,": too many arguments (expecting 1, 2 or 3 and got ").concat(arguments.length,")."))};var r="some"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[r]=function(){var e=Array.prototype.slice.call(arguments),t=e.pop();return e.push(function(e,n,i,o,s,r,a){return t(e,n,i,o,s,r,a)}),!!this[s].apply(this,e)};var a="every"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[a]=function(){var e=Array.prototype.slice.call(arguments),t=e.pop();return e.push(function(e,n,i,o,s,r,a){return!t(e,n,i,o,s,r,a)}),!this[s].apply(this,e)}}(e,t),function(e,t){var n=t.name,i=t.type,o=t.direction,s=n.slice(0,-1)+"Entries";e.prototype[s]=function(e,t){if("mixed"!==i&&"mixed"!==this.type&&i!==this.type)return _.empty();if(!arguments.length)return function(e,t){if(0===e.size)return _.empty();var n="mixed"!==t&&t!==e.type,i="undirected"===t,o=e._edges.values();return new _(function(){for(var e,t;;){if((e=o.next()).done)return e;if(t=e.value,!n||t.undirected===i)break}return{value:{edge:t.key,attributes:t.attributes,source:t.source.key,target:t.target.key,sourceAttributes:t.source.attributes,targetAttributes:t.target.attributes,undirected:t.undirected},done:!1}})}(this,i);if(1===arguments.length){e=""+e;var n=this._nodes.get(e);if(!n)throw new V("Graph.".concat(s,': could not find the "').concat(e,'" node in the graph.'));return function(e,t,n){var i=_.empty();return"undirected"!==e&&("out"!==t&&void 0!==n.in&&(i=J(i,ie(n.in))),"in"!==t&&void 0!==n.out&&(i=J(i,ie(n.out,t?void 0:n.key)))),"directed"!==e&&void 0!==n.undirected&&(i=J(i,ie(n.undirected))),i}(i,o,n)}if(2===arguments.length){e=""+e,t=""+t;var r=this._nodes.get(e);if(!r)throw new V("Graph.".concat(s,': could not find the "').concat(e,'" source node in the graph.'));if(!this._nodes.has(t))throw new V("Graph.".concat(s,': could not find the "').concat(t,'" target node in the graph.'));return function(e,t,n,i){var o=_.empty();return"undirected"!==e&&(void 0!==n.in&&"out"!==t&&i in n.in&&(o=J(o,re(n.in,i))),void 0!==n.out&&"in"!==t&&i in n.out&&(t||n.key!==i)&&(o=J(o,re(n.out,i)))),"directed"!==e&&void 0!==n.undirected&&i in n.undirected&&(o=J(o,re(n.undirected,i))),o}(i,o,r,t)}throw new B("Graph.".concat(s,": too many arguments (expecting 0, 1 or 2 and got ").concat(arguments.length,")."))}}(e,t)})}(xe),function(e){ue.forEach(function(t){(function(e,t){var n=t.name,i=t.type,o=t.direction;e.prototype[n]=function(e){if("mixed"!==i&&"mixed"!==this.type&&i!==this.type)return[];e=""+e;var t=this._nodes.get(e);if(void 0===t)throw new V("Graph.".concat(n,': could not find the "').concat(e,'" node in the graph.'));return function(e,t,n){if("mixed"!==e){if("undirected"===e)return Object.keys(n.undirected);if("string"==typeof t)return Object.keys(n[t])}var i=[];return me(!1,e,t,n,function(e){i.push(e)}),i}("mixed"===i?this.type:i,o,t)}})(e,t),function(e,t){var n=t.name,i=t.type,o=t.direction,s="forEach"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[s]=function(e,t){if("mixed"===i||"mixed"===this.type||i===this.type){e=""+e;var n=this._nodes.get(e);if(void 0===n)throw new V("Graph.".concat(s,': could not find the "').concat(e,'" node in the graph.'));me(!1,"mixed"===i?this.type:i,o,n,t)}};var r="map"+n[0].toUpperCase()+n.slice(1);e.prototype[r]=function(e,t){var n=[];return this[s](e,function(e,i){n.push(t(e,i))}),n};var a="filter"+n[0].toUpperCase()+n.slice(1);e.prototype[a]=function(e,t){var n=[];return this[s](e,function(e,i){t(e,i)&&n.push(e)}),n};var l="reduce"+n[0].toUpperCase()+n.slice(1);e.prototype[l]=function(e,t,n){if(arguments.length<3)throw new B("Graph.".concat(l,": missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array."));var i=n;return this[s](e,function(e,n){i=t(i,e,n)}),i}}(e,t),function(e,t){var n=t.name,i=t.type,o=t.direction,s=n[0].toUpperCase()+n.slice(1,-1),r="find"+s;e.prototype[r]=function(e,t){if("mixed"===i||"mixed"===this.type||i===this.type){e=""+e;var n=this._nodes.get(e);if(void 0===n)throw new V("Graph.".concat(r,': could not find the "').concat(e,'" node in the graph.'));return me(!0,"mixed"===i?this.type:i,o,n,t)}};var a="some"+s;e.prototype[a]=function(e,t){return!!this[r](e,t)};var l="every"+s;e.prototype[l]=function(e,t){return!this[r](e,function(e,n){return!t(e,n)})}}(e,t),function(e,t){var n=t.name,i=t.type,o=t.direction,s=n.slice(0,-1)+"Entries";e.prototype[s]=function(e){if("mixed"!==i&&"mixed"!==this.type&&i!==this.type)return _.empty();e=""+e;var t=this._nodes.get(e);if(void 0===t)throw new V("Graph.".concat(s,': could not find the "').concat(e,'" node in the graph.'));return function(e,t,n){if("mixed"!==e){if("undirected"===e)return pe(null,n,n.undirected);if("string"==typeof t)return pe(null,n,n[t])}var i=_.empty(),o=new he;return"undirected"!==e&&("out"!==t&&(i=J(i,pe(o,n,n.in))),"in"!==t&&(i=J(i,pe(o,n,n.out)))),"directed"!==e&&(i=J(i,pe(o,n,n.undirected))),i}("mixed"===i?this.type:i,o,t)}}(e,t)})}(xe);var Pe=function(e){function n(t){var n=a({type:"directed"},t);if("multi"in n&&!1!==n.multi)throw new B("DirectedGraph.from: inconsistent indication that the graph should be multi in given options!");if("directed"!==n.type)throw new B('DirectedGraph.from: inconsistent "'+n.type+'" type in given options!');return e.call(this,n)||this}return t(n,e),n}(xe),Le=function(e){function n(t){var n=a({type:"undirected"},t);if("multi"in n&&!1!==n.multi)throw new B("UndirectedGraph.from: inconsistent indication that the graph should be multi in given options!");if("undirected"!==n.type)throw new B('UndirectedGraph.from: inconsistent "'+n.type+'" type in given options!');return e.call(this,n)||this}return t(n,e),n}(xe),Ie=function(e){function n(t){var n=a({multi:!0},t);if("multi"in n&&!0!==n.multi)throw new B("MultiGraph.from: inconsistent indication that the graph should be simple in given options!");return e.call(this,n)||this}return t(n,e),n}(xe),_e=function(e){function n(t){var n=a({type:"directed",multi:!0},t);if("multi"in n&&!0!==n.multi)throw new B("MultiDirectedGraph.from: inconsistent indication that the graph should be simple in given options!");if("directed"!==n.type)throw new B('MultiDirectedGraph.from: inconsistent "'+n.type+'" type in given options!');return e.call(this,n)||this}return t(n,e),n}(xe),Ne=function(e){function n(t){var n=a({type:"undirected",multi:!0},t);if("multi"in n&&!0!==n.multi)throw new B("MultiUndirectedGraph.from: inconsistent indication that the graph should be simple in given options!");if("undirected"!==n.type)throw new B('MultiUndirectedGraph.from: inconsistent "'+n.type+'" type in given options!');return e.call(this,n)||this}return t(n,e),n}(xe);function Re(e){e.from=function(t,n){var i=a({},t.options,n),o=new e(i);return o.import(t),o}}return Re(xe),Re(Pe),Re(Le),Re(Ie),Re(_e),Re(Ne),xe.Graph=xe,xe.DirectedGraph=Pe,xe.UndirectedGraph=Le,xe.MultiGraph=Ie,xe.MultiDirectedGraph=_e,xe.MultiUndirectedGraph=Ne,xe.InvalidArgumentsGraphError=B,xe.NotFoundGraphError=V,xe.UsageGraphError=U,xe}()},944(e,t){"use strict";t.Vb=void 0,t.Vb=function(e,t,n){var i=function(e,t,n){if(0===e.length||0===t.length)return 0;if(n&&!n.caseSensitive&&(e=e.toUpperCase(),t=t.toUpperCase()),e===t)return 1;for(var i=0,o=e.length,s=t.length,r=Math.floor(Math.max(o,s)/2)-1,a=new Array(o),l=new Array(s),c=0;c<o;c++)for(var u=Math.max(0,c-r);u<=Math.min(s,c+r+1);u++)if(!a[c]&&!l[u]&&e[c]===t[u]){++i,a[c]=l[u]=!0;break}if(0===i)return 0;var h=0,d=0;for(c=0;c<o;c++)if(a[c]){for(;!l[d];)d++;e.charAt(c)!==t.charAt(d++)&&h++}return(i/o+i/s+(i-(h/=2))/i)/3}(e,t,n),o=0;if(i>.7){for(var s=Math.min(e.length,t.length),r=0;e[r]===t[r]&&r<4&&r<s;)++o,r++;i+=.1*o*(1-i)}return i}},7106(e){"use strict";var t=e.exports=function(e,t,i){"function"==typeof t&&(i=t,t={}),n(t,"function"==typeof(i=t.cb||i)?i:i.pre||function(){},i.post||function(){},e,"",e)};function n(e,o,s,r,a,l,c,u,h,d){if(r&&"object"==typeof r&&!Array.isArray(r)){for(var m in o(r,a,l,c,u,h,d),r){var p=r[m];if(Array.isArray(p)){if(m in t.arrayKeywords)for(var g=0;g<p.length;g++)n(e,o,s,p[g],a+"/"+m+"/"+g,l,a,m,r,g)}else if(m in t.propsKeywords){if(p&&"object"==typeof p)for(var f in p)n(e,o,s,p[f],a+"/"+m+"/"+i(f),l,a,m,r,f)}else(m in t.keywords||e.allKeys&&!(m in t.skipKeywords))&&n(e,o,s,p,a+"/"+m,l,a,m,r)}s(r,a,l,c,u,h,d)}}function i(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},t.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0}},5072(e){"use strict";var t=[];function n(e){for(var n=-1,i=0;i<t.length;i++)if(t[i].identifier===e){n=i;break}return n}function i(e,i){for(var s={},r=[],a=0;a<e.length;a++){var l=e[a],c=i.base?l[0]+i.base:l[0],u=s[c]||0,h="".concat(c," ").concat(u);s[c]=u+1;var d=n(h),m={css:l[1],media:l[2],sourceMap:l[3],supports:l[4],layer:l[5]};if(-1!==d)t[d].references++,t[d].updater(m);else{var p=o(m,i);i.byIndex=a,t.splice(a,0,{identifier:h,updater:p,references:1})}r.push(h)}return r}function o(e,t){var n=t.domAPI(t);return n.update(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap&&t.supports===e.supports&&t.layer===e.layer)return;n.update(e=t)}else n.remove()}}e.exports=function(e,o){var s=i(e=e||[],o=o||{});return function(e){e=e||[];for(var r=0;r<s.length;r++){var a=n(s[r]);t[a].references--}for(var l=i(e,o),c=0;c<s.length;c++){var u=n(s[c]);0===t[u].references&&(t[u].updater(),t.splice(u,1))}s=l}}},7659(e){"use strict";var t={};e.exports=function(e,n){var i=function(e){if(void 0===t[e]){var n=document.querySelector(e);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(e){n=null}t[e]=n}return t[e]}(e);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(e){"use strict";e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}},5056(e,t,n){"use strict";e.exports=function(e){var t=n.nc;t&&e.setAttribute("nonce",t)}},7825(e){"use strict";e.exports=function(e){if("undefined"==typeof document)return{update:function(){},remove:function(){}};var t=e.insertStyleElement(e);return{update:function(n){!function(e,t,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))))," */")),t.styleTagTransform(i,e,t.options)}(t,e,n)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}},1113(e){"use strict";e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}},3328(e,t,n){"use strict";n.d(t,{PackageFunctions:()=>Wo,_package:()=>Uo});var i,o=n(4328),s=n(7389),r=n(6082),a=n(684),l=n(9039);!function(e){e.EUCLIDEAN="EUCLIDEAN",e.MANHATTAN="MANHATTAN"}(i||(i={}));var c=n(1858),u=n(5072),h=n.n(u),d=n(7825),m=n.n(d),p=n(7659),g=n.n(p),f=n(5056),y=n.n(f),b=n(540),w=n.n(b),v=n(1113),C=n.n(v),A=n(7939),T={};T.styleTagTransform=C(),T.setAttributes=y(),T.insert=g().bind(null,"head"),T.domAPI=m(),T.insertStyleElement=w(),h()(A.A,T),A.A&&A.A.locals&&A.A.locals;var E=function(e,t,n,i){return new(n||(n=Promise))(function(o,s){function r(e){try{l(i.next(e))}catch(e){s(e)}}function a(e){try{l(i.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};let S=null,M=null;function x(e,t){return e&&""!=e?e:t}n(2780);class P{constructor(){this.learningRate={uiName:"Learninig Rate",value:1,tooltip:"The initial learning rate for the embedding optimization"},this.nEpochs={uiName:"Epochs",value:0,tooltip:"The number of epochs to optimize embeddings via SGD. Computed automatically if set to 0"},this.nNeighbors={uiName:"Neighbors",value:15,tooltip:"The number of nearest neighbors to construct the fuzzy manifold"},this.spread={uiName:"Spread",value:1,tooltip:"The effective scale of embedded points, used with min distance to control \n the clumped/dispersed nature of the embedding"},this.minDist={uiName:"Min Distance",value:.1,tooltip:"The effective minimum distance between embedded points, \n used with spread to control the clumped/dispersed nature of the embedding"},this.randomSeed={uiName:"Random Seed",value:null,tooltip:"Random seed",type:"string"},this.useWebGPU={uiName:"Use WebGPU",value:!1,tooltip:"Use WebGPU for Distance and UMAP computations",type:"boolean",disableTooltip:"WebGPU is not available"},function(){return E(this,void 0,void 0,function*(){if(!navigator.gpu)return console.error("WebGPU is not supported in this browser"),null;if(!S&&(S=yield navigator.gpu.requestAdapter(),null==S))return null;let e=null;return"info"in S&&(e=S.info),e?x(e.description,x(e.vendor,"No GPU description available")):"No GPU description available"})}().then(e=>{e?(this.useWebGPU.tooltip+=` (${e})`,this.useWebGPU.value=!0):(this.useWebGPU.value=!1,this.useWebGPU.disable=!0)})}}class L{constructor(){this.epsilon={uiName:"Epsilon",value:10,tooltip:"Epsilon is learning rate"},this.perplexity={uiName:"Perplexity",value:30,tooltip:"Roughly how many neighbors each point influences"}}}Promise.resolve(),n(934),n(8903);const I="MCL";r.SEMTYPE.MOLECULE,r.SEMTYPE.MACROMOLECULE;class _{constructor(){this.epsilon={uiName:"Epsilon",value:.01,tooltip:"Minimum distance between cluster points",min:0,max:2,step:.005},this.minPts={uiName:"Minimum points",value:4,tooltip:"Minimum number of points in cluster",min:1,max:1e3,step:1}}}class N{get algorithmOptions(){const e=this.methodsParams[this.methodInput.value],t={};return Object.keys(e).forEach(n=>{null!=e[n].value&&(t[n]=e[n].value)}),t}get dbScanOptions(){return{dbScanEpsilon:this.dbScanParams.epsilon.value??.01,dbScanMinPts:this.dbScanParams.minPts.value??4}}constructor(e={}){this.editorSettings={},this.plotEmbeddingsInput=s.input.bool("Plot embeddings",{value:!0}),this.clusterEmbeddingsInput=s.input.bool("Cluster embeddings",{value:!0}),this.preprocessingFunctionInputRoot=null,this.methods=[l.c.UMAP,l.c.T_SNE],this.columnFunctionsMap={},this.supportedFunctions={},this.availableMetrics=[],this.methodSettingsDiv=s.inputs([]),this.dbScanSettingsDiv=s.inputs([]),this.preprocessingFuncSettingsDiv=s.inputs([]),this.preprocessingFunctionSettings={},this.methodsParams={[l.c.UMAP]:new P,[l.c.T_SNE]:new L},this.dbScanParams=new _,this.editorSettings=e,this.editorSettings.enableMCL&&this.methods.push(I);const t=r.Func.find({tags:[a.GP]}),n=r.Func.find({meta:{role:a.GP}});Array.from(new Set([...t,...n])).forEach(e=>{const t=e.options.get(a.n3)??"",n=e.friendlyName??e.name,i=e.options.get(a.C0)??"",o=e.options.get(a._X)??"",s=e.options.get(a.Gi)??"";this.editorSettings.semtype&&!t.includes(this.editorSettings.semtype)||this.editorSettings.type&&!i.includes(this.editorSettings.type)||this.editorSettings.units&&!o.includes(this.editorSettings.units)||(this.supportedFunctions[n]={func:e,semTypes:t?t.split(","):[],types:i?i.split(","):[],units:o?o.split(","):[],distanceFunctions:s?s.split(","):[]})}),this.tableInput=s.input.table("Table",{value:o.shell.tv.dataFrame,items:o.shell.tables,onValueChanged:()=>{this.onTableInputChanged()}}),this.onTableInputChanged(),this.regenerateColInput(),this.onColumnInputChanged();let i=!1,c=!1;this.methodInput=s.input.choice("Method",{value:l.c.UMAP,items:this.methods,onValueChanged:e=>{i&&this.createAlgorithmSettingsDiv(this.methodSettingsDiv,this.methodsParams[e])}}),this.methodSettingsIcon=s.icons.settings(()=>{i=!i,i?this.createAlgorithmSettingsDiv(this.methodSettingsDiv,this.methodsParams[this.methodInput.value]):s.empty(this.methodSettingsDiv)},"Modify methods parameters"),this.dbScanSettingsIcon=s.icons.settings(()=>{c=!c,c?this.createAlgorithmSettingsDiv(this.dbScanSettingsDiv,this.dbScanParams):s.empty(this.dbScanSettingsDiv)},"Modify clustering parameters"),this.clusterEmbeddingsInput.classList.add("ml-dim-reduction-settings-input"),this.clusterEmbeddingsInput.root.prepend(this.dbScanSettingsIcon),this.methodInput.root.classList.add("ml-dim-reduction-settings-input"),this.methodInput.root.prepend(this.methodSettingsIcon),this.methodSettingsDiv=s.inputs([]);const u=this.columnFunctionsMap[this.colInput.value.name];this.preprocessingFunctionInput=s.input.choice("Encoding function",{value:u[0],items:u,onValueChanged:()=>{this.onPreprocessingFunctionChanged()}});let h=!1;this.preprocessingFunctionInputRoot||(this.preprocessingFunctionInputRoot=this.preprocessingFunctionInput.root,h=!0),h||(s.empty(this.preprocessingFunctionInputRoot),Array.from(this.preprocessingFunctionInput.root.children).forEach(e=>this.preprocessingFunctionInputRoot.append(e))),this.preprocessingFunctionInputRoot.classList.add("ml-dim-reduction-settings-input");let d=!1;this.preprocessingFuncSettingsIcon=s.icons.settings(async()=>{d?s.empty(this.preprocessingFuncSettingsDiv):await this.createPreprocessingFuncParamsDiv(this.preprocessingFuncSettingsDiv,this.supportedFunctions[this.preprocessingFunctionInput.value].func),d=!d},"Modify encoding function parameters"),this.preprocessingFunctionInputRoot.prepend(this.preprocessingFuncSettingsIcon),this.similarityMetricInput=s.input.choice("Similarity",{value:"",items:[]}),this.similarityMetricInput.nullable=!1,this.similarityMetricInputRoot||(this.similarityMetricInputRoot=this.similarityMetricInput.root),this.onPreprocessingFunctionChanged()}getColInput(){const e=this.tableInput.value?.columns.toList().find(e=>!!this.columnFunctionsMap[e.name])??null,t=s.input.column("Column",{table:this.tableInput.value,value:e,nullable:!1,onValueChanged:()=>this.onColumnInputChanged(),filter:e=>!!this.columnFunctionsMap[e.name]});return this.colInputRoot||(this.colInputRoot=t.root),t}regenerateColInput(){let e=!1;this.colInputRoot&&(e=!0,s.empty(this.colInputRoot)),this.colInput=this.getColInput(),e&&Array.from(this.colInput.root.children).forEach(e=>this.colInputRoot.append(e)),this.onColumnInputChanged()}onTableInputChanged(){const e=this.tableInput.value;if(!e)return;const t=()=>{this.columnFunctionsMap={},e.columns.toList().forEach(e=>{Object.keys(this.supportedFunctions).forEach(t=>{const n=this.supportedFunctions[t].semTypes,i=this.supportedFunctions[t].types,o=this.supportedFunctions[t].units,s=!n.length||e.semType&&n.includes(e.semType),r=!i.length||i.includes(e.type),a=!o.length||e.meta.units&&o.includes(e.meta.units);s&&r&&a&&(this.columnFunctionsMap[e.name]||(this.columnFunctionsMap[e.name]=[]),this.columnFunctionsMap[e.name].push(t))})}),this.regenerateColInput()};t(),e.columns.toList().some(e=>!!e.getTag(r.Tags.SemanticDetectionDuration))||e.meta.detectSemanticTypes().then(()=>{t()})}onColumnInputChanged(){const e=this.colInput.value;if(!e)return;const t=this.columnFunctionsMap[e.name];this.preprocessingFunctionInput=s.input.choice("Preprocessing function",{value:t[0],items:t,onValueChanged:()=>{this.onPreprocessingFunctionChanged()}});let n=!1;this.preprocessingFunctionInputRoot||(this.preprocessingFunctionInputRoot=this.preprocessingFunctionInput.root,n=!0),n||(s.empty(this.preprocessingFunctionInputRoot),Array.from(this.preprocessingFunctionInput.root.children).forEach(e=>this.preprocessingFunctionInputRoot.append(e))),this.onPreprocessingFunctionChanged()}onPreprocessingFunctionChanged(){s.empty(this.preprocessingFuncSettingsDiv),this.preprocessingFunctionSettings={};const e=this.preprocessingFunctionInput.value,t=this.supportedFunctions[e].distanceFunctions;this.availableMetrics=[...t],this.similarityMetricInput=s.input.choice("Similarity",{value:this.availableMetrics[0],items:this.availableMetrics}),this.similarityMetricInput.nullable=!1,this.similarityMetricInputRoot||(this.similarityMetricInputRoot=this.similarityMetricInput.root),s.empty(this.similarityMetricInputRoot),Array.from(this.similarityMetricInput.root.children).forEach(e=>this.similarityMetricInputRoot.append(e)),this.preprocessingFuncSettingsIcon&&(this.supportedFunctions[e].func.inputs.length<3?this.preprocessingFuncSettingsIcon.style.display="none":this.preprocessingFuncSettingsIcon.style.display="flex")}createAlgorithmSettingsDiv(e,t){return s.empty(e),Object.keys(t).forEach(n=>{const i=t[n],o="string"===i.type?s.input.string(i.uiName,{value:i.value??"",onValueChanged:e=>{i.value=e}}):"boolean"===i.type?s.input.bool(i.uiName,{value:i.value??!1,onValueChanged:e=>{i.value=e}}):s.input.float(i.uiName,{value:i.value,onValueChanged:e=>{i.value=e}});e.append(o.root),i.disable?(o.enabled=!1,s.tooltip.bind(o.input??o.root,i.disableTooltip??"")):s.tooltip.bind(o.input??o.root,i.tooltip)}),e}async createPreprocessingFuncParamsDiv(e,t){if(s.empty(e),t.inputs.length<3)return s.div();const n=t.prepare(),i=await n.buildEditor(s.div());for(let o=2;o<t.inputs.length;o++){const s=t.inputs[o];(this.preprocessingFunctionSettings[s.name]||n.inputParams[t.inputs[o].name].value||s.defaultValue)&&(this.preprocessingFunctionSettings[s.name]=this.preprocessingFunctionSettings[s.name]??n.inputParams[s.name].value??s.defaultValue);const r=i.find(e=>e.property.name===s.name);r&&(null!==this.preprocessingFunctionSettings[s.name]&&void 0!==this.preprocessingFunctionSettings[s.name]&&(r.value=this.preprocessingFunctionSettings[s.name]),r.onChanged.subscribe(e=>{this.preprocessingFunctionSettings[s.name]=e}),e.append(r.root))}return e}getEditor(){return s.div([this.tableInput,this.colInputRoot,this.preprocessingFunctionInputRoot,this.preprocessingFuncSettingsDiv,this.methodInput,this.methodSettingsDiv,this.similarityMetricInputRoot,this.plotEmbeddingsInput,this.clusterEmbeddingsInput,this.dbScanSettingsDiv],{style:{minWidth:"420px"},classes:"ui-form dim-reduction-dialog-form"})}getParams(){return{table:this.tableInput.value,col:this.colInput.value,methodName:this.methodInput.value,preprocessingFunction:this.supportedFunctions[this.preprocessingFunctionInput.value].func,similarityMetric:this.similarityMetricInput.value,plotEmbeddings:this.plotEmbeddingsInput.value,clusterEmbeddings:this.clusterEmbeddingsInput.value,options:{...this.algorithmOptions,...this.dbScanOptions,preprocessingFuncArgs:this.preprocessingFunctionSettings??{}}}}getInput(){return{table:this.tableInput.value.name,col:this.colInput.value.name,methodName:this.methodInput.value,preprocessingFunction:this.preprocessingFunctionInput.value,similarityMetric:this.similarityMetricInput.value,plotEmbeddings:this.plotEmbeddingsInput.value,clusterEmbeddings:this.clusterEmbeddingsInput.value,options:{...this.algorithmOptions,...this.dbScanOptions,preprocessingFuncArgs:this.preprocessingFunctionSettings??{}}}}getStringInput(){return JSON.stringify(this.getInput())}async applyStringInput(e){try{const t=JSON.parse(e);await this.applyInput(t)}catch(e){o.shell.error("Error applying input from history"),console.error(e)}}async applyInput(e){try{const t=this.tableInput.value?.col(e.col);if(!t)throw new Error("Column not found");this.colInput.value=t,this.preprocessingFunctionInput.value=e.preprocessingFunction,this.similarityMetricInput.value=e.similarityMetric,this.plotEmbeddingsInput.value=e.plotEmbeddings,this.clusterEmbeddingsInput.value=e.clusterEmbeddings;const n=this.methodsParams[this.methodInput.value];Object.keys(n).forEach(t=>{null!=e.options[t]&&(this.methodsParams[e.methodName][t].value=e.options[t])}),this.methodInput.value=e.methodName,this.preprocessingFunctionSettings=e.options.preprocessingFuncArgs,await this.createPreprocessingFuncParamsDiv(this.preprocessingFuncSettingsDiv,this.supportedFunctions[this.preprocessingFunctionInput.value].func)}catch(e){o.shell.error("Error applying input from history"),console.error(e)}}}var R=n(9713),$=n(6295);const O=e=>null==e;function H(e,t,n,i){if(n>e[e.length-1])return;const o=e.findIndex(e=>n<e);e.pop(),e.splice(o,0,n),t.pop(),t.splice(o,0,i)}class D{constructor(e=!0,t=!0){const i=navigator.hardwareConcurrency;this._workerCount=e?Math.max(i-2,1):1,this._workers=new Array(this._workerCount).fill(null).map(()=>new Worker(new URL(n.p+n.u(793),n.b))),this._terminateOnComplete=t}async calc(e,t,n=!0,o){return await this.calcMulti([e],[t],n,[o??{}],[1],i.MANHATTAN)}async calcMulti(e,t,n=!0,o=[{}],s=[1],r=i.MANHATTAN){if(e.length<1)throw new Error("values must contain at least one array");if(t.length!==e.length||o.length!==e.length||s.length!==e.length)throw new Error("values, fnNames, weights and opts must have the same length");return new Promise(async(i,a)=>{try{const a=e[0].length,l=new Array(this._workerCount),c=a*(a-1)/2;this._workerCount=Math.min(this._workerCount,c);const u=c/this._workerCount,h=new Float32Array(c);let d=0,m=1,p=0,g=Number.MIN_VALUE;for(let n=0;n<this._workerCount;n++){const i=Math.floor(n*u),f=n===this._workerCount-1?c:Math.floor((n+1)*u),y=d,b=m;n!==this._workerCount-1&&(d=a-2-Math.floor(Math.sqrt(-8*f+4*a*(a-1)-7)/2-.5),m=f-a*d+Math.floor((d+1)*(d+2)/2)),this._workers[n].postMessage({values:e,fnNames:t,startRow:y,startCol:b,chunckSize:f-i,opts:o,weights:s,aggregationMethod:r}),l[n]=new Promise((e,t)=>{this._workers[n].onmessage=({data:{error:o,distanceMatrixData:s,min:r,max:a}})=>{this._terminateOnComplete&&setTimeout(()=>this._workers[n].terminate()),o?t(o):(h.set(s,i),r<p&&(p=r),a>g&&(g=a),e())}})}await Promise.all(l),n&&h.forEach((e,t)=>{h[t]=(e-p)/(g-p)}),i(h)}catch(e){a(e)}})}terminate(){this._workers.forEach(e=>e.terminate())}}class F{constructor(){this._workerCount=Math.max(navigator.hardwareConcurrency-2,1)}static pruneSparseMatrix(e,t=1e6){const n=200,i=new Uint32Array(n),o=e.distance.length,s=e.distance;for(let e=0;e<o;e++)i[Math.floor(s[e]*n)]++;let r=0,a=0;for(let e=0;e<n&&(r+=i[e],a=e,!(r>=t));e++);const l=new Uint32Array(r),c=new Uint32Array(r),u=new Float32Array(r),h=e.i,d=e.j;let m=0;const p=(a+1)/n;for(let e=0;e<o;e++)s[e]<p&&(l[m]=h[e],c[m]=d[e],u[m]=s[e],m++);return{i:l,j:c,distance:u}}async calcMultiColumn(e,t,o,s=[{}],r=[1],a=i.EUCLIDEAN){const l=e[0].length*(e[0].length-1)/2,c=Math.floor(l/this._workerCount),u=e[0].length>2e4?await this.getMinimalThreshold(e,t,s,r,a):0;o<u&&(console.log(`using threshold ${u}`),o=u),s.forEach((e,t)=>s[t].threshold=o);const h=new Array(this._workerCount),d=new Array(this._workerCount).fill(null).map(()=>new Worker(new URL(n.p+n.u(111),n.b)));for(let n=0;n<this._workerCount;n++)h[n]=new Promise((i,u)=>{const h=n*c,m=n===this._workerCount-1?l:(n+1)*c;m<=h&&i({i:new Int32Array(0),j:new Int32Array(0),distance:new Float32Array(0),idx:n}),d[n].postMessage({values:e,startIdx:h,endIdx:m,threshold:o,fnNames:t,opts:s,weights:r,aggregationMethod:a}),d[n].onmessage=({data:{error:e,i:t,j:o,distance:s}})=>{e?(d[n].terminate(),u(e)):(d[n].terminate(),i({i:t,j:o,distance:s,idx:n}))}});const m=await Promise.all(h),p=m.reduce((e,t)=>e+t.i.length,0),g=new Int32Array(p),f=new Int32Array(p),y=new Float32Array(p);let b=0;for(const e of m)g.set(e.i,b),f.set(e.j,b),y.set(e.distance,b),b+=e.i.length;return{i:g,j:f,distance:y}}async calc(e,t,n,i={}){return await this.calcMultiColumn([e],[t],n,[i],[1])}async getKNN(e,t,n=15,i={}){return await this.multiColumnKNN([e],[t],n,[i],[1])}async getThresholdKNN(e,t,n=.8,i={}){return await this.multiColumnThresholdKnn([e],[t],n,[i],[1])}async multiColumnThresholdKnn(e,t,o=.8,s,r,a=i.EUCLIDEAN){if(e.length!==t.length||e.length!==s.length||e.length!==r.length)throw new Error("values, distance functions, options and weights arrays should have the same length");if(e.some(t=>t.length!==e[0].length))throw new Error("all values arrays should have the same length");const l=e[0].length*(e[0].length-1)/2,c=Math.floor(l/this._workerCount),u=new Array(this._workerCount),h=new Array(this._workerCount).fill(null).map(()=>new Worker(new URL(n.p+n.u(603),n.b)));for(let n=0;n<this._workerCount;n++)u[n]=new Promise((i,u)=>{const d=n*c,m=n===this._workerCount-1?l:(n+1)*c;m<=d&&i({knnDistances:new Array(0),knnIndexes:new Array(0)}),h[n].postMessage({values:e,startIdx:d,endIdx:m,fnNames:t,opts:s,threshold:o,weights:r,aggregationMethod:a}),h[n].onmessage=({data:{error:e,knnDistances:t,knnIndexes:o}})=>{e?(h[n].terminate(),u(e)):(h[n].terminate(),i({knnDistances:t,knnIndexes:o}))}});const d=await Promise.all(u),m=new Int32Array(e[0].length);for(const t of d)for(let n=0;n<e[0].length;++n)m[n]+=t.knnIndexes[n]?.length??0;const p={knnDistances:new Array(e[0].length).fill(null).map((e,t)=>new Array(m[t])),knnIndexes:new Array(e[0].length).fill(null).map((e,t)=>new Array(m[t]))};for(const t of d)for(let n=0;n<e[0].length;++n)for(let e=0;e<(t.knnDistances[n]?.length??0);++e)p.knnDistances[n][m[n]-1]=t.knnDistances[n][e],p.knnIndexes[n][m[n]-1]=t.knnIndexes[n][e],m[n]-=1;return p}async multiColumnSingleValueKNN(e,t,o,s=15,r,a,l=i.EUCLIDEAN){if(e.length!==o.length||e.length!==r.length||e.length!==a.length)throw new Error("values, distance functions, options and weights arrays should have the same length");if(e.some(t=>t.length!==e[0].length))throw new Error("all values arrays should have the same length");const c=new Array(this._workerCount).fill(null).map(()=>new Worker(new URL(n.p+n.u(810),n.b))),u=new Array(this._workerCount),h=e[0].length,d=e.map(e=>e[t]),m=Math.ceil(h/this._workerCount);for(let t=0;t<this._workerCount;t++)u[t]=new Promise((n,i)=>{const u=t*m,p=t===this._workerCount-1?h:(t+1)*m;p<=u&&n({knnDistances:new Array(0),knnIndexes:new Array(0)}),c[t].postMessage({values:e.map(e=>e.slice(u,p)),target:d,fnNames:o,opts:r,nNeighbours:s,weights:a,aggregationMethod:l,startIdx:u}),c[t].onmessage=({data:{error:e,knnDistances:o,knnIndexes:s}})=>{e?(c[t].terminate(),i(e)):(c[t].terminate(),n({knnDistances:o,knnIndexes:s}))}});const p=await Promise.all(u),g={knnDistances:new Array(s).fill(99999),knnIndexes:new Array(s).fill(-1)};for(const e of p)for(let t=0;t<(e.knnDistances?.length??0);++t)H(g.knnDistances,g.knnIndexes,e.knnDistances[t],e.knnIndexes[t]);return g}async multiColumnKNN(e,t,o=15,s,r,a=i.EUCLIDEAN){if(e.length!==t.length||e.length!==s.length||e.length!==r.length)throw new Error("values, distance functions, options and weights arrays should have the same length");if(e.some(t=>t.length!==e[0].length))throw new Error("all values arrays should have the same length");const l=e[0].length*(e[0].length-1)/2,c=Math.floor(l/this._workerCount),u=new Array(this._workerCount),h=new Array(this._workerCount).fill(null).map(()=>new Worker(new URL(n.p+n.u(950),n.b)));for(let n=0;n<this._workerCount;n++)u[n]=new Promise((i,u)=>{const d=n*c,m=n===this._workerCount-1?l:(n+1)*c;m<=d&&i({knnDistances:new Array(0),knnIndexes:new Array(0)}),h[n].postMessage({values:e,startIdx:d,endIdx:m,fnNames:t,opts:s,nNeighbours:o,weights:r,aggregationMethod:a}),h[n].onmessage=({data:{error:e,knnDistances:t,knnIndexes:o}})=>{e?(h[n].terminate(),u(e)):(h[n].terminate(),i({knnDistances:t,knnIndexes:o}))}});const d=await Promise.all(u),m={knnDistances:new Array(e[0].length).fill(null).map(()=>new Array(o).fill(99999)),knnIndexes:new Array(e[0].length).fill(null).map(()=>new Array(o).fill(-1))};for(const t of d)for(let n=0;n<e[0].length;++n)for(let e=0;e<(t.knnDistances[n]?.length??0);++e)H(m.knnDistances[n],m.knnIndexes[n],t.knnDistances[n][e],t.knnIndexes[n][e]);return m}async getSampleDistances(e,t,o=[],s,r=i.EUCLIDEAN){const a=new Array(this._workerCount).fill(null).map(()=>new Worker(new URL(n.p+n.u(778),n.b)));try{const n=e[0].length*(e[0].length-1)/2,i=Math.floor(n/this._workerCount),l=1e6,c=Math.max(Math.min(n/1e3,l),Math.min(n,l)),u=Math.floor(c/this._workerCount),h=new Array(this._workerCount);for(let l=0;l<this._workerCount;l++)h[l]=new Promise((c,h)=>{const d=l*i,m=l===this._workerCount-1?n:(l+1)*i;a[l].postMessage({values:e,startIdx:d,endIdx:m,sampleLength:u,fnNames:t,opts:o,weights:s,aggregationMethod:r}),a[l].onmessage=({data:{error:e,distance:t}})=>{a[l].terminate(),e?h(e):c({distance:t})}});const d=await Promise.all(h),m=d.reduce((e,t)=>e+t.distance.length,0),p=new Float32Array(m);let g=0;for(const e of d)p.set(e.distance,g),g+=e.distance.length;return p.sort(),p}catch(e){return a?.forEach(e=>e?.terminate()),console.error(e),new Float32Array(1).fill(.5)}}async getMinimalThreshold(e,t,n=[],o,s=i.EUCLIDEAN){try{const i=e.length*(e.length-1)/2,r=await this.getSampleDistances(e,t,n,o,s);return 1-r[Math.floor(7e7/i*r.length)]}catch(e){return console.error(e),.5}}static calcSync(e,t,n,i){const o=[],s=[],r=[];let a=0,l=0,c=0;const u=e.length*(e.length-1)/2;for(;a<u;){const t=O(e[l])||O(e[c])?1:n(e[l],e[c]);1-t>=i&&(o.push(l),s.push(c),r.push(t)),a++,c++,c===e.length&&(l++,c=l+1)}return{i:new Int32Array(o),j:new Int32Array(s),distance:new Float32Array(r)}}}var k,G=n(8774);!function(e){e.none="none",e.bold="bold",e.dashed="dashed"}(k||(k={}));class B{get currentLineId(){return this._currentLineIdx}set currentLineId(e){e!==this._currentLineIdx&&(this._currentLineIdx=e,this.sp.render(this.ctx))}set linesToRender(e){this.updateLines(e),this.sp.render(this.ctx)}set linesVisibility(e){this.visibility=e,this.sp.render(this.ctx)}constructor(e,t,n,i,o=k.none){var s;this._currentLineIdx=-1,this.lineClicked=new c.Subject,this.lineHover=new c.Subject,this.mouseOverLineId=-1,this.arrowWidth=15,this.sp=e,this.xAxisCol=this.sp.dataFrame.columns.byName(t),this.yAxisCol=this.sp.dataFrame.columns.byName(n),this.canvas=this.sp.getInfo().canvas,this.ctx=this.canvas.getContext("2d"),this.currentLineStyle=o,this.updateLines(i),this.visibility=null!==(s=i.visibility)&&void 0!==s?s:new G.A(this.lines.from.length),i.visibility||this.visibility.setAll(!0,!1),i.arrowSize&&(this.arrowWidth=i.arrowSize),this.canvas.onmousedown=e=>{var t;(null===(t=this.lines)||void 0===t?void 0:t.skipMouseOverDetection)&&(this.mouseOverLineId=this.checkCoordsOnLine(e.offsetX,e.offsetY)),-1!==this.mouseOverLineId&&this.lineClicked.next({x:e.clientX,y:e.clientY,id:this.mouseOverLineId,event:e})},this.canvas.onmousemove=e=>{var t;this.mouseOverLineId=(null===(t=this.lines)||void 0===t?void 0:t.skipMouseOverDetection)?-1:this.checkCoordsOnLine(e.offsetX,e.offsetY),-1!==this.mouseOverLineId&&this.lineHover.next({x:e.clientX,y:e.clientY,id:this.mouseOverLineId,event:e})},e.onEvent("d4-before-draw-scene").subscribe(e=>{this.renderLines()})}updateLines(e){this.lines=e,this.multipleLinesCounts=new Uint8Array(this.lines.from.length),e.skipMultiLineCalculation?this.multipleLinesCounts.fill(0):this.createMultiLinesIndices()}renderLines(){var e,t,n,i,o,s,r,a,l,c,u,h,d,m,p,g,f;const y=this.lines.colors||this.lines.widths||this.lines.opacities||this.lines.drawArrowsArr;y||(this.ctx.lineWidth=null!==(e=this.lines.width)&&void 0!==e?e:1,this.ctx.strokeStyle=`rgba(${null!==(t=this.lines.color)&&void 0!==t?t:"0,128,0"},${null!==(n=this.lines.opacity)&&void 0!==n?n:1})`);const b=this.sp.dataFrame.filter,w=Math.pow(null!==(i=this.lines.shortLineThreshold)&&void 0!==i?i:5,2);for(let e=0;e<this.lines.from.length;e++)if(b.get(this.lines.from[e])&&b.get(this.lines.to[e])&&this.visibility.getBit(e)){let t=0;const n=this.sp.getMarkerSize(this.lines.from[e])/2,i=this.sp.getMarkerSize(this.lines.to[e])/2,b=this.sp.pointToScreen(this.lines.from[e]);let v=null==b?void 0:b.x,C=null==b?void 0:b.y;const A=this.sp.pointToScreen(this.lines.to[e]);let T=null==A?void 0:A.x,E=null==A?void 0:A.y;const S=Math.min(this.sp.viewBox.width,this.sp.viewBox.height);if(this.ctx.beginPath(),v&&C&&T&&E&&Math.hypot(T-v,E-C)/S>.01){if(y){const t=(null===(o=this.lines.colors)||void 0===o?void 0:o[e])?null===(s=this.lines.colors)||void 0===s?void 0:s[e]:null!==(r=this.lines.color)&&void 0!==r?r:"0,128,0",n=(null===(a=this.lines.opacities)||void 0===a?void 0:a[e])?null===(l=this.lines.opacities)||void 0===l?void 0:l[e]:null!==(c=this.lines.opacity)&&void 0!==c?c:1;this.ctx.strokeStyle=`rgba(${t},${n})`,this.ctx.lineWidth=(null===(u=this.lines.widths)||void 0===u?void 0:u[e])?null===(h=this.lines.widths)||void 0===h?void 0:h[e]:null!==(d=this.lines.width)&&void 0!==d?d:1}e===this._currentLineIdx&&this.toggleCurrentLineStyle(!0);const b=this.multipleLinesCounts[e];let A=null;if(b){t=this.getLineLength(v,C,T,E);const o=this.getPointOnDistance(v,C,T,E,i,t),s=this.getPointOnDistance(T,E,v,C,n,t);v=o.x,C=o.y,T=s.x,E=s.y,A=this.lines.from[e]>this.lines.to[e]?this.findControlPoint(b,v,C,T,E,e):this.findControlPoint(b,T,E,v,C,e),this.ctx.moveTo(v,C),this.ctx.quadraticCurveTo(A.x,A.y,T,E)}else(!this.lines.skipShortLines||Math.pow(T-v,2)+Math.pow(E-C,2)>w)&&(this.ctx.moveTo(v,C),this.ctx.lineTo(T,E));if((null!==(m=this.lines.drawArrows)&&void 0!==m?m:null===(p=this.lines.drawArrowsArr)||void 0===p?void 0:p.getBit(e))&&(t||(t=this.getLineLength(v,C,T,E)),t>this.arrowWidth)){const e=b?null:this.getPointOnDistance(v,C,T,E,i,t),n=b?A.x:v,o=b?A.y:C;this.canvasArrow(this.ctx,null!==(g=null==e?void 0:e.x)&&void 0!==g?g:v,null!==(f=null==e?void 0:e.y)&&void 0!==f?f:C,n,o)}this.ctx.stroke(),this.ctx.closePath(),e===this._currentLineIdx&&this.toggleCurrentLineStyle(!1)}}this.fillLeftBottomRect()}toggleCurrentLineStyle(e){switch(this.currentLineStyle){case k.bold:e?this.ctx.lineWidth+=2:this.ctx.lineWidth-=2;break;case k.dashed:e?this.ctx.setLineDash([5,5]):this.ctx.setLineDash([]);break;default:return}}fillLeftBottomRect(){const e=new Path2D;e.rect(this.sp.yAxisBox.minX,this.sp.yAxisBox.maxY,this.sp.yAxisBox.width,this.sp.xAxisBox.height),this.ctx.fillStyle="white",this.ctx.beginPath(),this.ctx.fill(e),this.ctx.closePath()}createMultiLinesIndices(){const e={};for(let t=0;t<this.lines.from.length;t++){let n=0,i=0;this.lines.from[t]<this.lines.to[t]?(n=this.lines.from[t],i=this.lines.to[t]):(n=this.lines.to[t],i=this.lines.from[t]),e[`${n}|${i}`]?(1===e[`${n}|${i}`].length&&(this.multipleLinesCounts[e[`${n}|${i}`][0]]=1,e[`${n}|${i}`].push(1)),this.multipleLinesCounts[t]=++e[`${n}|${i}`][1]):e[`${n}|${i}`]=[t]}}checkCoordsOnLine(e,t){let n=-1,i=null,o=null;const s=this.sp.dataFrame.filter;for(let r=0;r<this.lines.from.length;r++)if(s.get(this.lines.from[r])&&s.get(this.lines.to[r])&&this.visibility.getBit(r)){const s=this.sp.getMarkerSize(this.lines.from[r])/2,a=this.sp.getMarkerSize(this.lines.to[r])/2,l=this.sp.worldToScreen(this.xAxisCol.get(this.lines.from[r]),this.yAxisCol.get(this.lines.from[r])),c=this.sp.worldToScreen(this.xAxisCol.get(this.lines.to[r]),this.yAxisCol.get(this.lines.to[r]));if(this.multipleLinesCounts[r]){const n=this.getLineLength(l.x,l.y,c.x,c.y),i=this.getPointOnDistance(l.x,l.y,c.x,c.y,a,n),u=this.getPointOnDistance(c.x,c.y,null==l?void 0:l.x,null==l?void 0:l.y,s,n),h=this.lines.from[r]>this.lines.to[r]?this.findControlPoint(this.multipleLinesCounts[r],i.x,i.y,u.x,u.y,r):this.findControlPoint(this.multipleLinesCounts[r],u.x,u.y,i.x,i.y,r);o=this.calculateDistToCurveLine(r,e,t,i,u,h)}else o=this.calculateDistToStraightLine(e,t,l,c);(!i&&null!==o&&o<5||i&&null!==o&&o<i)&&(i=o,n=r)}return n}calculateDistToStraightLine(e,t,n,i){const o=Math.min(n.x,i.x),s=Math.max(n.x,i.x),r=Math.min(n.y,i.y),a=Math.max(n.y,i.y);return e>=o-2&&e<=s+2&&t>=r-2&&t<=a+2?this.distToStraightLineSegment(e,t,n,i):null}distToStraightLineSegment(e,t,n,i){const o=(e,t,n,i)=>Math.pow(e-n,2)+Math.pow(t-i,2),s=o(n.x,n.y,i.x,i.y);if(0==s)return o(e,t,n.x,n.y);let r=((e-n.x)*(i.x-n.x)+(t-n.y)*(i.y-n.y))/s;return r=Math.max(0,Math.min(1,r)),o(e,t,n.x+r*(i.x-n.x),n.y+r*(i.y-n.y))}calculateDistToCurveLine(e,t,n,i,o,s){const r=Math.min(i.x,o.x,s.x),a=Math.max(i.x,o.x,s.x),l=Math.min(i.y,o.y,s.y),c=Math.max(i.y,o.y,s.y);if(t>=r-2&&t<=a+2&&n>=l-2&&n<=c+2){const e=a-r,u=c-l;return this.calculateDistToCurveInRect(t,n,i,s,o,e,u)}return null}calculateDistToCurveInRect(e,t,n,i,o,s,r){const a=Math.floor((s+r)/3),l=1/a,c=new Uint32Array(a),u=new Uint32Array(a),h=new Uint32Array(a);let d=null;const m=new G.A(a);for(let s=0;s<c.length;s++){const r=s*l,a=Math.pow(1-r,2)*n.x+2*r*(1-r)*i.x+Math.pow(r,2)*o.x,m=Math.pow(1-r,2)*n.y+2*r*(1-r)*i.y+Math.pow(r,2)*o.y,p=Math.abs(e-a),g=Math.abs(t-m),f=p+g;(!d||d>f)&&(d=f),h[s]=Math.max(p,g),c[s]=a,u[s]=m}for(let e=0;e<c.length;e++)h[e]<d&&m.setBit(e,!0,!1);let p=null;for(let n=-1;-1!==(n=m.findNext(n));){const i=Math.hypot(c[n]-e,u[n]-t);(!p||p>i)&&(p=i)}return p}getLineLength(e,t,n,i){return Math.sqrt(Math.pow(n-e,2)+Math.pow(i-t,2))}getPointOnDistance(e,t,n,i,o,s){const a=n-o*((n-e)/s),l=i-o*((i-t)/s);return new r.Point(a,l)}findControlPoint(e,t,n,i,o,s){const a=t+(i-t)/2,l=n+(o-n)/2;let c=a-t,u=l-n;const h=Math.sqrt(c*c+u*u);c/=h,u/=h;const d=50*Math.ceil(e/2);return e%2==0?new r.Point(a+d/2*u,l-d/2*c):new r.Point(a-d/2*u,l+d/2*c)}canvasArrow(e,t,n,i,o){const s=Math.atan2(i-t,o-n)+Math.PI;e.moveTo(t-this.arrowWidth*Math.sin(s-Math.PI/10),n-this.arrowWidth*Math.cos(s-Math.PI/10)),e.lineTo(t,n),e.lineTo(t-this.arrowWidth*Math.sin(s+Math.PI/10),n-this.arrowWidth*Math.cos(s+Math.PI/10))}}const V="dimensionality-reducer-terminate-event";var U,q=n(3629);async function W(e,t,i,s,r,a,l){let c=await async function(e,t,i,s,r,a,l){if(!a.distanceFnArgs)throw new Error("options.distanceFnArgs must be defined");if(e.length!==t.length||e.length!==a.distanceFnArgs.length||e.length!==s.length)throw new Error("data, metrics and options and weights must have the same length");return new Promise(function(c,u){const h=new Worker(new URL(n.p+n.u(234),n.b));h.postMessage({columnsData:e,distanceMetrics:t,method:i,options:a,weights:s,aggregationMethod:r});const d=o.events.onCustomEvent(V).subscribe(()=>{try{h?.terminate()}finally{d.unsubscribe()}});h.onmessage=({data:{error:e,embedding:t,epochNum:n,epochsLength:i}})=>{O(n)||O(i)?(d.unsubscribe(),e?u(e):c(t),setTimeout(()=>h.terminate(),100)):l&&l(n,i,t)}})}(e,i,t,s,r,a,l);return c=c.map(e=>(0,q.S8)(e)),c}!function(e){e.EUCLIDEAN="EUCLIDEAN",e.MANHATTAN="MANHATTAN"}(U||(U={}));const Y={[U.EUCLIDEAN]:function(e){return`\n var sum = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n sum = sum + distances[i] * distances[i] * computeInfo.weights[i] * computeInfo.weights[i];\n }\n return sqrt(sum);\n `},[U.MANHATTAN]:function(e){return`\n var sum = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n sum = sum + abs(distances[i]) * computeInfo.weights[i];\n }\n return sum;\n `}};var j;!function(e){e.HAMMING="Hamming",e.EUCLIDEAN="Euclidean",e.VECTOR_COSINE="Vector Cosine",e.MANHATTAN="Manhattan",e.TANIMOTO="Tanimoto",e.LEVENSTEIN="Levenshtein",e.NEEDLEMAN_WUNSCH="Needlemann-Wunsch",e.MONOMER_CHEMICAL_DISTANCE="Monomer chemical distance",e.SOKAL="Sokal",e.COSINE="Cosine",e.ASYMMETRIC="Asymmetric",e.Difference="Difference",e.OneHot="One-Hot"}(j||(j={}));const K={[j.HAMMING]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n let maxLength: u32 = max(aLength, bLength);\n let minLength: u32 = min(aLength, bLength);\n let sizeDiff: u32 = maxLength - minLength;\n \n let maxIntDistance = ceil(maxDistance * f32(maxLength)) - f32(sizeDiff);\n\n var diff: f32 = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n diff = diff + f32(a[i] != b[i]);\n if (diff > maxIntDistance) {\n return 1.0;\n }\n }\n diff += f32(sizeDiff);\n return diff / ${e};\n `},[j.EUCLIDEAN]:function(e,t){return`\n var dist: f32 = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n dist = dist + f32(a[i] - b[i]) * f32(a[i] - b[i]);\n }\n return sqrt(dist);\n `},[j.MANHATTAN]:function(e,t){return`\n var dist: f32 = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n dist = dist + abs(f32(a[i] - b[i]));\n }\n return dist;\n `},[j.VECTOR_COSINE]:function(e,t){return`\n var dist: f32 = 0.0;\n var productSum: f32 = 0.0;\n var aSquareSum: f32 = 0.0;\n var bSquareSum: f32 = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n productSum = productSum + f32(a[i] * b[i]);\n aSquareSum = aSquareSum + f32(a[i] * a[i]);\n bSquareSum = bSquareSum + f32(b[i] * b[i]);\n }\n var sim = productSum / (sqrt(aSquareSum) * sqrt(bSquareSum));\n return (1.0 - sim) / 2.0;\n `},[j.TANIMOTO]:function(e,t){return`\n var onBitsa: u32 = 0u;\n var onBitsb: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n onBitsa = onBitsa + countOneBits(a[i]);\n onBitsb = onBitsb + countOneBits(b[i]);\n }\n\n if (onBitsa == 0u && onBitsb == 0u) {\n return 0.0;\n }\n\n let totalOnBits = onBitsa + onBitsb;\n var commonBits: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n commonBits = commonBits + countOneBits(a[i] & b[i]);\n }\n\n return 1.0 - f32(commonBits) / f32(totalOnBits - commonBits);\n `},[j.LEVENSTEIN]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n let maxLength: u32 = max(aLength, bLength);\n let minLength: u32 = min(aLength, bLength);\n\n let maxIntDistance = ceil(maxDistance * f32(maxLength));\n\n // we will store two arrays as matrix and swap the working indices per pass.\n // this way we can reduce memory usage per computation to just O(aLength)\n // the grid will have aLength + 1 columns and bLength + 1 rows\n // this will be guaranteed by iteration, but the array sizes must be known at compile time, so we will use a fixed size of maxArraySize\n var dynamicPassMat: array<array<f32, ${e+1}u>, 2>; // initialize to 0\n \n var prevIndex: u32 = 0;\n var curIndex: u32 = 1; // we will swap these indices per pass\n\n // initialize the first row\n for (var i = 0u; i <= aLength; i = i + 1u) {\n dynamicPassMat[prevIndex][i] = f32(i);\n }\n\n // iterate over the rows\n for (var i = 1u; i <= bLength; i = i + 1u) {\n dynamicPassMat[curIndex][0] = f32(i);\n var minEntry: f32 = f32(maxLength);\n let prevRow = &dynamicPassMat[prevIndex];\n let curRow = &dynamicPassMat[curIndex];\n let bMon = u32(b[i - 1]);\n for (var j = 1u; j <= aLength; j = j + 1u) {\n var cost: f32 = f32(a[j - 1] != bMon);\n var res: f32 = min(\n min(\n (*prevRow)[j] + 1.0, // deletion\n (*curRow)[j - 1] + 1.0, // insertion\n ),\n (*prevRow)[j - 1] + cost // substitution\n );\n (*curRow)[j] = res;\n if (res < minEntry) {\n minEntry = res;\n }\n }\n // swap the indices\n let temp: u32 = prevIndex;\n prevIndex = curIndex;\n curIndex = temp;\n if (minEntry > maxIntDistance) {\n return 1.0;\n }\n }\n\n return dynamicPassMat[prevIndex][aLength] / f32(maxLength);\n `},[j.NEEDLEMAN_WUNSCH]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n let maxLength: u32 = max(aLength, bLength);\n let minLength: u32 = min(aLength, bLength);\n \n let maxIntDistance = ceil(maxDistance * f32(maxLength));\n // we will store two arrays as matrix and swap the working indices per pass.\n // this way we can reduce memory usage per computation to just O(aLength)\n // the grid will have aLength + 1 columns and bLength + 1 rows\n // this will be guaranteed by iteration, but the array sizes must be known at compile time, so we will use a fixed size of maxArraySize\n var dynamicPassMat: array<array<f32, ${e+1}u>, 2>; // initialize to 0\n \n // we need to keep track of which operation led to the current cell\n // i.e. whether we came from the left, top or diagonal to assign gap open/gap extend penalty\n var verticalGaps: array<u32, ${e+1}u>;\n var horizontalGaps: array<u32, ${e+1}u>;\n\n let gapOpenPenalty: f32 = suppInfo.gapOpenPenalty${t};\n let gapExtensionPenalty: f32 = suppInfo.gapExtensionPenalty${t};\n var prevIndex: u32 = 0;\n var curIndex: u32 = 1; // we will swap these indices per pass\n // initialize the first row\n for (var i = 0u; i <= aLength; i = i + 1u) {\n dynamicPassMat[prevIndex][i] = gapExtensionPenalty + f32(i - 1) * gapExtensionPenalty; // accounting for the fact that left and right gaps are less costly\n dynamicPassMat[curIndex][i] = 0.0;\n }\n dynamicPassMat[0][0] = 0.0;\n\n let simMatrix = &suppInfo.similarityMatrix${t}; // using pointers make things faster\n // iterate over the rows\n for (var i = 1u; i <= bLength; i = i + 1u) {\n let prevRow = &dynamicPassMat[prevIndex];\n let curRow = &dynamicPassMat[curIndex];\n (*curRow)[0] = gapExtensionPenalty + f32(i - 1) * gapExtensionPenalty;\n var minEntry: f32 = f32(maxLength);\n let monB = u32(b[i - 1]);\n for (var j = 1u; j <= aLength; j = j + 1u) {\n let monA = u32(a[j - 1]);\n \n let cost: f32 = (*prevRow)[j - 1] + 1f - (*simMatrix)[monA][monB];\n var top = (*prevRow)[j]; // deletion\n if (verticalGaps[j] > 0 || i == 1 || i == bLength) {\n top = top + gapExtensionPenalty;\n } else {\n top = top + gapOpenPenalty;\n }\n var left = (*curRow)[j - 1]; // insertion\n if (horizontalGaps[j - 1] > 0 || j == 1 || j == aLength) {\n left = left + gapExtensionPenalty;\n } else {\n left = left + gapOpenPenalty;\n }\n var res: f32 = min(\n min(\n top, // deletion\n left, // insertion\n ),\n cost // substitution\n );\n (*curRow)[j] = res;\n if (res < minEntry) {\n minEntry = res;\n }\n // update the horizontal and vertical gaps\n if (res == cost) {\n verticalGaps[j] = 0;\n horizontalGaps[j] = 0;\n } else if (res == left) {\n verticalGaps[j] = 0;\n horizontalGaps[j] = 1;\n } else {\n verticalGaps[j] = 1;\n horizontalGaps[j] = 0;\n }\n }\n // swap the indices\n let temp: u32 = prevIndex;\n prevIndex = curIndex;\n curIndex = temp;\n if (minEntry > maxIntDistance) {\n return 1.0;\n }\n }\n return dynamicPassMat[prevIndex][aLength] / f32(minLength);\n\n `},[j.MONOMER_CHEMICAL_DISTANCE]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n let maxLength: u32 = max(aLength, bLength);\n let minLength: u32 = min(aLength, bLength);\n let sizeDiff: u32 = maxLength - minLength;\n \n let maxIntDistance = ceil(maxDistance * f32(maxLength)) - f32(sizeDiff);\n\n let simMatrix = &(suppInfo.similarityMatrix${t}); // using pointers make things faster\n var diff: f32 = 0.0;\n for (var i = 0u; i < ${e}; i = i + 1u) {\n diff = diff + 1.0 - (*simMatrix)[u32(a[i])][u32(b[i])];\n if (diff > maxIntDistance) {\n return 1.0;\n }\n }\n diff += f32(sizeDiff);\n return diff / ${e};\n `},[j.SOKAL]:function(e,t){return`\n var onBitsa: u32 = 0u;\n var onBitsb: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n onBitsa = onBitsa + countOneBits(a[i]);\n onBitsb = onBitsb + countOneBits(b[i]);\n }\n let total = onBitsa + onBitsb;\n if (total == 0u) {\n return 1.0;\n }\n var commonBits: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n commonBits = commonBits + countOneBits(a[i] & b[i]);\n }\n return 1.0 - f32(commonBits) / f32(total * 2 - commonBits * 3);\n `},[j.COSINE]:function(e,t){return`\n var onBitsa: u32 = 0u;\n var onBitsb: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n onBitsa = onBitsa + countOneBits(a[i]);\n onBitsb = onBitsb + countOneBits(b[i]);\n }\n let total = onBitsa * onBitsb; // p.s. here total is taken by multiplying\n if (total == 0u) {\n return 1.0;\n }\n var commonBits: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n commonBits = commonBits + countOneBits(a[i] & b[i]);\n }\n return 1.0 - f32(commonBits) / sqrt(f32(total));\n `},[j.ASYMMETRIC]:function(e,t){return`\n var onBitsa: u32 = 0u;\n var onBitsb: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n onBitsa = onBitsa + countOneBits(a[i]);\n onBitsb = onBitsb + countOneBits(b[i]);\n }\n let min = min(onBitsa, onBitsb);\n if (min == 0u) {\n return 1.0;\n }\n var commonBits: u32 = 0u;\n for (var i = 0u; i < ${e}u; i = i + 1u) {\n commonBits = commonBits + countOneBits(a[i] & b[i]);\n }\n return 1.0 - f32(commonBits) / f32(min);\n `},[j.Difference]:function(e,t){return`\n let range = suppInfo.range${t};\n return f32(abs(f32(a[0]) - f32(b[0])) / range);\n `},[j.OneHot]:function(e,t){return`\n let aLength: u32 = computeInfo.entrySizes[${t}][aIndex];\n let bLength: u32 = computeInfo.entrySizes[${t}][bIndex];\n if (aLength != bLength) {\n return 1.0;\n }\n for (var i = 0u; i < aLength; i = i + 1u) {\n if(a[i] != b[i]) {\n return 1.0;\n }\n }\n return 0.0;\n `}},z={[j.HAMMING]:e=>Math.ceil(e/30),[j.EUCLIDEAN]:e=>Math.ceil(e/30),[j.MANHATTAN]:e=>Math.ceil(e/30),[j.TANIMOTO]:e=>Math.ceil(e/30),[j.SOKAL]:e=>Math.ceil(e/30),[j.COSINE]:e=>Math.ceil(e/30),[j.ASYMMETRIC]:e=>Math.ceil(e/30),[j.LEVENSTEIN]:e=>Math.ceil(e*e/60),[j.NEEDLEMAN_WUNSCH]:e=>Math.ceil(e*e/60),[j.MONOMER_CHEMICAL_DISTANCE]:e=>Math.ceil(e/25),[j.Difference]:e=>1,[j.OneHot]:e=>Math.ceil(e/40),[j.VECTOR_COSINE]:e=>Math.ceil(e/30)},Z={STRING:new Set([j.HAMMING,j.LEVENSTEIN,j.NEEDLEMAN_WUNSCH,j.MONOMER_CHEMICAL_DISTANCE,j.OneHot]),UINT32ARRAY:new Set([j.HAMMING,j.EUCLIDEAN,j.MANHATTAN,j.MONOMER_CHEMICAL_DISTANCE,j.LEVENSTEIN,j.NEEDLEMAN_WUNSCH,j.TANIMOTO,j.COSINE,j.VECTOR_COSINE,j.SOKAL,j.ASYMMETRIC,j.OneHot,j.Difference]),INT32ARRAY:new Set([j.EUCLIDEAN,j.MANHATTAN,j.OneHot,j.Difference,j.VECTOR_COSINE]),FLOAT32ARRAY:new Set([j.EUCLIDEAN,j.MANHATTAN,j.Difference,j.VECTOR_COSINE]),NUMBER:new Set([j.EUCLIDEAN,j.MANHATTAN,j.Difference]),BITARRAY:new Set([j.TANIMOTO,j.COSINE,j.SOKAL,j.ASYMMETRIC])};function X(e,t=.8,n,i,o,s){return function(e,t,n,i){return new(n||(n=Promise))(function(o,s){function r(e){try{l(i.next(e))}catch(e){s(e)}}function a(e){try{l(i.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})}(this,void 0,void 0,function*(){const r=yield function(){return E(this,void 0,void 0,function*(){if(!navigator.gpu)return console.error("WebGPU is not supported in this browser"),null;if(!S&&(S=yield navigator.gpu.requestAdapter({powerPreference:"high-performance"}),null==S))return null;let e=!1;if(M&&(M.lost.then(()=>{e=!0}),yield new Promise(e=>setTimeout(e,10))),!M||e){const e=1e9,t=S.limits,n=t.maxBufferSize,i=t.maxStorageBufferBindingSize;try{return M=yield S.requestDevice({requiredLimits:{maxBufferSize:Math.min(n,e),maxStorageBufferBindingSize:Math.min(i,e)}}),M}catch(e){return console.error("Failed to create device with required limits",e),M=yield S.requestDevice(),M}}return M})}();if(!r)return null;const a=Object.values(j);if(n.some(e=>!a.includes(e)))throw new Error("Invalid distance metrics provided: "+n.join(", "));if(!Object.values(U).includes(i))throw new Error("Invalid aggregation function provided: "+i);const l=1-t;if(s.length!==e.length||s.length!==n.length||s.length!==o.length)throw new Error("Options, weigths and distance functions must be provided for each column");if(e.some(t=>t.length!==e[0].length))throw new Error("All entry lists must be the same length");const c=e.length,u=e[0].length,h=e.map((e,t)=>function(e,t=j.HAMMING,n,i={gapOpenPenalty:1,gapExtensionPenalty:.6}){var o,s;let r=null;const a=e.some(e=>"string"==typeof e)?(r="STRING",e.map(e=>new Uint32Array(e.split("").map(e=>e.charCodeAt(0))))):e.some(e=>"number"==typeof e)?(r="NUMBER",e.map(e=>new Float32Array([e]))):"object"==typeof e[0]&&e.some(e=>"_data"in e&&"_length"in e)?(r="BITARRAY",e.map(e=>e._data)):e.some(e=>e instanceof Float32Array)?(r="FLOAT32ARRAY",e):e.some(e=>e instanceof Uint32Array)?(r="UINT32ARRAY",e):e.some(e=>e instanceof Int32Array)?(r="INT32ARRAY",e):void 0;if(!a||!r)throw new Error("Invalid entry type, could not determine entry type from input list");const l=a[0]instanceof Int32Array?"INT32ARRAY":a[0]instanceof Float32Array?"FLOAT32ARRAY":"UINT32ARRAY",c=new Uint32Array(a.map(e=>e.length));if(!Z[r]||!Z[r].has(t))throw new Error(`Distance metric '${t}' not supported for entry type '${r}'`);const u=c.reduce((e,t)=>Math.max(e,t),0),h=z[t](u),d="INT32ARRAY"===l?Int32Array:"FLOAT32ARRAY"===l?Float32Array:Uint32Array,m=new d(a.length*u);a.forEach((e,t)=>{m.set(e,t*u)});let p="",g=0,f="FLOAT32ARRAY",y=null;if(t===j.NEEDLEMAN_WUNSCH||t===j.MONOMER_CHEMICAL_DISTANCE){let e=i.scoringMatrix&&i.alphabetIndexes?Object.keys(i.alphabetIndexes).reduce((e,t)=>Math.max(e,t.charCodeAt(0)),0):-1;if(!i.alphabetIndexes||!i.scoringMatrix){for(let t=0;t<m.length;t++)m[t]>e&&(e=m[t]);i.scoringMatrix=new Array(e+1).fill(null).map(()=>new Array(e+1).fill(0)),i.alphabetIndexes={};for(let e=0;e<i.scoringMatrix.length;e++)i.scoringMatrix[e][e]=1,i.alphabetIndexes[String.fromCharCode(e)]=e}const t=(e+1)*(e+1),r=new Array(e+1).fill(null).map(()=>new Float32Array(e+1));for(let t=0;t<e+1;t++)r[t][t]=1;const a=i.alphabetIndexes;for(const e of Object.keys(a))for(const t of Object.keys(a))e!==t&&(r[e.charCodeAt(0)][t.charCodeAt(0)]=i.scoringMatrix[a[e]][a[t]]);g=2+t,f="FLOAT32ARRAY",y=new Float32Array(g),y[0]=null!==(o=i.gapOpenPenalty)&&void 0!==o?o:1,y[1]=null!==(s=i.gapExtensionPenalty)&&void 0!==s?s:.6;let l=2;for(let e=0;e<r.length;e++)y.set(r[e],l),l+=r[e].length;p=`\n gapOpenPenalty${n}: f32,\n gapExtensionPenalty${n}: f32,\n similarityMatrix${n}: array<array<f32, ${e+1}>, ${e+1}>`}else if(t===j.Difference){if(!i.range||"number"!=typeof i.range||i.range<=0){const e=m.reduce((e,t)=>Math.min(e,t),m[0]),t=m.reduce((e,t)=>Math.max(e,t),m[0]);i.range=t-e}i.range<=0&&(i.range=1),g=1,f="FLOAT32ARRAY",y=new Float32Array([i.range]),p=`\n range${n}: f32`}const b=m instanceof Int32Array?"i32":m instanceof Float32Array?"f32":"u32",w=`data${n}: array<array<${b}, ${u}>, ${a.length}>`;return{flatSourceArray:m,sourceArraySize:m.length,maxEntryLen:u,arraySizes:c,complexity:h,suppInfoBuffer:y,suppInfoSize:g,suppInfoType:f,suppInfoStructWgsl:p,entryType:r,dataTypeWGSL:b,dataStructWgsl:w,EncodedArrayConstructor:d}}(e,n[t],t,s[t]));if(0===c)throw new Error("No columns provided. Please provide at least one column of data.");1===c&&(i=U.MANHATTAN);let d=h.map(e=>e.suppInfoStructWgsl).filter(e=>!!e&&""!=e).join(",\n"),m=!1;d&&""!=d.trim()||(m=!0,d="\ndummy: f32\n");const p=h.map(e=>e.dataStructWgsl).filter(e=>!!e&&""!=e).join(",\n"),g=new Uint32Array(c*u);h.forEach((e,t)=>{g.set(e.arraySizes,t*u)});const f=1e4,y=100,b=h.reduce((e,t)=>e+t.complexity,0),w=Math.ceil(6e3/b),v=Math.ceil(Math.sqrt(Math.ceil(100))),C=10*v,A=u*(u-1)/2,T=Math.ceil(A/f),x=r.createShaderModule({label:"Sparse matrix compute shader",code:`\n // each thread will perform 100 iterations at one time, comparing 100 pairs of entries.\n // in total, each thread will perform at most ${T} comparisons.\n // first is the result struct, containing is, js, and distances. each array with length of 100,\n // and also integer for how many pairs were found to be below threshold.\n struct SparseResult {\n i: array<array<u32, 100>, 10000>,\n j: array<array<u32, 100>, 10000>,\n distances: array<array<f32, 100>, 10000>,\n found: array<u32, 10000>,\n done: array<u32, 10000>\n }\n // struct for the data\n struct ComputeInfo {\n // start at cols and rows, and end at cols and rows for each thread, these will be calculated on cpu and passed to gpu.\n startAtCols: array<u32, 10000>,\n startAtRows: array<u32, 10000>,\n endAtCols: array<u32, 10000>,\n endAtRows: array<u32, 10000>,\n\n // the ACTUALLY sizes of each entry\n entrySizes: array<array<u32, ${u}>, ${c}>,\n // the weights for each entry\n weights: array<f32, ${c}>,\n // the data for each entry\n ${p} // an example of the dataWgsl would be:\n //data0: array<array<u32,20>,100>,\n //data1: array<array<u32,20>,100>\n }\n\n // struct for the supplementary information\n struct SuppInfo {\n // struct containing all the supplementary info, like scoring matrix, alphabet indexes, range, etc.\n ${d}\n };\n\n @group(0) @binding(0) var<storage, read_write> computeInfo: ComputeInfo;\n @group(0) @binding(1) var<storage, read_write> suppInfo: SuppInfo;\n @group(0) @binding(2) var<storage, read_write> results: SparseResult;\n @compute @workgroup_size(10, 10) fn calcSparseMatrix(\n @builtin(global_invocation_id) id: vec3<u32>\n ) {\n ${m?"let otherDummy = suppInfo.dummy * 2;":""} // just to make sure that the suppInfo is not optimized out\n let threadCol = id.x;\n let threadRow = id.y;\n let linearIndex = threadRow * ${C} + threadCol;\n if (linearIndex >= 10000) {\n return; // if we are out of bounds, return\n } \n var startAtCol: u32 = computeInfo.startAtCols[linearIndex];\n var startAtRow: u32 = computeInfo.startAtRows[linearIndex];\n let endAtCol: u32 = min(computeInfo.endAtCols[linearIndex], ${u}u);\n let endAtRow: u32 = min(computeInfo.endAtRows[linearIndex], ${u}u);\n let is = &results.i[linearIndex];\n let js = &results.j[linearIndex];\n let distances = &results.distances[linearIndex];\n results.found[linearIndex] = 0; // initialize the found counter\n var found: u32 = 0;\n if (results.done[linearIndex] > 0) {\n return; // if we are done, return\n }\n for (var i = 0; i < ${w}; i++) {\n if (startAtCol >= endAtCol && startAtRow >= endAtRow) {\n results.done[linearIndex] = 1;\n break;\n }\n if (found >= 100) {\n break;\n }\n let dist = combinedDistance(startAtCol, startAtRow);\n if (dist <= ${l}) {\n (*is)[found] = startAtCol;\n (*js)[found] = startAtRow;\n (*distances)[found] = dist;\n found = found + 1;\n }\n startAtCol = startAtCol + 1;\n if (startAtCol >= ${u}u) {\n startAtRow += 1;\n startAtCol = startAtRow + 1;\n }\n }\n results.found[linearIndex] = found;\n // update the startAtCols and startAtRows\n computeInfo.startAtCols[linearIndex] = startAtCol;\n computeInfo.startAtRows[linearIndex] = startAtRow;\n\n }\n\n // this will generate the distance script for each distance metric and then combine them into one\n ${Q(n,h.map(e=>e.maxEntryLen),l,i)}\n\n\n `}),P=r.createComputePipeline({label:"sparse matrix compute pipeline",layout:"auto",compute:{module:x,entryPoint:"calcSparseMatrix"}}),L=new Uint32Array(f),I=new Uint32Array(f),_=new Uint32Array(f),N=new Uint32Array(f),R=Math.floor(A/f);let $=0,O=1;console.time("GPUthreadStarts");for(let e=0;e<f;e++){const t=9999===e?A-1:(e+1)*R,n=u-2-Math.floor(Math.sqrt(-8*t+4*u*(u-1)-7)/2-.5),i=t-u*n+Math.floor((n+1)*(n+2)/2);L[e]=O,I[e]=$,_[e]=i,N[e]=n,$=n,O=i}console.timeEnd("GPUthreadStarts");const H=4e4+u*c+c+h.reduce((e,t)=>e+t.sourceArraySize,0),D=h.reduce((e,t)=>e+t.suppInfoSize,0),F=1e6,k=H*Uint32Array.BYTES_PER_ELEMENT;let G=k;const B=15&k;0!==B&&(G+=16-B);const V=r.createBuffer({label:"compute info buffer",size:G,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST,mappedAtCreation:!0}),q=V.getMappedRange();let W=0;new Uint32Array(q,W,f).set(L),W+=f*Uint32Array.BYTES_PER_ELEMENT,new Uint32Array(q,W,f).set(I),W+=f*Uint32Array.BYTES_PER_ELEMENT,new Uint32Array(q,W,f).set(_),W+=f*Uint32Array.BYTES_PER_ELEMENT,new Uint32Array(q,W,f).set(N),W+=f*Uint32Array.BYTES_PER_ELEMENT,new Uint32Array(q,W,g.length).set(g),W+=g.length*Uint32Array.BYTES_PER_ELEMENT,new Float32Array(q,W,c).set(o),W+=c*Float32Array.BYTES_PER_ELEMENT;for(const e of h){const t=e.EncodedArrayConstructor,n=e.sourceArraySize;new t(q,W,n).set(e.flatSourceArray),W+=n*t.BYTES_PER_ELEMENT}V.unmap();const Y=D*Uint32Array.BYTES_PER_ELEMENT;let K=Y;const X=15&Y;0!==X&&(K+=16-X),K=Math.max(K,16);const J=r.createBuffer({label:"supp info buffer",size:K,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST,mappedAtCreation:!0}),ee=J.getMappedRange();let te=0;for(const e of h)e.suppInfoBuffer&&e.suppInfoBuffer.byteLength>0&&e.suppInfoSize>0&&(new("UINT32ARRAY"===e.suppInfoType?Uint32Array:Float32Array)(ee,te,e.suppInfoBuffer.length).set(e.suppInfoBuffer),te+=e.suppInfoBuffer.byteLength);0===te&&new Uint32Array(ee,0,4).set([1,1,1,1]),J.unmap();const ne=302e4*Uint32Array.BYTES_PER_ELEMENT;let ie=ne;const oe=15≠0!==oe&&(ie+=16-oe);const se=r.createBuffer({label:"results buffer",size:ie,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),re=r.createBindGroup({label:"bindGroup for sparse matrix buffer",layout:P.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:V}},{binding:1,resource:{buffer:J}},{binding:2,resource:{buffer:se}}]}),ae=r.createBuffer({label:"results out buffer",size:se.size,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),le=[],ce=[],ue=[];let he=!1;for(;!he;){const e=r.createCommandEncoder({label:"distance encoder"}),t=e.beginComputePass({label:"distance compute pass"});t.setPipeline(P),t.setBindGroup(0,re),t.dispatchWorkgroups(v,v),t.end(),e.copyBufferToBuffer(se,0,ae,0,ae.size);const n=e.finish();r.queue.submit([n]),yield r.queue.onSubmittedWorkDone(),yield ae.mapAsync(GPUMapMode.READ);const i=ae.getMappedRange();let o=0;const s=new Uint32Array(i,o,F);o+=F*Uint32Array.BYTES_PER_ELEMENT;const a=new Uint32Array(i,o,F);o+=F*Uint32Array.BYTES_PER_ELEMENT;const l=new Float32Array(i,o,F);o+=F*Float32Array.BYTES_PER_ELEMENT;const c=new Uint32Array(i,o,f);o+=f*Uint32Array.BYTES_PER_ELEMENT,he=new Uint32Array(i,o,f).every(e=>1===e);const u=c.reduce((e,t)=>e+t,0),h=new Uint32Array(u),d=new Uint32Array(u),m=new Float32Array(u);let p=0;for(let e=0;e<c.length;e++){const t=c[e];0!==t&&(h.set(s.subarray(e*y,e*y+t),p),d.set(a.subarray(e*y,e*y+t),p),m.set(l.subarray(e*y,e*y+t),p),p+=t)}le.push(h),ce.push(d),ue.push(m),ae.unmap()}const de=le.reduce((e,t)=>e+t.length,0),me=new Uint32Array(de),pe=new Uint32Array(de),ge=new Float32Array(de);let fe=0;for(let e=0;e<le.length;e++)me.set(le[e],fe),pe.set(ce[e],fe),ge.set(ue[e],fe),fe+=le[e].length;return V.destroy(),J.destroy(),se.destroy(),ae.destroy(),{i:me,j:pe,distance:ge}})}function Q(e,t,n,i){return e.map((e,i)=>`\n fn distanceScript${i}(aIndex: u32, bIndex: u32) -> f32 {\n let a = computeInfo.data${i}[aIndex];\n let b = computeInfo.data${i}[bIndex];\n let maxDistance: f32 = ${n};\n ${K[e](t[i],i)}\n }\n `).join("\n")+"\n"+`\n fn combinedDistance(aIndex: u32, bIndex: u32) -> f32 {\n var distances: array<f32, ${e.length}>;\n ${e.map((e,t)=>`distances[${t}] = distanceScript${t}(aIndex, bIndex);`).join("\n")}\n ${Y[i](e.length)}\n }\n \n `}var J=n(1991),ee=n.n(J);let te=0;const ne="cliffsDf",ie=new c.Subject,oe="SALI",se="line index",re=["From","To"],ae="filterCliffs";async function le(e,t,n,i,a,l,c,u,h,d,m,p,g,f,y,b){te++;const w=c/100;let v,C=!1;const A=o.shell.tv?.dataFrame===t?o.shell.tv:o.shell.getTableView(t.name);let T=null;if(h.useWebGPU)try{T=await X([i.entries],w,[u],U.MANHATTAN,[1],[i.options??{}])}catch(e){console.error(e)}T||(h.useWebGPU&&console.error("WebGPU sparse matrix calculation failed, falling back to CPU implementation"),T=await(new F).calc(i.entries,u,w,i.options));const E=await async function(e,t){const n=e.distance.map((n,i)=>{const o=Math.abs(t.get(e.i[i])-t.get(e.j[i]));return 0!=n?o/n:1/0}),i=e.distance.map(e=>1-e),o=e.i,s=e.j,a=r.BitSet.create(t.length);return e.distance.forEach((t,n)=>{a.set(e.i[n],!0),a.set(e.j[n],!0)}),{simVals:i,saliVals:n,n1:o,n2:s,cliffsBitSet:a}}(T,a),S=`sali_${l[0].substring(l[0].lastIndexOf("_"))}`;if(!t.columns.names().includes(S)){const i=function(e,t,n,i,o,s,a){const l=new Array(e).fill(0);for(let e=0;e!=i.length;++e)n[e]!=1/0&&(a.get(i[e])>a.get(o[e])?l[i[e]]+=n[e]:l[o[e]]+=n[e]);return r.Column.fromList("double",t,l)}(n.length,S,E.saliVals,E.n1,E.n2,0,a);t.columns.add(i),e.setOptions({size:i.name})}const M=function(e){const t=e.filter(e=>e!==1/0),n=t.reduce((e,t)=>Math.min(e,t),Number.MAX_VALUE);return{max:t.reduce((e,t)=>Math.max(e,t),n),min:n}}(E.saliVals),x=.8/(M.max-M.min),P=function(e,t,n,i,o,s,a,l){const c={from:new Uint32Array(t.n1.length),to:new Uint32Array(t.n1.length),opacities:new Float32Array(t.n1.length),colors:new Array(t.n1.length),widths:new Float32Array(t.n1.length)};for(let n=0;n<t.n1.length;n++)c.from[n]=t.n1[n],c.to[n]=t.n2[n],c.opacities[n]=t.saliVals[n]===1/0?1:.2+(t.saliVals[n]-a.min)*l,c.colors[n]=e.selection.get(c.from[n])&&e.selection.get(c.to[n])?"255,255,0":"0,128,0",c.widths[n]=1;const u=r.DataFrame.create(c.from.length);return re.forEach((e,t)=>{u.columns.addNewString(e).init(e=>n.get(0===t?c.from[e]:c.to[e])),function(e,t){Object.keys(t).forEach(n=>{e.tags[n]=t[n]})}(u.col(e),s),u.col(e).semType=o}),u.columns.addNewFloat("Δ activity").init(e=>Math.abs(i.get(c.from[e])-i.get(c.to[e]))),u.columns.addNewInt(se).init(e=>e),u.columns.addNewFloat(oe).init(e=>t.saliVals[e]),u.columns.addNewFloat("Similarity").init(e=>t.simVals[e]),u.name=`${ne}${te}`,{lines:c,linesDf:u}}(t,E,n,a,d,m,M,x);P.lines.skipMultiLineCalculation=!0,P.linesDf.col(oe).setTag("description","Structure−Activity Landscape Index (activity difference divided by 1 minus similarity)");const L=new B(e,l[0],l[1],P.lines,k.none);let I=null;const _=s.button(`${P.linesDf.rowCount} cliffs`,()=>{if(!I?.dataFrame){I=(()=>{const e=f?f(P.linesDf,re).sort([oe],[!1]):P.linesDf.plot.grid().sort([oe],[!1]);return e.col(se)&&(e.col(se).visible=!1),t.temp[".cliffsDfGrid"]=I,e})();const e=ee()(A.viewers).some(e=>e.dataFrame.name===`${ne}${te}`);b&&!e&&A.addViewer(I),A.dockManager.dock(I,"down",void 0,"Activity cliffs",y??.2)}});_.classList.add("scatter_plot_link","cliffs_grid");const N=s.input.toggle("Show only cliffs",{value:!1,onValueChanged:n=>{n?(e.dataFrame.setTag(ae,l[0]),t.filter.and(E.cliffsBitSet),ie.next(l[0])):(e.dataFrame.setTag(ae,""),t.filter.setAll(!0),ie.next(""))}});e.root.prepend(s.divH([_,N.root],"cliffs_div")),ie.subscribe(e=>{N.enabled=""===e||e===l[0]}),t.onRowsFiltering.subscribe(()=>{N.value&&t.filter.and(E.cliffsBitSet)});const $=o.events.onViewerClosed.subscribe(t=>{t.args.viewer===e&&(I&&A.dockManager.close(I.root),$.unsubscribe(),A.subs=A.subs.filter(e=>e!==$))});A.subs.push($),P.linesDf.onCurrentCellChanged.subscribe(()=>{for(let e=0;e<P.linesDf.rowCount;e++)P.lines.widths[e]=e===P.linesDf.currentRowIdx?3:1;L.linesToRender=P.lines;const i=P.linesDf.currentCol&&P.linesDf.currentCol.name===re[1]?P.lines.to:P.lines.from,r=-1!==P.linesDf.currentRowIdx?P.linesDf.currentRowIdx:null;if(e.dataFrame.currentRowIdx=r?i[r]:-1,null!==r){const i=P.linesDf.currentRowIdx;L.currentLineId=i;const{zoomLeft:c,zoomRight:u,zoomTop:h,zoomBottom:d}=function(e,t,n,i,o,s){const r=Math.abs(n-o),a=Math.abs(i-s),l=e/r,c=t/a,u=Math.min(l,c),h=e/u*5,d=t/u*5,m=(n<o?n:o)+r/2-h/2,p=(i>s?i:s)-a/2+d/2;return{zoomLeft:m,zoomRight:m+h,zoomTop:p,zoomBottom:p-d}}(e.viewport.width,e.viewport.height,e.dataFrame.get(l[0],P.lines.from[i]),e.dataFrame.get(l[1],P.lines.from[i]),e.dataFrame.get(l[0],P.lines.to[i]),e.dataFrame.get(l[1],P.lines.to[i]));e.zoom(c,h,u,d),N.value?t.filter.and(E.cliffsBitSet):!0===N.enabled&&t.filter.setAll(!0),setTimeout(()=>{!function(e,t,n,i,r,a,l,c,u){const h=t.getPane("Cliff Details");s.empty(h.root);const d=u({points:[n,i],lineId:r,df:e,seqCol:a,activityCol:l,sali:c});h.root.append(d),setTimeout(()=>{o.shell.o=t.root},500)}(t,v,P.lines.from[r],P.lines.to[r],r,n,a,P.linesDf.get(oe,r),g);const i=e.dataFrame.getSortedOrder(A.grid.sortByColumns,A.grid.sortTypes);A.grid.scrollToCell(n.name,i.indexOf(e.dataFrame.currentRowIdx))},1e3)}}),P.linesDf.onSelectionChanged.subscribe(e=>{setTimeout(()=>(()=>{const e=r.BitSet.create(t.rowCount);for(let t=0;t<P.linesDf.rowCount;t++){const n=P.linesDf.selection.get(t);n&&(e.set(P.lines.from[t],!0),e.set(P.lines.to[t],!0)),P.lines.colors[t]=n?"255,255,0":"0,128,0"}t.selection.copyFrom(e),L.linesToRender=P.lines})(),100)}),t.onSelectionChanged.subscribe(e=>{!1===t.selection.anyTrue&&"number"==typeof e&&(!C&&I?.dataFrame?(e=>{e.selection.setAll(!1);for(let e=0;e<P.lines.colors.length;e++)P.lines.colors[e]="0,128,0";L.linesToRender=P.lines})(I.dataFrame):C=!1)}),L.lineClicked.subscribe(e=>{if(C=!0,L.currentLineId=e.id,-1!==e.id){const n=P.linesDf.selection.clone();setTimeout(()=>{if(e.event.ctrlKey?(n.set(e.id,!n.get(e.id)),P.linesDf.selection.copyFrom(n)):(P.linesDf.currentRowIdx!==e.id&&(P.linesDf.currentRowIdx=e.id,t.currentRowIdx=P.lines.from[e.id]),P.linesDf.selection.copyFrom(n)),I?.dataFrame){const t=P.linesDf.getSortedOrder(I.sortByColumns,I.sortTypes);I.scrollToCell(re[0],t.indexOf(e.id))}},500)}}),L.lineHover.pipe((0,R.debounceTime)(500)).subscribe(e=>{-1!==e.id&&-1===t.mouseOverRowIdx&&s.tooltip.show(p({lineId:e.id,points:[P.lines.from[e.id],P.lines.to[e.id]],df:t,seqCol:n,activityCol:a}),e.x,e.y)}),e.addProperty("similarityLimit","double",w),v=function(){const e=s.accordion(),t=s.element("i");return t.className="grok-icon svg-icon svg-view-layout",e.addTitle(s.span([t,s.label("Activity cliffs")])),e.addPane("Cliff Details",()=>s.divText("Cliff has not been selected"),!0),o.shell.o=e.root,e}()}var ce=n(6863),ue=n(2003),he=n(3516),de=n(3151),me=n(4025),pe=n(439);function ge(e,t){const n=e=>o[e]??null,i=e=>{const t=a.columns.addNewString((e+1).toString());return o.push(t),t},o=[],s=e.length,a=r.DataFrame.create(s),l=t.getSeqHandler(e);for(let e=0;e<s;++e){const t=l.getSplitted(e);for(let o=0;o<t.length;++o){const s=t.getOriginal(o);(n(o)||i(o)).set(e,s,!1)}}const c=e.temp[me.j.notationProvider]??null,u=c?.monomerCanonicalizerFuncName;if(u)for(const e of o)e.setTag(pe.jz,u);return a}var fe,ye=n(4971);async function be(e){const t=(await(0,ye.pj)()).getMonomerLib(),n=[],i={},s=e.map(e=>t.getMonomer("PEPTIDE",e)?.smiles??""),a=r.Column.fromStrings("smiles",s);for(let t=0;t<s.length;++t){i[e[t]]=t;const r=s[t],l=""===r?new Array(s.length).fill(0):(await o.chem.getSimilarities(a,r)).getRawData();l[t]=1,n[t]=Array.from(l)}return{scoringMatrix:n,alphabetIndexes:i}}!function(e){e.IDENTITY="identity",e.SIMILARITY="similarity"}(fe||(fe={}));var we=n(9192);class ve{constructor(){this.maxIterations={uiName:"Max iterations",value:0,tooltip:"Maximum iterations for MCL process.Default is \n 0 which will construct the clusters with plain sparse matrix. Values greater than 0 will \n perform MCL with the given number of iterations and will result in trans-cluster activity cliff lines."},this.useWebGPU={uiName:"Use WebGPU",value:!1,tooltip:"Use WebGPU for MCL calculation. (Experimental)",type:"boolean"}}}class Ce extends N{constructor(e={}){super({...e,enableMCL:!0});const t=Array.from(this.tableInput.value.columns.numericalNoDateTime);this.activitiesInput=s.input.column("Activities",{table:this.tableInput.value,value:t.length?t[0]:null,filter:e=>t.includes(e)}),this.activitiesInputRoot=this.activitiesInput.root,this.similarityInput=s.input.int("Similarity cutoff",{value:80}),this.methodsParams[I]=new ve}onTableInputChanged(){if(super.onTableInputChanged(),this.activitiesInputRoot){s.empty(this.activitiesInputRoot);const e=Array.from(this.tableInput.value.columns.numerical);this.activitiesInput=s.input.column("Activities",{table:this.tableInput.value,value:e.length?e[0]:null,filter:t=>e.includes(t)}),Array.from(this.activitiesInput.root.children).forEach(e=>this.activitiesInputRoot.append(e))}}getEditor(){return s.div([this.tableInput,this.colInputRoot,this.preprocessingFunctionInputRoot,this.preprocessingFuncSettingsDiv,this.activitiesInputRoot,this.similarityMetricInputRoot,this.methodInput,this.methodSettingsDiv,this.similarityMetricInputRoot,this.similarityInput],{style:{minWidth:"320px"},classes:"ui-form dim-reduction-dialog-form"})}getParams(){return{...super.getParams(),activities:this.activitiesInput.value,similarityThreshold:this.similarityInput.value}}getInput(){return{...super.getInput(),activityCol:this.activitiesInput.value.name,simThreshold:this.similarityInput.value}}async applyInput(e){super.applyInput(e),this.activitiesInput.value=this.tableInput.value.col(e.activityCol),this.similarityInput.value=e.simThreshold}}var Ae,Te,Ee;function Se(e){const t=["Embed_X","Embed_Y"],n=e.columns.names().filter(e=>e.includes(t[0])).length+1;return t.map(e=>`${e}_${n}`)}function Me(e,t){return`${t} (${e.length>4?`${e.length} columns`:e.map(e=>e.name).join(", ")})`}async function xe(e,t,i,l,c,u,h,d=!0,m=!1,p={preprocessingFuncArgs:[]},g={},f=null,y={},b){const w={showXAxis:!1,showYAxis:!1,showXSelector:!1,showYSelector:!1};if(t.length!==l.length||t.length!==u.length||t.length!==c.length||t.length!==p.preprocessingFuncArgs.length)throw new Error("columns, metrics and preprocessing functions, weights and function argumentsmust have the same length");const v=d?g.tableView??o.shell.tableView(e.name)??o.shell.addTableView(e):null,C=async()=>{const C=r.TaskBarProgressIndicator.create(`Initializing ${g.scatterPlotName??"dimensionality reduction"} ...`);let A;try{const T=g.embedColsNames??Se(e);function E(n,o,l){let c=null,u=null;e.columns.names().includes(T[0])?(c=e.columns.byName(T[0]),u=e.columns.byName(T[1])):(c=e.columns.add(r.Column.float(T[0],e.rowCount)),u=e.columns.add(r.Column.float(T[1],e.rowCount)),d&&!A&&(A=v.scatterPlot({...w,x:T[0],y:T[1],title:g.scatterPlotName??Me(t,i)}))),g[a.YP]&&(A?.root&&s.setUpdateIndicator(A.root,!1),c.init(e=>l[0]?l[0][e]:void 0),u.init(e=>l[1]?l[1][e]:void 0));const h=n/o*100;C.update(h,`Running ${g.scatterPlotName??"dimensionality reduction"}... ${h.toFixed(0)}%`)}async function S(){e.columns.add(r.Column.float(T[0],e.rowCount)),e.columns.add(r.Column.float(T[1],e.rowCount));let n=null;d&&(A=v.scatterPlot({...w,x:T[0],y:T[1],title:g.scatterPlotName??Me(t,i)}),s.setUpdateIndicator(A.root,!0));const m=o.events.onViewerClosed.subscribe(e=>{const t=e.args.viewer;t?.getOptions()?.look?.title&&A?.getOptions()?.look?.title&&t?.getOptions()?.look?.title===A?.getOptions()?.look?.title&&(o.events.fireCustomEvent(V,{}),m.unsubscribe(),n?.(),C.close())}),f=new Promise(async(o,s)=>{try{n=o;const s=[];let r=l,d=c,m=h;if(b&&t.every(e=>e.isNumerical)){const n=t.map(e=>e.toList()),i=new Array(e.rowCount).fill(0).map((e,n)=>new Float32Array(t.length));for(let o=0;o<t.length;++o)for(let t=0;t<e.rowCount;++t)i[t][o]=n[o][t];p.distanceFnArgs=[{}],s.push({entries:i,options:{}}),r=[b],d=[1],m="MANHATTAN"}else for(let e=0;e<u.length;++e){const n=u[e];if(p.distanceFnArgs||(p.distanceFnArgs=[]),n){const i=n.inputs[0].name,o=n.inputs[1].name,{entries:r,options:a}=await n.apply({[i]:t[e],[o]:l[e],...p.preprocessingFuncArgs[e]??{}});s.push({entries:r,options:a}),p.distanceFnArgs.push(a)}else{const n=t[e].toList(),i={};s.push({entries:n,options:i}),p.distanceFnArgs.push(i)}}o(await W(s.map(e=>e.entries),i,r,d,h,p,g[a.vb]?void 0:E))}catch(e){s(e)}}),y=await f;return C.close(),m.unsubscribe(),y}const M=await S();if(m&&M){const x=r.TaskBarProgressIndicator.create("Clustering embeddings ...");try{const P=await function(e,t,i,o){return function(e,t,n,i){return new(n||(n=Promise))(function(o,s){function r(e){try{l(i.next(e))}catch(e){s(e)}}function a(e){try{l(i.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})}(this,void 0,void 0,function*(){return new Promise(function(s,r){const a=new Worker(new URL(n.p+n.u(682),n.b));a.postMessage({embedX:e,embedY:t,minPts:o,epsilon:i}),a.onmessage=({data:{error:e,clusters:t}})=>{a.terminate(),e?r(e):s(t)}})})}(M[0],M[1],p.dbScanEpsilon??.01,p.dbScanMinPts??4),L=g.clusterColName??e.columns.getUnusedName("Cluster (DBSCAN)");e.columns.addNewString(L).init(e=>P[e].toString()),A&&(A.props.colorColumnName=L)}catch(I){o.shell.error("Clustering embeddings failed"),console.error(I)}finally{x.close()}}if(M){const _=e.columns.byName(T[0]),N=e.columns.byName(T[1]);if(_.init(e=>M[0][e]),N.init(e=>M[1][e]),f)try{const R=f.inputs[0].name,$=f.inputs[1].name;await f.prepare({[R]:_,[$]:N,...y}).call(!0)}catch(O){o.shell.error("Post-processing failed"),console.error(O)}if(A)return s.setUpdateIndicator(A.root,!1),A.helpUrl="/help/compute/sequence-space",A}}catch(H){o.shell.error("Dimensionality reduction failed"),console.error(H),C.close(),A&&s.setUpdateIndicator(A.root,!1)}};return new Promise(async(t,n)=>{try{if(g.fastRowCount&&e.rowCount>g.fastRowCount&&!g[a.vb])s.dialog().add(s.divText("Analysis might take several minutes. Do you want to continue?")).onOK(async()=>{try{const e=await C();t(e)}catch(e){n(e)}}).onCancel(()=>t(void 0)).show();else{const e=await C();t(e)}}catch(e){n(e)}})}n(5540),function(e){e.ADD="ADD",e.SUB="SUB",e.MULT="MULT"}(Ae||(Ae={})),function(e){e.SQUARE="SQUARE",e.INVERSE="INVERSE",e.TRANSPOSE="TRANSPOSE",e.NORM="NORM",e.COLUMN_NORM="COLUMN_NORM"}(Te||(Te={})),function(e){e.SCALARMULT="SCALARMULT",e.SCALARADD="SCALARADD",e.SCALARPOW="SCALARPOW"}(Ee||(Ee={})),Object.prototype.toString;var Pe=n(6873),Le=n(4356),Ie=n(6717);function _e(e){var t;if((null===(t=o.shell.tv)||void 0===t?void 0:t.dataFrame)===e)return;const n=o.shell.tableView(e.name);n?o.shell.v=n:o.shell.addTableView(e)}var Ne=n(4870),Re=n(3856),$e=n(819),Oe=n(7278),He=n(5553),De=n(6642),Fe=n(3599),ke=n(673),Ge=n(8312);class Be extends De.sD{monomerLib=null;seqHelper=null;constructor(e,t){super(e,t,Uo.logger),(0,ye.pj)().then(e=>{this.monomerLib=e.getMonomerLib(),this.dirty=!0,this.gridCol?.grid?.invalidate(),this.subs.push(this.monomerLib.onChanged.subscribe(()=>{this.dirty=!0,this.gridCol?.grid?.invalidate()}))}),(0,Ge.Q)().then(e=>{this.seqHelper=e,this.dirty=!0,this.gridCol?.grid?.invalidate()})}}var Ve=n(4139);const Ue=ue.zS;function qe(e){const t=!ee().enumerate(e).some(([t,n])=>t.length>1&&0!=n&&n!=e.length-1),n=[],i=t?"":" ";for(const[t,o]of ee().enumerate(e)){let s=t;o<e.length&&(s+=`${t?"":"-"}${i}`),n.push(s)}return[n,t]}class We extends r.GridCellRenderer{seqHelper;get name(){return"sequence"}get cellType(){return"sequence"}get defaultHeight(){return 30}get defaultWidth(){return 230}hasMouseOver=!1;constructor(){super(),this.seqHelper=Uo.seqHelper}getRendererBack(e){const[t,n,i]=(0,De.BG)(e);if(i.rendererBack)return i.rendererBack;let o=null;return this.seqHelper&&(o=this.seqHelper.getSeqHandler(n).getRendererBack(t,n)),o}onClick(e,t){e.cell.column.temp["current-word"]=e.cell.value,e.grid.invalidate();const n=this.getRendererBack(e);n?.onClick(e,t)}onMouseEnter(e,t){const n=this.getRendererBack(e);n?.onMouseEnter(e,t),this.hasMouseOver=!0}onMouseMove(e,t){const n=this.getRendererBack(e);n?.onMouseMove(e,t)}onMouseLeave(e,t){if((0,He.WN)(e,null),e?.grid){const t=e.grid.onEvent("d4-grid-show-tooltip").subscribe(e=>{t.unsubscribe(),this.hasMouseOver&&e.preventDefault()})}this.hasMouseOver=!1}onDoubleClick(e,t){const n=this.getRendererBack(e);n?.onDoubleClick(e,t)}onKeyDown(e,t){const n=this.getRendererBack(e);n?.onKeyDown(e,t)}onKeyPress(e,t){const n=this.getRendererBack(e);n?.onKeyPress(e,t)}renderInt(e,t,n,i,o,s,r){const[a,l,c]=(0,De.BG)(s);if(!l)return;const u=l.temp,h=this.seqHelper.getSeqHandler(l);let d=(Uo.properties?Uo.properties.maxMonomerLength:4)??50;if(Re.gp.maxMonomerLength in l.tags){const e=parseInt(l.getTag(Re.gp.maxMonomerLength));d=!isNaN(e)&&e?e:50}if(".mm.cellRenderer.maxMonomerLength"in u){const e=u[".mm.cellRenderer.maxMonomerLength"];d=!isNaN(e)&&e?e:50}let m=c.rendererBack;m||(m=c.rendererBack=new $e.Jy(a,l,Uo.logger,d,()=>{const{font:e,fontWidth:t}=$e.Jy.getFontSettings(l);return{font:e,fontCharWidth:t,separatorWidth:h.isMsa()?8:0,monomerToShort:Ue}}),l.temp[".mm.cellRenderer.settingsChanged"],ke.s.true,m.init().then(()=>{})),m.render(e,t,n,i,o,s,r)}render(e,t,n,i,o,s,r){const a=this.getRendererBack(s);a?a?.render(e,t,n,i,o,s,r):this.renderInt(e,t,n,i,o,s,r)}}class Ye extends Be{constructor(e,t){super(e,t)}render(e,t,n,i,o,s,r){const a=window.devicePixelRatio,l=s.grid,c=s.cell.value??"",u=this.tableCol.tags[ue.gp.separator];let h=this.tableCol.meta.units;i=(0,$e.U0)(l,e,t,i,a);const[d,m]=c.split("#");h!==ue.Hi.CUSTOM||this.tableCol.temp[me.j.notationProvider]||(h=ue.Hi.SEPARATOR);const p=this.tableCol.temp[me.j.notationProvider]?.separatorSplitter??this.tableCol.temp[me.j.notationProvider]?.splitter??(0,Oe.Iv)(h,u),g=p(d),f=p(m),y=ee().count(0).take(g.length).map(e=>g.getOriginal(e)).toArray(),b=ee().count(0).take(f.length).map(e=>f.getOriginal(e)).toArray(),w=this.tableCol.getTag(ue.gp.alphabet);Ke(e,t,n,i,o,y,b,w===ue.YI.RNA||w===ue.YI.DNA?Fe.o.NUCLEOTIDE:Fe.o.AA,this.monomerLib,void 0,void 0)}async awaitRendered(e=1e4,t=`${e} timeout`){return Promise.resolve()}static getOrCreate(e){const[t,n,i]=(0,De.BG)(e);let o=i.rendererBack;return o||(o=i.rendererBack=new Ye(t,n)),o}}class je extends r.GridCellRenderer{get name(){return"MacromoleculeDifferenceCR"}get cellType(){return Ve.uF.MACROMOLECULE_DIFFERENCE}get defaultHeight(){return 30}get defaultWidth(){return 230}render(e,t,n,i,o,s,r){Ye.getOrCreate(s).render(e,t,n,i,o,s,r)}}function Ke(e,t,n,i,o,s,r,a,l,c,u){if(s.length!==r.length){const e=function(e,t){let n=0,i=0;const o=e.length>t.length?e:t,s=e.length>t.length?t:e;for(let e=0;e<s.length;e++)o[e]===s[e]&&n++;const r=o.length-s.length;for(let e=o.length-1;e>r;e--)o[e]===s[e-r]&&i++;const a=new Array(Math.abs(e.length-t.length)).fill(pe.b9[ue.Hi.FASTA]);function l(e){return n>i?e.concat(a):a.concat(e)}return e.length>t.length?t=l(ee()(t).toArray()):e=l(ee()(e).toArray()),{subParts1:e,subParts2:t}}(s,r);s=e.subParts1,r=e.subParts2}const h=e.measureText(qe(s).join("")),d=e.measureText(qe(r).join("")),m=Math.max(h.width,d.width);c&&(i=m+4*s.length,e.canvas.width=m+4*s.length);let p=Math.max(t,t+(i-(m+4*s.length))/2)+5;const g=Math.max(n,n+(o-28)/2);e.save();try{e.beginPath(),e.rect(t,n,c?m+4*s.length:i,o),e.clip(),e.font="12px monospace",e.textBaseline="top";const h=7;for(let t=0;t<s.length;t++){const n=s[t],c=r[t];let d=$e.S$;if(l&&(d=l.getMonomerTextColor(a,n)),n!=c){let s=$e.S$;l&&(s=l.getMonomerTextColor(a,c));const r=(0,Re.oZ)(e,n,p,g-h,i,o,{color:d,pivot:0,left:!0}),m=(0,Re.oZ)(e,c,p,g+h,i,o,{color:s,pivot:0,left:!0});p=Math.max(m,r),u&&(u[t]=ze(n,c,d,s,g,h,o))}else p=(0,Re.oZ)(e,n,p,g,i,o,{color:d,pivot:0,left:!0,transparencyRate:.5});p+=4}}finally{e.restore()}}function ze(e,t,n,i,o,s,r){const a=document.createElement("canvas"),l=a.getContext("2d");l.font="12px monospace";const c=l.measureText(qe([e]).join("")).width,u=l.measureText(qe([t]).join("")).width,h=Math.max(c,u);return a.height=r,a.width=h+4,l.font="12px monospace",l.textBaseline="top",(0,Re.oZ)(l,e,0,o-s,h,r,{color:n,pivot:0,left:!0}),(0,Re.oZ)(l,t,0,o+s,h,r,{color:i,pivot:0,left:!0}),a}var Ze,Xe=n(8070),Qe=n(4326);!function(e){e.Unknown="unknown",e.FR="framework",e.CDR="cdr"}(Ze||(Ze={}));const Je=new class{constructor(){this.regionTypes=[Ze.CDR],this.chains=["Heavy","Light"],this.skipEmptyPositions=!1,this.fitWidth=!1,this.positionWidth=16,this.positionHeight=Qe.fH.Entropy,this.filterSource=Qe.Fo.filterSource}};var et=n(7602),tt=n(250);const nt=Ze;var it,ot;!function(e){e.STYLE="Style",e.BEHAVIOR="Behavior",e.LAYOUT="Layout",e.DATA="Data"}(it||(it={})),function(e){e.skipEmptyPositions="skipEmptyPositions",e.regionTypes="regionTypes",e.chains="chains",e.fitWidth="fitWidth",e.positionWidth="positionWidth",e.positionHeight="positionHeight",e.filterSource="filterSource"}(ot||(ot={}));const st=Je;class rt extends r.JsViewer{viewed=!1;regionsFg=null;regionsRoot=null;isOpened=!1;panelNode=null;regions=[];regionTypes;chains;skipEmptyPositions;fitWidth;positionWidth;positionHeight;filterSource;constructor(){super(),this.skipEmptyPositions=this.bool(ot.skipEmptyPositions,st.skipEmptyPositions,{category:it.DATA}),this.regionTypes=this.stringList(ot.regionTypes,st.regionTypes,{category:it.DATA,choices:Object.values(nt).filter(e=>e!=nt.Unknown)}),this.chains=this.stringList(ot.chains,st.chains,{category:it.DATA,choices:["Heavy","Light"]}),this.fitWidth=this.bool(ot.fitWidth,st.fitWidth,{category:it.LAYOUT}),this.positionWidth=this.float(ot.positionWidth,st.positionWidth,{category:it.LAYOUT,editor:"slider",min:0,max:64,description:"Internal WebLogo viewers property width of position."}),this.positionHeight=this.string(ot.positionHeight,st.positionHeight,{category:it.LAYOUT,choices:Object.keys(Qe.fH)}),this.filterSource=this.string(ot.filterSource,st.filterSource,{category:it.BEHAVIOR,choices:Object.values(Qe.lT)}),this.viewSyncer=new et.g(Uo.logger)}static viewerCounter=-1;viewerId=++rt.viewerCounter;viewerToLog(){return`VdRegionsViewer<${this.viewerId}>`}async init(){this.subs.push((0,c.fromEvent)(this.root,"mousemove").subscribe(this.rootOnMouseMove.bind(this)))}detach(){const e=`${this.viewerToLog()}.detach()`,t=super.detach.bind(this);this.viewSyncer.sync(`${e}`,async()=>{this.setDataInProgress||(this.viewed&&(await this.destroyView("detach"),this.viewed=!1),t())})}onTableAttached(){super.onTableAttached(),this.setData(this.regions)}onPropertyChanged(e){if(super.onPropertyChanged(e),e){switch(e.name){case ot.regionTypes:case ot.chains:this.setData(this.regions)}switch(e.name){case ot.skipEmptyPositions:for(let e=0;e<this.logos.length;++e)for(const t of this.chains)this.logos[e][t].setOptions({[tt.n5.skipEmptyPositions]:this.skipEmptyPositions});this.calcSize();break;case ot.fitWidth:case ot.positionWidth:this.calcSize();break;case ot.positionHeight:for(let e=0;e<this.logos.length;++e)for(const t of this.chains)this.logos[e][t].setOptions({[tt.n5.positionHeight]:this.positionHeight});this.calcSize();break;case ot.filterSource:this.filterSourceInput.value=this.filterSource;break;default:this.setData(this.regions)}}else console.warn("Bio: VdRegionsViewer.onPropertyChanged() property is null")}setData(e){const t=`${this.viewerToLog()}.setData()`;Uo.logger.debug(`${t}, in, regions.length = ${e.length}`),this.viewSyncer.sync(`${t}`,async()=>{if(!this.setDataInProgress){this.setDataInProgress=!0;try{this.viewed&&(await this.destroyView("setData"),this.viewed=!1),this.regions=e,this.viewed||(await this.buildView("setData"),this.viewed=!0)}finally{this.setDataInProgress=!1}}})}viewSyncer;setDataInProgress=!1;host=null;filterSourceInput;mainLayout=null;logos=[];viewSubs=[];async destroyView(e){Uo.logger.debug(`Bio: VdRegionsViewer.destroyView( mainLayout = ${this.mainLayout?"value":"none"} ), purpose = '${e}', this.regions.length = ${this.regions.length}`),this.filterSourceInput&&s.empty(this.filterSourceInput.root),null!=this.mainLayout&&(this.mainLayout.remove(),this.host.remove(),this.host=null,this.mainLayout=null);for(const e of this.viewSubs)e.unsubscribe()}async buildView(e){Uo.logger.debug(`Bio: VdRegionsViewer.buildView() begin, purpose = '${e}', this.regions.length = ${this.regions.length}`);const t=this.regions.filter(e=>this.regionTypes.includes(e.type)),n=Array.from(new Set(t.map(e=>e.order))).sort(),i=[];for(let e=0;e<n.length;e++)for(const o of this.chains){const s=t.find(t=>t.order==n[e]&&t.chain==o);s&&i.push((async()=>{const t=await this.dataFrame.plot.fromType("WebLogo",{sequenceColumnName:s.sequenceColumnName,startPositionName:s.positionStartName,endPositionName:s.positionEndName,fixWidth:!0,skipEmptyPositions:this.skipEmptyPositions,positionWidth:this.positionWidth,positionHeight:this.positionHeight,filterSource:this.filterSource});return t.onSizeChanged.subscribe(()=>{this.calcSize()}),[e,o,t]})())}const o=await Promise.all(i);this.logos=new Array(n.length);for(let e=0;e<n.length;++e)this.logos[e]={};for(const[e,t,n]of o)this.logos[e][t]=n,this.viewSubs.push(n.onFreqsCalculated.subscribe(()=>{this.calcSize()}));this.mainLayout=s.table(this.chains,e=>[...n.length>0?[s.div(e,{style:{transform:"rotate(-90deg)",font:"12px Roboto, Roboto Local, sans-serif",textAlign:"center",width:"16px",marginTop:"24px",marginLeft:"6px"}})]:[],...[...Array(n.length).keys()].map(t=>{const n=this.logos[t][e];return n.root.style.height="100%",s.div([n.root],{style:{marginTop:"4px",marginBottom:"4px"}})})],["",...[...Array(n.length).keys()].map(e=>t.find(t=>t.order==n[e]&&t.chain==this.chains[0]).name||"Name")]),this.mainLayout.className="mlb-vd-regions-viewer-table2",this.filterSourceInput=s.input.choice("Data source",{value:this.filterSource,items:Object.values(Qe.lT),onValueChanged:this.filterSourceInputOnValueChanged.bind(this)}),this.filterSourceInput.root.style.position="absolute",this.filterSourceInput.root.style.right="9px",this.filterSourceInput.root.style.top="-4px",Math.ceil(255*Math.random()).toString(16),this.host=s.div([this.mainLayout,this.filterSourceInput.root],{}),this.root.appendChild(this.host),this.root.style.overflowX="auto",this.calcSize(),this.viewSubs.push(s.onSizeChanged(this.root).subscribe(this.rootOnSizeChanged.bind(this))),Uo.logger.debug("Bio: VdRegionsViewer.buildView() end")}calcSizeRequested=!1;calcSize(){Uo.logger.debug("Bio: VdRegionsViewer.calcSize(), start");const e=()=>{if(!this.host)return;const e=(this.root.clientHeight-54)/this.chains.length;let t=0;for(let n=0;n<this.logos.length;n++){for(const t of this.chains)this.logos[n][t].root.style.height=`${e}px`;t+=Math.max(...this.chains.map(e=>this.logos[n][e].Length))}if(this.fitWidth){if(this.logos.length>0&&t>0){const e=22,n=13,i=9,o=(this.root.clientWidth-e-(this.logos.length-1)*i-n)/t;for(let e=0;e<this.logos.length;e++)for(const t of this.chains){const n=this.logos[e][t];n.setOptions({[tt.n5.positionWidth]:o-n.positionMarginValue}),n.root.style.width=o*n.Length+"px"}}this.host.style.setProperty("overflow","hidden","important")}else{for(let e=0;e<this.logos.length;e++)for(const t of this.chains)this.logos[e][t].setOptions({[tt.n5.positionWidth]:this.positionWidth});this.host.style.removeProperty("overflow")}0===this.positionWidth?this.host.style.setProperty("overflow-x","hidden","important"):this.host.style.removeProperty("overflow-x")};this.calcSizeRequested||(this.calcSizeRequested=!0,window.setTimeout(()=>{e(),this.calcSizeRequested=!1},0))}rootOnSizeChanged(e){this.calcSize()}rootOnMouseMove(e){}filterSourceInputOnValueChanged(){const e=`${this.viewerToLog()}.filterSourceInputOnValueChanged()`,t=this.filterSourceInput.value;this.viewSyncer.sync(`${e}`,async()=>{if(this.filterSource!==t){this.props.getProperty(ot.filterSource).set(this,t);for(let e=0;e<this.logos.length;e++)for(let t=0;t<this.chains.length;t++){const n=this.chains[t];this.logos[e][n].setOptions({[tt.n5.filterSource]:this.filterSource})}}})}_onRendered=new c.Subject;get onRendered(){return this._onRendered}invalidate(e){const t=`${this.viewerToLog()}.invalidate(${e?` <- ${e} `:""})`;this.viewSyncer.sync(`${t}`,async()=>{this._onRendered.next()})}async awaitRendered(e=5e3){await(0,Xe.PE)(this.onRendered,()=>{},()=>{this.invalidate()},e);const t=this.viewSyncer.resetErrors();if(t.length>0)throw t[0]}}class at{value;parentI;parentJ;constructor(){this.value=0,this.parentI=0,this.parentJ=0}}class lt{seq1;seq2;score;constructor(e,t,n){this.seq1=e,this.seq2=t,this.score=n}}class ct{seq1="";seq2="";gap=1;len1=0;len2=0;step=1;alignGrid=[];scores=[];dpGrid=[];connections={};BLOSUM45=[[5,-2,-1,-2,-1,-1,-1,0,-2,-1,-1,-1,-1,-2,-1,1,0,-2,-2,0,-1,-1,0,-5],[-2,7,0,-1,-3,1,0,-2,0,-3,-2,3,-1,-2,-2,-1,-1,-2,-1,-2,-1,0,-1,-5],[-1,0,6,2,-2,0,0,0,1,-2,-3,0,-2,-2,-2,1,0,-4,-2,-3,4,0,-1,-5],[-2,-1,2,7,-3,0,2,-1,0,-4,-3,0,-3,-4,-1,0,-1,-4,-2,-3,5,1,-1,-5],[-1,-3,-2,-3,12,-3,-3,-3,-3,-3,-2,-3,-2,-2,-4,-1,-1,-5,-3,-1,-2,-3,-2,-5],[-1,1,0,0,-3,6,2,-2,1,-2,-2,1,0,-4,-1,0,-1,-2,-1,-3,0,4,-1,-5],[-1,0,0,2,-3,2,6,-2,0,-3,-2,1,-2,-3,0,0,-1,-3,-2,-3,1,4,-1,-5],[0,-2,0,-1,-3,-2,-2,7,-2,-4,-3,-2,-2,-3,-2,0,-2,-2,-3,-3,-1,-2,-1,-5],[-2,0,1,0,-3,1,0,-2,10,-3,-2,-1,0,-2,-2,-1,-2,-3,2,-3,0,0,-1,-5],[-1,-3,-2,-4,-3,-2,-3,-4,-3,5,2,-3,2,0,-2,-2,-1,-2,0,3,-3,-3,-1,-5],[-1,-2,-3,-3,-2,-2,-2,-3,-2,2,5,-3,2,1,-3,-3,-1,-2,0,1,-3,-2,-1,-5],[-1,3,0,0,-3,1,1,-2,-1,-3,-3,5,-1,-3,-1,-1,-1,-2,-1,-2,0,1,-1,-5],[-1,-1,-2,-3,-2,0,-2,-2,0,2,2,-1,6,0,-2,-2,-1,-2,0,1,-2,-1,-1,-5],[-2,-2,-2,-4,-2,-4,-3,-3,-2,0,1,-3,0,8,-3,-2,-1,1,3,0,-3,-3,-1,-5],[-1,-2,-2,-1,-4,-1,0,-2,-2,-2,-3,-1,-2,-3,9,-1,-1,-3,-3,-3,-2,-1,-1,-5],[1,-1,1,0,-1,0,0,0,-1,-2,-3,-1,-2,-2,-1,4,2,-4,-2,-1,0,0,0,-5],[0,-1,0,-1,-1,-1,-1,-2,-2,-1,-1,-1,-1,-1,-1,2,5,-3,-1,0,0,-1,0,-5],[-2,-2,-4,-4,-5,-2,-3,-2,-3,-2,-2,-2,-2,1,-3,-4,-3,15,3,-3,-4,-2,-2,-5],[-2,-1,-2,-2,-3,-1,-2,-3,2,0,0,-1,0,3,-3,-2,-1,3,8,-1,-2,-2,-1,-5],[0,-2,-3,-3,-1,-3,-3,-3,-3,3,1,-2,1,0,-3,-1,0,-3,-1,5,-3,-3,-1,-5],[-1,-1,4,5,-2,0,1,-1,0,-3,-3,0,-2,-3,-2,0,0,-4,-2,-3,4,2,-1,-5],[-1,0,0,1,-3,4,4,-2,0,-3,-2,1,-1,-3,-1,0,-1,-2,-2,-3,2,4,-1,-5],[0,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,0,-2,-1,-1,-1,-1,-1,-5],[-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,1]];BLOSUM50=[[5,-2,-1,-2,-1,-1,-1,0,-2,-1,-2,-1,-1,-3,-1,1,0,-3,-2,0,-2,-1,-1,-5],[-2,7,-1,-2,-4,1,0,-3,0,-4,-3,3,-2,-3,-3,-1,-1,-3,-1,-3,-1,0,-1,-5],[-1,-1,7,2,-2,0,0,0,1,-3,-4,0,-2,-4,-2,1,0,-4,-2,-3,4,0,-1,-5],[-2,-2,2,8,-4,0,2,-1,-1,-4,-4,-1,-4,-5,-1,0,-1,-5,-3,-4,5,1,-1,-5],[-1,-4,-2,-4,13,-3,-3,-3,-3,-2,-2,-3,-2,-2,-4,-1,-1,-5,-3,-1,-3,-3,-2,-5],[-1,1,0,0,-3,7,2,-2,1,-3,-2,2,0,-4,-1,0,-1,-1,-1,-3,0,4,-1,-5],[-1,0,0,2,-3,2,6,-3,0,-4,-3,1,-2,-3,-1,-1,-1,-3,-2,-3,1,5,-1,-5],[0,-3,0,-1,-3,-2,-3,8,-2,-4,-4,-2,-3,-4,-2,0,-2,-3,-3,-4,-1,-2,-2,-5],[-2,0,1,-1,-3,1,0,-2,10,-4,-3,0,-1,-1,-2,-1,-2,-3,2,-4,0,0,-1,-5],[-1,-4,-3,-4,-2,-3,-4,-4,-4,5,2,-3,2,0,-3,-3,-1,-3,-1,4,-4,-3,-1,-5],[-2,-3,-4,-4,-2,-2,-3,-4,-3,2,5,-3,3,1,-4,-3,-1,-2,-1,1,-4,-3,-1,-5],[-1,3,0,-1,-3,2,1,-2,0,-3,-3,6,-2,-4,-1,0,-1,-3,-2,-3,0,1,-1,-5],[-1,-2,-2,-4,-2,0,-2,-3,-1,2,3,-2,7,0,-3,-2,-1,-1,0,1,-3,-1,-1,-5],[-3,-3,-4,-5,-2,-4,-3,-4,-1,0,1,-4,0,8,-4,-3,-2,1,4,-1,-4,-4,-2,-5],[-1,-3,-2,-1,-4,-1,-1,-2,-2,-3,-4,-1,-3,-4,10,-1,-1,-4,-3,-3,-2,-1,-2,-5],[1,-1,1,0,-1,0,-1,0,-1,-3,-3,0,-2,-3,-1,5,2,-4,-2,-2,0,0,-1,-5],[0,-1,0,-1,-1,-1,-1,-2,-2,-1,-1,-1,-1,-2,-1,2,5,-3,-2,0,0,-1,0,-5],[-3,-3,-4,-5,-5,-1,-3,-3,-3,-3,-2,-3,-1,1,-4,-4,-3,15,2,-3,-5,-2,-3,-5],[-2,-1,-2,-3,-3,-1,-2,-3,2,-1,-1,-2,0,4,-3,-2,-2,2,8,-1,-3,-2,-1,-5],[0,-3,-3,-4,-1,-3,-3,-4,-4,4,1,-3,1,-1,-3,-2,0,-3,-1,5,-4,-3,-1,-5],[-2,-1,4,5,-3,0,1,-1,0,-4,-4,0,-3,-4,-2,0,0,-5,-3,-4,5,2,-1,-5],[-1,0,0,1,-3,4,5,-2,0,-3,-3,1,-1,-4,-1,0,-1,-2,-2,-3,2,5,-1,-5],[-1,-1,-1,-1,-2,-1,-1,-2,-1,-1,-1,-1,-1,-2,-2,-1,0,-3,-1,-1,-1,-1,-1,-5],[-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,1]];BLOSUM62=[[4,-1,-2,-2,0,-1,-1,0,-2,-1,-1,-1,-1,-2,-1,1,0,-3,-2,0,-2,-1,0,-4],[-1,5,0,-2,-3,1,0,-2,0,-3,-2,2,-1,-3,-2,-1,-1,-3,-2,-3,-1,0,-1,-4],[-2,0,6,1,-3,0,0,0,1,-3,-3,0,-2,-3,-2,1,0,-4,-2,-3,3,0,-1,-4],[-2,-2,1,6,-3,0,2,-1,-1,-3,-4,-1,-3,-3,-1,0,-1,-4,-3,-3,4,1,-1,-4],[0,-3,-3,-3,9,-3,-4,-3,-3,-1,-1,-3,-1,-2,-3,-1,-1,-2,-2,-1,-3,-3,-2,-4],[-1,1,0,0,-3,5,2,-2,0,-3,-2,1,0,-3,-1,0,-1,-2,-1,-2,0,3,-1,-4],[-1,0,0,2,-4,2,5,-2,0,-3,-3,1,-2,-3,-1,0,-1,-3,-2,-2,1,4,-1,-4],[0,-2,0,-1,-3,-2,-2,6,-2,-4,-4,-2,-3,-3,-2,0,-2,-2,-3,-3,-1,-2,-1,-4],[-2,0,1,-1,-3,0,0,-2,8,-3,-3,-1,-2,-1,-2,-1,-2,-2,2,-3,0,0,-1,-4],[-1,-3,-3,-3,-1,-3,-3,-4,-3,4,2,-3,1,0,-3,-2,-1,-3,-1,3,-3,-3,-1,-4],[-1,-2,-3,-4,-1,-2,-3,-4,-3,2,4,-2,2,0,-3,-2,-1,-2,-1,1,-4,-3,-1,-4],[-1,2,0,-1,-3,1,1,-2,-1,-3,-2,5,-1,-3,-1,0,-1,-3,-2,-2,0,1,-1,-4],[-1,-1,-2,-3,-1,0,-2,-3,-2,1,2,-1,5,0,-2,-1,-1,-1,-1,1,-3,-1,-1,-4],[-2,-3,-3,-3,-2,-3,-3,-3,-1,0,0,-3,0,6,-4,-2,-2,1,3,-1,-3,-3,-1,-4],[-1,-2,-2,-1,-3,-1,-1,-2,-2,-3,-3,-1,-2,-4,7,-1,-1,-4,-3,-2,-2,-1,-2,-4],[1,-1,1,0,-1,0,0,0,-1,-2,-2,0,-1,-2,-1,4,1,-3,-2,-2,0,0,0,-4],[0,-1,0,-1,-1,-1,-1,-2,-2,-1,-1,-1,-1,-2,-1,1,5,-2,-2,0,-1,-1,0,-4],[-3,-3,-4,-4,-2,-2,-3,-2,-2,-3,-2,-3,-1,1,-4,-3,-2,11,2,-3,-4,-3,-2,-4],[-2,-2,-2,-3,-2,-1,-2,-3,2,-1,-1,-2,-1,3,-3,-2,-2,2,7,-1,-3,-2,-1,-4],[0,-3,-3,-3,-1,-2,-2,-3,-3,3,1,-2,1,-1,-2,-2,0,-3,-1,4,-3,-2,-1,-4],[-2,-1,3,4,-3,0,1,-1,0,-3,-4,0,-3,-3,-2,0,-1,-4,-3,-3,4,1,-1,-4],[-1,0,0,1,-3,3,4,-2,0,-3,-3,1,-1,-3,-1,0,-1,-3,-2,-2,1,4,-1,-4],[0,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-2,0,0,-2,-1,-1,-1,-1,-1,-4],[-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,1]];BLOSUM80=[[7,-3,-3,-3,-1,-2,-2,0,-3,-3,-3,-1,-2,-4,-1,2,0,-5,-4,-1,-3,-2,-1,-8],[-3,9,-1,-3,-6,1,-1,-4,0,-5,-4,3,-3,-5,-3,-2,-2,-5,-4,-4,-2,0,-2,-8],[-3,-1,9,2,-5,0,-1,-1,1,-6,-6,0,-4,-6,-4,1,0,-7,-4,-5,5,-1,-2,-8],[-3,-3,2,10,-7,-1,2,-3,-2,-7,-7,-2,-6,-6,-3,-1,-2,-8,-6,-6,6,1,-3,-8],[-1,-6,-5,-7,13,-5,-7,-6,-7,-2,-3,-6,-3,-4,-6,-2,-2,-5,-5,-2,-6,-7,-4,-8],[-2,1,0,-1,-5,9,3,-4,1,-5,-4,2,-1,-5,-3,-1,-1,-4,-3,-4,-1,5,-2,-8],[-2,-1,-1,2,-7,3,8,-4,0,-6,-6,1,-4,-6,-2,-1,-2,-6,-5,-4,1,6,-2,-8],[0,-4,-1,-3,-6,-4,-4,9,-4,-7,-7,-3,-5,-6,-5,-1,-3,-6,-6,-6,-2,-4,-3,-8],[-3,0,1,-2,-7,1,0,-4,12,-6,-5,-1,-4,-2,-4,-2,-3,-4,3,-5,-1,0,-2,-8],[-3,-5,-6,-7,-2,-5,-6,-7,-6,7,2,-5,2,-1,-5,-4,-2,-5,-3,4,-6,-6,-2,-8],[-3,-4,-6,-7,-3,-4,-6,-7,-5,2,6,-4,3,0,-5,-4,-3,-4,-2,1,-7,-5,-2,-8],[-1,3,0,-2,-6,2,1,-3,-1,-5,-4,8,-3,-5,-2,-1,-1,-6,-4,-4,-1,1,-2,-8],[-2,-3,-4,-6,-3,-1,-4,-5,-4,2,3,-3,9,0,-4,-3,-1,-3,-3,1,-5,-3,-2,-8],[-4,-5,-6,-6,-4,-5,-6,-6,-2,-1,0,-5,0,10,-6,-4,-4,0,4,-2,-6,-6,-3,-8],[-1,-3,-4,-3,-6,-3,-2,-5,-4,-5,-5,-2,-4,-6,12,-2,-3,-7,-6,-4,-4,-2,-3,-8],[2,-2,1,-1,-2,-1,-1,-1,-2,-4,-4,-1,-3,-4,-2,7,2,-6,-3,-3,0,-1,-1,-8],[0,-2,0,-2,-2,-1,-2,-3,-3,-2,-3,-1,-1,-4,-3,2,8,-5,-3,0,-1,-2,-1,-8],[-5,-5,-7,-8,-5,-4,-6,-6,-4,-5,-4,-6,-3,0,-7,-6,-5,16,3,-5,-8,-5,-5,-8],[-4,-4,-4,-6,-5,-3,-5,-6,3,-3,-2,-4,-3,4,-6,-3,-3,3,11,-3,-5,-4,-3,-8],[-1,-4,-5,-6,-2,-4,-4,-6,-5,4,1,-4,1,-2,-4,-3,0,-5,-3,7,-6,-4,-2,-8],[-3,-2,5,6,-6,-1,1,-2,-1,-6,-7,-1,-5,-6,-4,0,-1,-8,-5,-6,6,0,-3,-8],[-2,0,-1,1,-7,5,6,-4,0,-6,-5,1,-3,-6,-2,-1,-2,-5,-4,-4,0,6,-1,-8],[-1,-2,-2,-3,-4,-2,-2,-3,-2,-2,-2,-2,-2,-3,-3,-1,-1,-5,-3,-2,-3,-1,-2,-8],[-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,1]];BLOSUM90=[[5,-2,-2,-3,-1,-1,-1,0,-2,-2,-2,-1,-2,-3,-1,1,0,-4,-3,-1,-2,-1,-1,-6],[-2,6,-1,-3,-5,1,-1,-3,0,-4,-3,2,-2,-4,-3,-1,-2,-4,-3,-3,-2,0,-2,-6],[-2,-1,7,1,-4,0,-1,-1,0,-4,-4,0,-3,-4,-3,0,0,-5,-3,-4,4,-1,-2,-6],[-3,-3,1,7,-5,-1,1,-2,-2,-5,-5,-1,-4,-5,-3,-1,-2,-6,-4,-5,4,0,-2,-6],[-1,-5,-4,-5,9,-4,-6,-4,-5,-2,-2,-4,-2,-3,-4,-2,-2,-4,-4,-2,-4,-5,-3,-6],[-1,1,0,-1,-4,7,2,-3,1,-4,-3,1,0,-4,-2,-1,-1,-3,-3,-3,-1,4,-1,-6],[-1,-1,-1,1,-6,2,6,-3,-1,-4,-4,0,-3,-5,-2,-1,-1,-5,-4,-3,0,4,-2,-6],[0,-3,-1,-2,-4,-3,-3,6,-3,-5,-5,-2,-4,-5,-3,-1,-3,-4,-5,-5,-2,-3,-2,-6],[-2,0,0,-2,-5,1,-1,-3,8,-4,-4,-1,-3,-2,-3,-2,-2,-3,1,-4,-1,0,-2,-6],[-2,-4,-4,-5,-2,-4,-4,-5,-4,5,1,-4,1,-1,-4,-3,-1,-4,-2,3,-5,-4,-2,-6],[-2,-3,-4,-5,-2,-3,-4,-5,-4,1,5,-3,2,0,-4,-3,-2,-3,-2,0,-5,-4,-2,-6],[-1,2,0,-1,-4,1,0,-2,-1,-4,-3,6,-2,-4,-2,-1,-1,-5,-3,-3,-1,1,-1,-6],[-2,-2,-3,-4,-2,0,-3,-4,-3,1,2,-2,7,-1,-3,-2,-1,-2,-2,0,-4,-2,-1,-6],[-3,-4,-4,-5,-3,-4,-5,-5,-2,-1,0,-4,-1,7,-4,-3,-3,0,3,-2,-4,-4,-2,-6],[-1,-3,-3,-3,-4,-2,-2,-3,-3,-4,-4,-2,-3,-4,8,-2,-2,-5,-4,-3,-3,-2,-2,-6],[1,-1,0,-1,-2,-1,-1,-1,-2,-3,-3,-1,-2,-3,-2,5,1,-4,-3,-2,0,-1,-1,-6],[0,-2,0,-2,-2,-1,-1,-3,-2,-1,-2,-1,-1,-3,-2,1,6,-4,-2,-1,-1,-1,-1,-6],[-4,-4,-5,-6,-4,-3,-5,-4,-3,-4,-3,-5,-2,0,-5,-4,-4,11,2,-3,-6,-4,-3,-6],[-3,-3,-3,-4,-4,-3,-4,-5,1,-2,-2,-3,-2,3,-4,-3,-2,2,8,-3,-4,-3,-2,-6],[-1,-3,-4,-5,-2,-3,-3,-5,-4,3,0,-3,0,-2,-3,-2,-1,-3,-3,5,-4,-3,-2,-6],[-2,-2,4,4,-4,-1,0,-2,-1,-5,-5,-1,-4,-4,-3,0,-1,-6,-4,-4,4,0,-2,-6],[-1,0,-1,0,-5,4,4,-3,0,-4,-4,1,-2,-4,-2,-1,-1,-4,-3,-3,0,4,-1,-6],[-1,-2,-2,-2,-3,-1,-2,-2,-2,-2,-2,-1,-1,-2,-2,-1,-1,-3,-2,-2,-2,-1,-2,-6],[-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,1]];NUCLEOTIDES=[[1,-1,-1,-1],[-1,1,-1,-1],[-1,-1,1,-1],[-1,-1,-1,1]];PAM30=[[6,-7,-4,-3,-6,-4,-2,-2,-7,-5,-6,-7,-5,-8,-2,0,-1,-13,-8,-2,-3,-3,-3,-17],[-7,8,-6,-10,-8,-2,-9,-9,-2,-5,-8,0,-4,-9,-4,-3,-6,-2,-10,-8,-7,-4,-6,-17],[-4,-6,8,2,-11,-3,-2,-3,0,-5,-7,-1,-9,-9,-6,0,-2,-8,-4,-8,6,-3,-3,-17],[-3,-10,2,8,-14,-2,2,-3,-4,-7,-12,-4,-11,-15,-8,-4,-5,-15,-11,-8,6,1,-5,-17],[-6,-8,-11,-14,10,-14,-14,-9,-7,-6,-15,-14,-13,-13,-8,-3,-8,-15,-4,-6,-12,-14,-9,-17],[-4,-2,-3,-2,-14,8,1,-7,1,-8,-5,-3,-4,-13,-3,-5,-5,-13,-12,-7,-3,6,-5,-17],[-2,-9,-2,2,-14,1,8,-4,-5,-5,-9,-4,-7,-14,-5,-4,-6,-17,-8,-6,1,6,-5,-17],[-2,-9,-3,-3,-9,-7,-4,6,-9,-11,-10,-7,-8,-9,-6,-2,-6,-15,-14,-5,-3,-5,-5,-17],[-7,-2,0,-4,-7,1,-5,-9,9,-9,-6,-6,-10,-6,-4,-6,-7,-7,-3,-6,-1,-1,-5,-17],[-5,-5,-5,-7,-6,-8,-5,-11,-9,8,-1,-6,-1,-2,-8,-7,-2,-14,-6,2,-6,-6,-5,-17],[-6,-8,-7,-12,-15,-5,-9,-10,-6,-1,7,-8,1,-3,-7,-8,-7,-6,-7,-2,-9,-7,-6,-17],[-7,0,-1,-4,-14,-3,-4,-7,-6,-6,-8,7,-2,-14,-6,-4,-3,-12,-9,-9,-2,-4,-5,-17],[-5,-4,-9,-11,-13,-4,-7,-8,-10,-1,1,-2,11,-4,-8,-5,-4,-13,-11,-1,-10,-5,-5,-17],[-8,-9,-9,-15,-13,-13,-14,-9,-6,-2,-3,-14,-4,9,-10,-6,-9,-4,2,-8,-10,-13,-8,-17],[-2,-4,-6,-8,-8,-3,-5,-6,-4,-8,-7,-6,-8,-10,8,-2,-4,-14,-13,-6,-7,-4,-5,-17],[0,-3,0,-4,-3,-5,-4,-2,-6,-7,-8,-4,-5,-6,-2,6,0,-5,-7,-6,-1,-5,-3,-17],[-1,-6,-2,-5,-8,-5,-6,-6,-7,-2,-7,-3,-4,-9,-4,0,7,-13,-6,-3,-3,-6,-4,-17],[-13,-2,-8,-15,-15,-13,-17,-15,-7,-14,-6,-12,-13,-4,-14,-5,-13,13,-5,-15,-10,-14,-11,-17],[-8,-10,-4,-11,-4,-12,-8,-14,-3,-6,-7,-9,-11,2,-13,-7,-6,-5,10,-7,-6,-9,-7,-17],[-2,-8,-8,-8,-6,-7,-6,-5,-6,2,-2,-9,-1,-8,-6,-6,-3,-15,-7,7,-8,-6,-5,-17],[-3,-7,6,6,-12,-3,1,-3,-1,-6,-9,-2,-10,-10,-7,-1,-3,-10,-6,-8,6,0,-5,-17],[-3,-4,-3,1,-14,6,6,-5,-1,-6,-7,-4,-5,-13,-4,-5,-6,-14,-9,-6,0,6,-5,-17],[-3,-6,-3,-5,-9,-5,-5,-5,-5,-5,-6,-5,-5,-8,-5,-3,-4,-11,-7,-5,-5,-5,-5,-17],[-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,-17,1]];PAM70=[[5,-4,-2,-1,-4,-2,-1,0,-4,-2,-4,-4,-3,-6,0,1,1,-9,-5,-1,-1,-1,-2,-11],[-4,8,-3,-6,-5,0,-5,-6,0,-3,-6,2,-2,-7,-2,-1,-4,0,-7,-5,-4,-2,-3,-11],[-2,-3,6,3,-7,-1,0,-1,1,-3,-5,0,-5,-6,-3,1,0,-6,-3,-5,5,-1,-2,-11],[-1,-6,3,6,-9,0,3,-1,-1,-5,-8,-2,-7,-10,-4,-1,-2,-10,-7,-5,5,2,-3,-11],[-4,-5,-7,-9,9,-9,-9,-6,-5,-4,-10,-9,-9,-8,-5,-1,-5,-11,-2,-4,-8,-9,-6,-11],[-2,0,-1,0,-9,7,2,-4,2,-5,-3,-1,-2,-9,-1,-3,-3,-8,-8,-4,-1,5,-2,-11],[-1,-5,0,3,-9,2,6,-2,-2,-4,-6,-2,-4,-9,-3,-2,-3,-11,-6,-4,2,5,-3,-11],[0,-6,-1,-1,-6,-4,-2,6,-6,-6,-7,-5,-6,-7,-3,0,-3,-10,-9,-3,-1,-3,-3,-11],[-4,0,1,-1,-5,2,-2,-6,8,-6,-4,-3,-6,-4,-2,-3,-4,-5,-1,-4,0,1,-3,-11],[-2,-3,-3,-5,-4,-5,-4,-6,-6,7,1,-4,1,0,-5,-4,-1,-9,-4,3,-4,-4,-3,-11],[-4,-6,-5,-8,-10,-3,-6,-7,-4,1,6,-5,2,-1,-5,-6,-4,-4,-4,0,-6,-4,-4,-11],[-4,2,0,-2,-9,-1,-2,-5,-3,-4,-5,6,0,-9,-4,-2,-1,-7,-7,-6,-1,-2,-3,-11],[-3,-2,-5,-7,-9,-2,-4,-6,-6,1,2,0,10,-2,-5,-3,-2,-8,-7,0,-6,-3,-3,-11],[-6,-7,-6,-10,-8,-9,-9,-7,-4,0,-1,-9,-2,8,-7,-4,-6,-2,4,-5,-7,-9,-5,-11],[0,-2,-3,-4,-5,-1,-3,-3,-2,-5,-5,-4,-5,-7,7,0,-2,-9,-9,-3,-4,-2,-3,-11],[1,-1,1,-1,-1,-3,-2,0,-3,-4,-6,-2,-3,-4,0,5,2,-3,-5,-3,0,-2,-1,-11],[1,-4,0,-2,-5,-3,-3,-3,-4,-1,-4,-1,-2,-6,-2,2,6,-8,-4,-1,-1,-3,-2,-11],[-9,0,-6,-10,-11,-8,-11,-10,-5,-9,-4,-7,-8,-2,-9,-3,-8,13,-3,-10,-7,-10,-7,-11],[-5,-7,-3,-7,-2,-8,-6,-9,-1,-4,-4,-7,-7,4,-9,-5,-4,-3,9,-5,-4,-7,-5,-11],[-1,-5,-5,-5,-4,-4,-4,-3,-4,3,0,-6,0,-5,-3,-3,-1,-10,-5,6,-5,-4,-2,-11],[-1,-4,5,5,-8,-1,2,-1,0,-4,-6,-1,-6,-7,-4,0,-1,-7,-4,-5,5,1,-2,-11],[-1,-2,-1,2,-9,5,5,-3,1,-4,-4,-2,-3,-9,-2,-2,-3,-10,-7,-4,1,5,-3,-11],[-2,-3,-2,-3,-6,-2,-3,-3,-3,-3,-4,-3,-3,-5,-3,-1,-2,-7,-5,-2,-2,-3,-3,-11],[-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,-11,1]];PAM250=[[2,-2,0,0,-2,0,0,1,-1,-1,-2,-1,-1,-3,1,1,1,-6,-3,0,0,0,0,-8],[-2,6,0,-1,-4,1,-1,-3,2,-2,-3,3,0,-4,0,0,-1,2,-4,-2,-1,0,-1,-8],[0,0,2,2,-4,1,1,0,2,-2,-3,1,-2,-3,0,1,0,-4,-2,-2,2,1,0,-8],[0,-1,2,4,-5,2,3,1,1,-2,-4,0,-3,-6,-1,0,0,-7,-4,-2,3,3,-1,-8],[-2,-4,-4,-5,12,-5,-5,-3,-3,-2,-6,-5,-5,-4,-3,0,-2,-8,0,-2,-4,-5,-3,-8],[0,1,1,2,-5,4,2,-1,3,-2,-2,1,-1,-5,0,-1,-1,-5,-4,-2,1,3,-1,-8],[0,-1,1,3,-5,2,4,0,1,-2,-3,0,-2,-5,-1,0,0,-7,-4,-2,3,3,-1,-8],[1,-3,0,1,-3,-1,0,5,-2,-3,-4,-2,-3,-5,0,1,0,-7,-5,-1,0,0,-1,-8],[-1,2,2,1,-3,3,1,-2,6,-2,-2,0,-2,-2,0,-1,-1,-3,0,-2,1,2,-1,-8],[-1,-2,-2,-2,-2,-2,-2,-3,-2,5,2,-2,2,1,-2,-1,0,-5,-1,4,-2,-2,-1,-8],[-2,-3,-3,-4,-6,-2,-3,-4,-2,2,6,-3,4,2,-3,-3,-2,-2,-1,2,-3,-3,-1,-8],[-1,3,1,0,-5,1,0,-2,0,-2,-3,5,0,-5,-1,0,0,-3,-4,-2,1,0,-1,-8],[-1,0,-2,-3,-5,-1,-2,-3,-2,2,4,0,6,0,-2,-2,-1,-4,-2,2,-2,-2,-1,-8],[-3,-4,-3,-6,-4,-5,-5,-5,-2,1,2,-5,0,9,-5,-3,-3,0,7,-1,-4,-5,-2,-8],[1,0,0,-1,-3,0,-1,0,0,-2,-3,-1,-2,-5,6,1,0,-6,-5,-1,-1,0,-1,-8],[1,0,1,0,0,-1,0,1,-1,-1,-3,0,-2,-3,1,2,1,-2,-3,-1,0,0,0,-8],[1,-1,0,0,-2,-1,0,0,-1,0,-2,0,-1,-3,0,1,3,-5,-3,0,0,-1,0,-8],[-6,2,-4,-7,-8,-5,-7,-7,-3,-5,-2,-3,-4,0,-6,-2,-5,17,0,-6,-5,-6,-4,-8],[-3,-4,-2,-4,0,-4,-4,-5,0,-1,-1,-4,-2,7,-5,-3,-3,0,10,-2,-3,-4,-2,-8],[0,-2,-2,-2,-2,-2,-2,-1,-2,4,2,-2,2,-1,-1,-1,0,-6,-2,4,-2,-2,-1,-8],[0,-1,2,3,-4,1,3,0,1,-2,-3,1,-2,-4,-1,0,0,-5,-3,-2,3,2,-1,-8],[0,0,1,3,-5,3,3,0,2,-2,-3,0,-2,-5,0,0,-1,-6,-4,-2,2,3,-1,-8],[0,-1,0,-1,-3,-1,-1,-1,-1,-1,-1,-1,-1,-2,-1,0,0,-4,-2,-1,-1,-1,-1,-8],[-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,1]];SCHNEIDER=[[11.6,-2.7,9.7,-1.7,-2.7,-6.4,-3.9,-5.6,5.1,-5,3.6,-4.2,-6.3,-13,-7.1,-11.5,.4,-6,-1.9,-5.3,-8.5,-11.2,-8.9,-10.8,2.1,0,1.4,.2,-10.2,-13.5,-13,-12.5,-2.6,-8.5,-5,-8.1,-6.3,-9.9,-7.5,-9,-7.1,-10.2,-8.2,-9.2,-8.2,-12.5,-11.1,-11.4,-50,-14.8,-50,-13.8,-7.3,-10.1,-8.4,-9.1,-50,-13,-13.5,-12.4,-10.7,-18.1,-11.8,-17.2],[-2.7,13,-3.3,10.9,-3.5,-.4,-3.3,-1.8,-5.4,4.6,-5.5,3,-10.2,-7.9,-9.9,-9.6,-5,.5,-5.5,-1,-10.3,-8.1,-9.4,-9.6,-8.1,-5,-7.3,-6.3,-13.4,-11.3,-14.4,-12.9,-6.3,.8,-6.4,-1.1,-7.4,-5,-6.2,-6.5,-5.6,-1.6,-4.7,-3,-10.8,-8.7,-11.9,-10,-50,-6.2,-50,-7.5,-6.3,-4.3,-6.2,-5.4,-50,-7,-16.3,-8.2,-13.2,-12.3,-13.1,-13.3],[9.7,-3.3,11.6,-2.8,-4.5,-6.7,-3.1,-6.9,3.3,-5.5,4.8,-5.1,-8.9,-13.2,-5.7,-12.6,-1.5,-6.1,-.6,-6.1,-10,-11.8,-8.6,-11.9,1.2,.5,2.2,.1,-11.8,-14,-11.9,-13.4,-4.9,-9.1,-3.4,-8.9,-8,-10,-7.2,-10,-9.1,-10.2,-7.1,-9.9,-10.1,-13,-10.6,-12.7,-50,-14.9,-50,-14.4,-8.9,-10.8,-8.9,-10.4,-50,-13.1,-11.8,-13,-12.4,-19.4,-11.5,-17.8],[-1.7,10.9,-2.8,12.9,-2.7,-2.2,-2.8,.2,-4.8,2.9,-5.2,5.2,-9.1,-9.5,-9,-7,-4,-1,-5,1,-9,-8.8,-8.9,-7.7,-7,-6.8,-7.1,-4.3,-12.4,-12.9,-13.9,-10,-4.9,-.7,-5.6,1.4,-6,-6.5,-6.2,-4.8,-5.1,-3.2,-5,-1.2,-9.8,-9.9,-11.3,-8.2,-50,-7.6,-50,-5.1,-5.5,-5.8,-5.9,-4.2,-50,-8.3,-15.5,-5.9,-11.6,-14.2,-12,-11.6],[-2.7,-3.5,-4.5,-2.7,11.7,9,10.6,9.6,-3.2,-.7,-5.1,-.4,.7,-4.6,-.4,-3.6,-4.8,-8.9,-6.5,-7.8,-1.4,-4.1,-2.9,-3.3,-8,-9.1,-8,-8.2,-6,-9.3,-7.7,-8.5,-6.4,-10.1,-7.5,-8.6,2.8,-.7,.9,.1,-5.9,-7.3,-6.5,-6.5,-.4,-3.9,-2.6,-3.1,-50,-14.6,-50,-12.6,2.9,.1,1.8,1,-50,-9.2,-13.6,-7.7,-4.8,-12.2,-6.2,-11],[-6.4,-.4,-6.7,-2.2,9,12.3,9.8,9.6,-7.1,2.4,-7.2,.3,-2.9,-1.2,-3,-3.3,-7.6,-6.7,-8.1,-7.9,-4.9,-1.9,-4.5,-3.8,-9.5,-7.8,-9.3,-8.9,-9.4,-7.1,-9,-9,-9.4,-7.5,-9.3,-9.2,-.7,2.6,.2,-.1,-8,-4.6,-7.7,-6.1,-3.6,-1,-4.1,-3.1,-50,-11.6,-50,-11.6,.2,2.3,.4,.5,-50,-6.5,-15.3,-7.8,-8.4,-9.5,-8.3,-11.1],[-3.9,-3.3,-3.1,-2.8,10.6,9.8,12.2,9.8,-4.9,.1,-3.6,-.2,-1.7,-4.1,.9,-3.5,-5.9,-8.9,-5.6,-8.5,-3.9,-3.9,-2.2,-4.5,-7.3,-7.5,-6.4,-8.5,-7.1,-8.2,-6.7,-7.8,-7.9,-9.1,-7.1,-9.4,.9,-.2,2.5,-.3,-6.9,-6.5,-5.5,-6.8,-1.7,-3.4,-1.7,-2.8,-50,-13,-50,-11.5,1.5,.7,2.7,.6,-50,-8.9,-12.1,-7.4,-6.1,-11.5,-5.4,-10.4],[-5.6,-1.8,-6.9,.2,9.6,9.6,9.8,11.6,-6.6,.9,-7.2,2.5,-2.3,-3.4,-2.3,-.6,-6.5,-8.2,-8,-6.3,-3.7,-3.5,-3.9,-1.6,-9.9,-8.9,-9.6,-7,-8.6,-8.9,-8.8,-6.8,-8.6,-8.2,-8.8,-6.8,.3,.1,.2,2.4,-7.4,-6.2,-6.9,-4.4,-2.9,-2.9,-3.5,-.9,-50,-12.2,-50,-10.1,1.2,.6,1.2,2.4,-50,-7.6,-16.1,-5.8,-7.2,-10.8,-7.4,-9],[5.1,-5.4,3.3,-4.8,-3.2,-7.1,-4.9,-6.6,13.3,-2.8,11.2,-1.9,-5.7,-12.5,-7.2,-11.6,-.7,-4.8,-3.1,-4.3,-10,-11.6,-8.8,-11.7,10.5,7.7,9.1,8.5,-9.8,-12.7,-11.7,-11.8,-6.3,-11.4,-8.8,-11,-7.5,-10.3,-8.3,-9.9,-1.9,-6.7,-4.1,-6.4,-7.9,-12.5,-11.4,-11.7,-50,-14,-50,-13.2,-8.5,-10.4,-9.1,-9.6,-50,-9.8,-7.7,-8.8,-10.3,-17.9,-11.8,-16],[-5,4.6,-5.5,2.9,-.7,2.4,.1,.9,-2.8,12.8,-2.6,11,-8.4,-6.3,-8.3,-7.7,-6.1,-2.9,-6.5,-4.2,-8.5,-5.9,-7.5,-7.7,-5.5,-2.4,-5.5,-4.1,-12.9,-10.3,-12.7,-11.3,-7.4,-3.1,-7.4,-4.9,-4.4,-1.8,-3.5,-3.5,-1.6,3,-.8,.9,-8.4,-6.3,-9.6,-7.3,-50,-9,-50,-9.7,-2.3,-.2,-1.2,-1.5,-50,-.7,-13.3,-2,-11.8,-11.9,-12.3,-12.7],[3.6,-5.5,4.8,-5.2,-5.1,-7.2,-3.6,-7.2,11.2,-2.6,13.4,-2.1,-7.7,-12.5,-5.3,-11.9,-2.2,-4.4,-1.9,-4.8,-10.2,-11.5,-8.1,-12,9.3,8.2,10,8,-10.8,-11.9,-10.7,-12.4,-8.2,-11.8,-6.9,-11.5,-8.4,-9.9,-7.1,-10.6,-4.7,-6.8,-1.2,-7,-9.8,-11.6,-9.6,-12.1,-50,-14.1,-50,-12.7,-10,-10.8,-8.8,-10.5,-50,-9.2,-4.2,-9.3,-11,-18.2,-11.1,-16.1],[-4.2,3,-5.1,5.2,-.4,.3,-.2,2.5,-1.9,11,-2.1,13.2,-7.6,-8.5,-8,-5.3,-5.6,-4.5,-6.8,-2.4,-7.8,-7.9,-7.9,-6.2,-5.7,-5.1,-5.4,-2.1,-12.4,-12.3,-13.1,-10.1,-6.6,-4.4,-6.9,-2.6,-3.6,-3.8,-3.7,-2,-1.4,.8,-.9,3,-8.2,-8.1,-9.2,-5.8,-50,-10.1,-50,-7.4,-1.7,-2,-1.5,-.5,-50,-2.1,-12.6,-.4,-11.6,-13.9,-11.4,-11.1],[-6.3,-10.2,-8.9,-9.1,.7,-2.9,-1.7,-2.3,-5.7,-8.4,-7.7,-7.6,13.2,9.6,3.5,9.7,-8.7,-12.4,-10.7,-10.7,-7.8,-10.2,-8.8,-9.6,-9.5,-11.9,-10.9,-10.5,2.3,-.4,-.2,-.3,-9.7,-15.5,-11.4,-13.7,-3,-6.4,-4.1,-5.4,-9.6,-11.9,-10.5,-11.8,6.2,3.3,3.7,3.6,-50,-13.6,-50,-11.9,-5.6,-8.8,-7.2,-8.9,-50,-12.4,-14.1,-11.6,2.8,-6.4,.5,-5.2],[-13,-7.9,-13.2,-9.5,-4.6,-1.2,-4.1,-3.4,-12.5,-6.3,-12.5,-8.5,9.6,12.7,.2,10.5,-12.4,-11.6,-13.2,-12,-12.4,-10.1,-11.6,-12,-15.1,-13.1,-14.3,-13.4,-1.4,1.4,-1.6,-.5,-14.9,-14.3,-15.2,-16.8,-7.7,-4.7,-6.3,-6.6,-14.6,-10.8,-12.8,-13,2.3,6,2.5,3.6,-50,-11.2,-50,-11.9,-10.5,-9.2,-10.5,-10.5,-50,-10.3,-16.2,-11.3,-1.7,-3.7,-2.5,-5.4],[-7.1,-9.9,-5.7,-9,-.4,-3,.9,-2.3,-7.2,-8.3,-5.3,-8,3.5,.2,14.3,1,-7.3,-11.2,-6.9,-9.7,-8.5,-10.2,-7.7,-9.8,-10,-10.4,-8.4,-10.2,1,-.6,1.7,-.5,-11.1,-14.8,-9.7,-14.5,-3.7,-5.8,-3.1,-5.6,-10.4,-11.5,-8.2,-11.1,.6,-1.6,1.6,-1.1,-50,-12.4,-50,-11.5,-5.5,-8,-4.9,-7.2,-50,-12.4,-10.3,-11.6,.7,-6.8,2.4,-6],[-11.5,-9.6,-12.6,-7,-3.6,-3.3,-3.5,-.6,-11.6,-7.7,-11.9,-5.3,9.7,10.5,1,12.6,-12,-12.2,-12.5,-9.7,-11.1,-11.2,-11.9,-9.4,-12.9,-14.3,-14,-11.9,-1,-.4,-1.6,1.2,-13.9,-15.4,-13.7,-12.6,-6.2,-6.7,-6.3,-4.4,-13,-12.2,-13,-10.4,2.9,3.8,2.5,5.8,-50,-12.5,-50,-10.2,-9.6,-9.7,-9.6,-8.3,-50,-11.6,-15.4,-9.4,-1.1,-5.4,-1.6,-3.3],[.4,-5,-1.5,-4,-4.8,-7.6,-5.9,-6.5,-.7,-6.1,-2.2,-5.6,-8.7,-12.4,-7.3,-12,12.8,2.3,10.2,3,0,-3.4,-.7,-3.2,2.5,-.8,.9,.2,-3,-7.2,-5.7,-6.1,-.2,-6.6,-1.8,-6,-5.3,-8.2,-5.7,-7.6,-6.7,-9.6,-7.5,-9.3,-7.1,-10.5,-9.6,-9.4,-50,-8.1,-50,-7.2,-4.3,-6.8,-5.7,-6.3,-50,-9.5,-9.6,-8.9,-6.2,-12.8,-6.8,-11.8],[-6,.5,-6.1,-1,-8.9,-6.7,-8.9,-8.2,-4.8,-2.9,-4.4,-4.5,-12.4,-11.6,-11.2,-12.2,2.3,14.6,1.9,12.9,-5.5,-2.6,-4.1,-4.7,-1.2,3,-1.1,1.6,-8,-4.7,-8.7,-6,-8.2,-4.7,-7.8,-6.7,-10,-8.3,-8.9,-9.9,-10.8,-7.1,-10,-9.2,-11.6,-10.1,-12.3,-11.9,-50,2.2,-50,.9,-7.9,-5.9,-7.4,-6.9,-50,-4.6,-11.6,-5.6,-9.7,-5.9,-9.9,-7.3],[-1.9,-5.5,-.6,-5,-6.5,-8.1,-5.6,-8,-3.1,-6.5,-1.9,-6.8,-10.7,-13.2,-6.9,-12.5,10.2,1.9,11.9,2.1,-2.3,-4.1,-.5,-4.6,-.1,-.9,2.4,-.8,-5.1,-6.9,-4.8,-6.7,-2.3,-7.1,-.8,-7.2,-7.2,-8,-5.6,-8.5,-9.4,-9.7,-7.2,-9.8,-9.2,-11.1,-9.5,-10.7,-50,-8.7,-50,-8.6,-6.1,-7.5,-5.5,-7.7,-50,-10.4,-7.7,-10,-7.3,-13.6,-6.4,-13.3],[-5.3,-1,-6.1,1,-7.8,-7.9,-8.5,-6.3,-4.3,-4.2,-4.8,-2.4,-10.7,-12,-9.7,-9.7,3,12.9,2.1,14.7,-4.9,-3.8,-4,-2.4,-1,.8,-1.3,3.4,-7.6,-5.7,-8.1,-3.5,-6.8,-5.8,-7.2,-4.2,-8.9,-10.2,-8.4,-8.2,-9.9,-8.4,-9.7,-6.4,-11.1,-11.1,-11.8,-10,-50,.4,-50,2.6,-7.2,-7,-7.4,-5.1,-50,-5.7,-9.8,-3.2,-8.4,-7.4,-8.9,-5.9],[-8.5,-10.3,-10,-9,-1.4,-4.9,-3.9,-3.7,-10,-8.5,-10.2,-7.8,-7.8,-12.4,-8.5,-11.1,0,-5.5,-2.3,-4.9,12.6,10,11.1,10.5,-6,-8.3,-6.9,-7.5,-2.2,-7.4,-5.3,-5.9,-8.9,-12.5,-9.4,-11.6,-.7,-3.9,-2.3,-3,-9.1,-9.8,-9.2,-9.5,-5.6,-9,-8,-8.5,-50,-15.3,-50,-14.1,2.3,-1.4,.3,-.5,-50,-13.6,-14.3,-11.5,-5.3,-13.7,-6.1,-12.7],[-11.2,-8.1,-11.8,-8.8,-4.1,-1.9,-3.9,-3.5,-11.6,-5.9,-11.5,-7.9,-10.2,-10.1,-10.2,-11.2,-3.4,-2.6,-4.1,-3.8,10,13.1,10.7,10.6,-8.1,-5.2,-8,-6.7,-6.1,-3.7,-7.5,-5.6,-11.1,-10.3,-10.6,-11.9,-3.2,-1,-2.2,-2.8,-10.5,-8.1,-9.4,-9.5,-8.3,-6.9,-9.4,-8.8,-50,-11.3,-50,-12.8,-.6,2.2,-.3,.1,-50,-10.1,-17.5,-11.1,-8.6,-9.9,-8.6,-11.9],[-8.9,-9.4,-8.6,-8.9,-2.9,-4.5,-2.2,-3.9,-8.8,-7.5,-8.1,-7.9,-8.8,-11.6,-7.7,-11.9,-.7,-4.1,-.5,-4,11.1,10.7,13.2,10.4,-5.7,-5.8,-3.5,-6.1,-3.6,-6.5,-3.3,-5.5,-9.4,-11,-8.7,-11.2,-1.8,-2.7,.7,-3,-9.1,-8.2,-7.3,-9.4,-7.2,-8.2,-7.2,-8.2,-50,-13.2,-50,-13.3,.5,-.9,1.8,-.6,-50,-11.4,-11.1,-10.5,-6.1,-12.9,-5,-11.9],[-10.8,-9.6,-11.9,-7.7,-3.3,-3.8,-4.5,-1.6,-11.7,-7.7,-12,-6.2,-9.6,-12,-9.8,-9.4,-3.2,-4.7,-4.6,-2.4,10.5,10.6,10.4,12.6,-8.2,-7.9,-9,-4.7,-6.1,-6,-7.5,-2.9,-10.9,-12.2,-11.2,-10.9,-2.4,-2.9,-2.7,-.9,-10.4,-9.7,-10.2,-8,-8.4,-9.1,-9.3,-6.5,-50,-13.3,-50,-11,-0,-.4,-.4,2.3,-50,-10.9,-17.2,-8.3,-8.3,-12.7,-7.8,-9.3],[2.1,-8.1,1.2,-7,-8,-9.5,-7.3,-9.9,10.5,-5.5,9.3,-5.7,-9.5,-15.1,-10,-12.9,2.5,-1.2,-.1,-1,-6,-8.1,-5.7,-8.2,13.8,11.3,11.8,12.1,-6,-9.1,-9,-9.5,-8.9,-13.4,-10,-13.1,-9.9,-11.7,-9.8,-12.8,-5.9,-9.4,-6.5,-8.1,-10.7,-14,-13.3,-13.9,-50,-11.9,-50,-9.7,-8.9,-10.8,-9,-11.1,-50,-6.5,-5.3,-6.3,-10.5,-16.2,-10.4,-15.2],[0,-5,.5,-6.8,-9.1,-7.8,-7.5,-8.9,7.7,-2.4,8.2,-5.1,-11.9,-13.1,-10.4,-14.3,-.8,3,-.9,.8,-8.3,-5.2,-5.8,-7.9,11.3,15,11.2,12.8,-9.7,-5.3,-9.2,-7.8,-11.7,-10.6,-10.1,-12.2,-11.7,-8.8,-8.9,-11.8,-9.3,-5,-8,-8.2,-13.6,-11.4,-12.8,-13,-50,-7.2,-50,-8.4,-11,-7.7,-8.7,-10.2,-50,-1.5,-7.1,-4.9,-11.2,-11.6,-11.6,-15],[1.4,-7.3,2.2,-7.1,-8,-9.3,-6.4,-9.6,9.1,-5.5,10,-5.4,-10.9,-14.3,-8.4,-14,.9,-1.1,2.4,-1.3,-6.9,-8,-3.5,-9,11.8,11.2,13.4,11.4,-7.3,-8.8,-6.5,-8.5,-10,-12.5,-7.8,-12.5,-9.6,-11,-7.1,-10.7,-7.9,-8,-4.3,-9.4,-11.4,-12.3,-10.9,-12.9,-50,-11.8,-50,-11.2,-9.4,-9.8,-7.3,-10.5,-50,-6.2,-2.2,-6.7,-9.8,-15.2,-8.5,-14.9],[.2,-6.3,.1,-4.3,-8.2,-8.9,-8.5,-7,8.5,-4.1,8,-2.1,-10.5,-13.4,-10.2,-11.9,.2,1.6,-.8,3.4,-7.5,-6.7,-6.1,-4.7,12.1,12.8,11.4,14.7,-8.7,-7.4,-9.4,-5.3,-9.9,-11.8,-10.5,-10.3,-9.9,-10.1,-9.3,-9.3,-8.1,-7.2,-8,-5.2,-12,-12.1,-12.6,-10.9,-50,-7.9,-50,-5.3,-9.3,-8.8,-8.9,-7,-50,-3.6,-7.1,-1.2,-10.2,-12.7,-9.9,-11],[-10.2,-13.4,-11.8,-12.4,-6,-9.4,-7.1,-8.6,-9.8,-12.9,-10.8,-12.4,2.3,-1.4,1,-1,-3,-8,-5.1,-7.6,-2.2,-6.1,-3.6,-6.1,-6,-9.7,-7.3,-8.7,11.2,7.9,8.9,8.1,-12.1,-17.4,-13.2,-16.8,-6.3,-9.5,-7.5,-8.8,-12.7,-15.2,-13.1,-14.2,0,-3.1,-1.8,-3.1,-50,-10.7,-50,-9.3,-4.6,-8.9,-5.9,-8.3,-50,-12.8,-9.6,-10.6,9.5,-3.2,8.2,-2.8],[-13.5,-11.3,-14,-12.9,-9.3,-7.1,-8.2,-8.9,-12.7,-10.3,-11.9,-12.3,-.4,1.4,-.6,-.4,-7.2,-4.7,-6.9,-5.7,-7.4,-3.7,-6.5,-6,-9.1,-5.3,-8.8,-7.4,7.9,11.9,7.8,9.3,-15.2,-15.1,-14.6,-17.2,-9.7,-7.3,-8.2,-9.2,-15,-12.8,-14.1,-14.9,-2.8,.2,-2.9,-2.3,-50,-7.4,-50,-8.7,-9.4,-7.3,-9.4,-9.4,-50,-8,-11.9,-9.7,6.5,.5,6.4,-1.8],[-13,-14.4,-11.9,-13.9,-7.7,-9,-6.7,-8.8,-11.7,-12.7,-10.7,-13.1,-.2,-1.6,1.7,-1.6,-5.7,-8.7,-4.8,-8.1,-5.3,-7.5,-3.3,-7.5,-9,-9.2,-6.5,-9.4,8.9,7.8,10.1,7.8,-14.3,-17.7,-13,-17.8,-8,-9.4,-6.2,-9.2,-15.1,-14.9,-12.2,-14.9,-1.8,-3.2,-.8,-3.2,-50,-10.8,-50,-9.9,-7.3,-9.6,-6.4,-9.4,-50,-12.3,-8.7,-11.3,7.6,-3.3,8.7,-2.9],[-12.5,-12.9,-13.4,-10,-8.5,-9,-7.8,-6.8,-11.8,-11.3,-12.4,-10.1,-.3,-.5,-.5,1.2,-6.1,-6,-6.7,-3.5,-5.9,-5.6,-5.5,-2.9,-9.5,-7.8,-8.5,-5.3,8.1,9.3,7.8,11.8,-14.4,-15.7,-14.5,-14.6,-8.4,-8.7,-7.9,-7.1,-14.3,-13.8,-13.8,-12.3,-2.4,-2.2,-2.9,-.2,-50,-8.9,-50,-7.1,-8.1,-9.1,-8.7,-6.6,-50,-9.7,-11.4,-8,6.8,-1.8,6.9,.4],[-2.6,-6.3,-4.9,-4.9,-6.4,-9.4,-7.9,-8.6,-6.3,-7.4,-8.2,-6.6,-9.7,-14.9,-11.1,-13.9,-.2,-8.2,-2.3,-6.8,-8.9,-11.1,-9.4,-10.9,-8.9,-11.7,-10,-9.9,-12.1,-15.2,-14.3,-14.4,11.1,2.9,9.2,3.5,-3,-7,-4.3,-6.2,-2.2,-6.6,-3.7,-5.7,-6,-10.4,-8.6,-9.5,-50,-15.5,-50,-13.9,-7.8,-10.5,-8.7,-9.6,-50,-16.5,-17.1,-14.8,-12.1,-18.9,-12.4,-17.4],[-8.5,.8,-9.1,-.7,-10.1,-7.5,-9.1,-8.2,-11.4,-3.1,-11.8,-4.4,-15.5,-14.3,-14.8,-15.4,-6.6,-4.7,-7.1,-5.8,-12.5,-10.3,-11,-12.2,-13.4,-10.6,-12.5,-11.8,-17.4,-15.1,-17.7,-15.7,2.9,12.5,3.1,10.3,-7.7,-5.2,-6.2,-7.3,-5.4,-1.7,-5.4,-3.7,-11.6,-9.1,-13,-10.8,-50,-10.3,-50,-11.2,-9.8,-8.3,-9.1,-9.7,-50,-12.7,-20.6,-13.1,-16,-16.6,-17,-18.4],[-5,-6.4,-3.4,-5.6,-7.5,-9.3,-7.1,-8.8,-8.8,-7.4,-6.9,-6.9,-11.4,-15.2,-9.7,-13.7,-1.8,-7.8,-.8,-7.2,-9.4,-10.6,-8.7,-11.2,-10,-10.1,-7.8,-10.5,-13.2,-14.6,-13,-14.5,9.2,3.1,10.8,3,-4.5,-6.7,-2.7,-6.7,-5,-6.8,-2.5,-6.7,-7.5,-10.4,-7.4,-10.2,-50,-15.5,-50,-14.2,-8.9,-10.2,-8.5,-10,-50,-15.6,-15.3,-15.5,-13,-18.8,-12.6,-18.3],[-8.1,-1.1,-8.9,1.4,-8.6,-9.2,-9.4,-6.8,-11,-4.9,-11.5,-2.6,-13.7,-16.8,-14.5,-12.6,-6,-6.7,-7.2,-4.2,-11.6,-11.9,-11.2,-10.9,-13.1,-12.2,-12.5,-10.3,-16.8,-17.2,-17.8,-14.6,3.5,10.3,3,12.4,-6.9,-7.5,-6.8,-4.9,-5.4,-4.2,-5.4,-1.3,-10.8,-11.5,-12.4,-8.2,-50,-12.5,-50,-8.9,-9.2,-10,-9.4,-7.9,-50,-14.3,-19.9,-11.4,-16.2,-19.2,-15.8,-15.9],[-6.3,-7.4,-8,-6,2.8,-.7,.9,.3,-7.5,-4.4,-8.4,-3.6,-3,-7.7,-3.7,-6.2,-5.3,-10,-7.2,-8.9,-.7,-3.2,-1.8,-2.4,-9.9,-11.7,-9.6,-9.9,-6.3,-9.7,-8,-8.4,-3,-7.7,-4.5,-6.9,11.3,8.2,9.4,9.1,-1,-3.3,-1.8,-2.4,1.5,-2.1,-.4,-1.1,-50,-14.5,-50,-12.9,2.8,-0,1.4,.7,-50,-8.7,-14.1,-7.5,-5.2,-12.5,-6.5,-10.7],[-9.9,-5,-10,-6.5,-.7,2.6,-.2,.1,-10.3,-1.8,-9.9,-3.8,-6.4,-4.7,-5.8,-6.7,-8.2,-8.3,-8,-10.2,-3.9,-1,-2.7,-2.9,-11.7,-8.8,-11,-10.1,-9.5,-7.3,-9.4,-8.7,-7,-5.2,-6.7,-7.5,8.2,11.6,8.8,9.1,-3.7,-.9,-3.1,-3,-2,1.2,-2.3,-1.3,-50,-12.1,-50,-12.6,.1,2.5,.7,.6,-50,-6,-14.8,-7.5,-8.6,-9.4,-8.5,-11.2],[-7.5,-6.2,-7.2,-6.2,.9,.2,2.5,.2,-8.3,-3.5,-7.1,-3.7,-4.1,-6.3,-3.1,-6.3,-5.7,-8.9,-5.6,-8.4,-2.3,-2.2,.7,-2.7,-9.8,-8.9,-7.1,-9.3,-7.5,-8.2,-6.2,-7.9,-4.3,-6.2,-2.7,-6.8,9.4,8.8,12.1,8.8,-2.1,-2,.1,-2.4,0,-1.1,1.3,-.8,-50,-11.9,-50,-12.6,1.2,.7,3.5,.8,-50,-7.1,-12.4,-7.1,-7.1,-10.6,-5,-10.6],[-9,-6.5,-10,-4.8,.1,-.1,-.3,2.4,-9.9,-3.5,-10.6,-2,-5.4,-6.6,-5.6,-4.4,-7.6,-9.9,-8.5,-8.2,-3,-2.8,-3,-.9,-12.8,-11.8,-10.7,-9.3,-8.8,-9.2,-9.2,-7.1,-6.2,-7.3,-6.7,-4.9,9.1,9.1,8.8,11.2,-3.1,-3,-3.3,-1,-1.1,-1.4,-2,1.2,-50,-12.8,-50,-10.9,.8,.5,.7,2.3,-50,-7.5,-16.5,-5.9,-7.8,-11.1,-7.8,-9],[-7.1,-5.6,-9.1,-5.1,-5.9,-8,-6.9,-7.4,-1.9,-1.6,-4.7,-1.4,-9.6,-14.6,-10.4,-13,-6.7,-10.8,-9.4,-9.9,-9.1,-10.5,-9.1,-10.4,-5.9,-9.3,-7.9,-8.1,-12.7,-15,-15.1,-14.3,-2.2,-5.4,-5,-5.4,-1,-3.7,-2.1,-3.1,12.8,9.6,11.1,10.1,-4.8,-9.4,-8.1,-8.6,-50,-18.3,-50,-15.4,-5.9,-7.5,-6.6,-7.1,-50,-9.5,-11.7,-8.4,-12.5,-17.3,-13.2,-15.4],[-10.2,-1.6,-10.2,-3.2,-7.3,-4.6,-6.5,-6.2,-6.7,3,-6.8,.8,-11.9,-10.8,-11.5,-12.2,-9.6,-7.1,-9.7,-8.4,-9.8,-8.1,-8.2,-9.7,-9.4,-5,-8,-7.2,-15.2,-12.8,-14.9,-13.8,-6.6,-1.7,-6.8,-4.2,-3.3,-.9,-2,-3,9.6,12.8,9.7,10.5,-8.5,-5.6,-9.3,-7.8,-50,-12.7,-50,-13.8,-6.8,-5.1,-5.3,-6.5,-50,-4.1,-12.8,-5.8,-14.4,-14.1,-13.6,-14.8],[-8.2,-4.7,-7.1,-5,-6.5,-7.7,-5.5,-6.9,-4.1,-.8,-1.2,-.9,-10.5,-12.8,-8.2,-13,-7.5,-10,-7.2,-9.7,-9.2,-9.4,-7.3,-10.2,-6.5,-8,-4.3,-8,-13.1,-14.1,-12.2,-13.8,-3.7,-5.4,-2.5,-5.4,-1.8,-3.1,.1,-3.3,11.1,9.7,12.9,9.8,-5.5,-8.1,-5.4,-7.8,-50,-16.4,-50,-14.8,-5.9,-7.1,-4.7,-7.2,-50,-8.4,-6.4,-8.1,-12.1,-16.2,-10.3,-15.8],[-9.2,-3,-9.9,-1.2,-6.5,-6.1,-6.8,-4.4,-6.4,.9,-7,3,-11.8,-13,-11.1,-10.4,-9.3,-9.2,-9.8,-6.4,-9.5,-9.5,-9.4,-8,-8.1,-8.2,-9.4,-5.2,-14.2,-14.9,-14.9,-12.3,-5.7,-3.7,-6.7,-1.3,-2.4,-3,-2.4,-1,10.1,10.5,9.8,13.1,-7.2,-8,-8.4,-5,-50,-14.7,-50,-11.4,-6.3,-6.7,-5.8,-5,-50,-6.1,-13.4,-3.6,-13,-16,-13.7,-13.3],[-8.2,-10.8,-10.1,-9.8,-.4,-3.6,-1.7,-2.9,-7.9,-8.4,-9.8,-8.2,6.2,2.3,.6,2.9,-7.1,-11.6,-9.2,-11.1,-5.6,-8.3,-7.2,-8.4,-10.7,-13.6,-11.4,-12,0,-2.8,-1.8,-2.4,-6,-11.6,-7.5,-10.8,1.5,-2,0,-1.1,-4.8,-8.5,-5.5,-7.2,11.9,8.6,10,9,-50,-14.2,-50,-12.8,-4.1,-7.4,-5.7,-6.5,-50,-11,-14.3,-9.9,1.4,-7.9,-.7,-6.8],[-12.5,-8.7,-13,-9.9,-3.9,-1,-3.4,-2.9,-12.5,-6.3,-11.6,-8.1,3.3,6,-1.6,3.8,-10.5,-10.1,-11.1,-11.1,-9,-6.9,-8.2,-9.1,-14,-11.4,-12.3,-12.1,-3.1,.2,-3.2,-2.2,-10.4,-9.1,-10.4,-11.5,-2.1,1.2,-1.1,-1.4,-9.4,-5.6,-8.1,-8,8.6,12.4,8.6,9.5,-50,-10.4,-50,-11.6,-7.2,-5.7,-7.5,-7.4,-50,-8.6,-15.7,-9.7,-3,-3.7,-3.2,-5.9],[-11.1,-11.9,-10.6,-11.3,-2.6,-4.1,-1.7,-3.5,-11.4,-9.6,-9.6,-9.2,3.7,2.5,1.6,2.5,-9.6,-12.3,-9.5,-11.8,-8,-9.4,-7.2,-9.3,-13.3,-12.8,-10.9,-12.6,-1.8,-2.9,-.8,-2.9,-8.6,-13,-7.4,-12.4,-.4,-2.3,1.3,-2,-8.1,-9.3,-5.4,-8.4,10,8.6,11.4,8.9,-50,-13.7,-50,-13.2,-6.1,-8.1,-5.5,-7.5,-50,-11.3,-12.7,-10.1,-1.6,-7.8,-.3,-7.2],[-11.4,-10,-12.7,-8.2,-3.1,-3.1,-2.8,-.9,-11.7,-7.3,-12.1,-5.8,3.6,3.6,-1.1,5.8,-9.4,-11.9,-10.7,-10,-8.5,-8.8,-8.2,-6.5,-13.9,-13,-12.9,-10.9,-3.1,-2.3,-3.2,-.2,-9.5,-10.8,-10.2,-8.2,-1.1,-1.3,-.8,1.2,-8.6,-7.8,-7.8,-5,9,9.5,8.9,12,-50,-13,-50,-10.3,-6.2,-7,-7.1,-5.4,-50,-9.3,-14,-8.2,-2.4,-6.3,-2.4,-3.9],[-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,33.3,-50,30.6,-50,-50,-50,-50,-50,29.2,-50,-50,-50,-50,-50,-50,-50],[-14.8,-6.2,-14.9,-7.6,-14.6,-11.6,-13,-12.2,-14,-9,-14.1,-10.1,-13.6,-11.2,-12.4,-12.5,-8.1,2.2,-8.7,.4,-15.3,-11.3,-13.2,-13.3,-11.9,-7.2,-11.8,-7.9,-10.7,-7.4,-10.8,-8.9,-15.5,-10.3,-15.5,-12.5,-14.5,-12.1,-11.9,-12.8,-18.3,-12.7,-16.4,-14.7,-14.2,-10.4,-13.7,-13,-50,15.1,-50,13.3,-9.9,-5.8,-8.9,-7.6,-50,-1.5,-7.8,-3,-8.1,3.6,-9.4,2],[-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,30.6,-50,35.2,-50,-50,-50,-50,-50,28.5,-50,-50,-50,-50,-50,-50,-50],[-13.8,-7.5,-14.4,-5.1,-12.6,-11.6,-11.5,-10.1,-13.2,-9.7,-12.7,-7.4,-11.9,-11.9,-11.5,-10.2,-7.2,.9,-8.6,2.6,-14.1,-12.8,-13.3,-11,-9.7,-8.4,-11.2,-5.3,-9.3,-8.7,-9.9,-7.1,-13.9,-11.2,-14.2,-8.9,-12.9,-12.6,-12.6,-10.9,-15.4,-13.8,-14.8,-11.4,-12.8,-11.6,-13.2,-10.3,-50,13.3,-50,15.2,-8.6,-7,-8.4,-4.8,-50,-3,-7.1,-.1,-7.3,2.3,-8.7,3.9],[-7.3,-6.3,-8.9,-5.5,2.9,.2,1.5,1.2,-8.5,-2.3,-10,-1.7,-5.6,-10.5,-5.5,-9.6,-4.3,-7.9,-6.1,-7.2,2.3,-.6,.5,-0,-8.9,-11,-9.4,-9.3,-4.6,-9.4,-7.3,-8.1,-7.8,-9.8,-8.9,-9.2,2.8,.1,1.2,.8,-5.9,-6.8,-5.9,-6.3,-4.1,-7.2,-6.1,-6.2,-50,-9.9,-50,-8.6,12.5,9.4,11,9.8,-50,-4.8,-8.7,-3.5,-0,-8.6,-2.1,-7],[-10.1,-4.3,-10.8,-5.8,.1,2.3,.7,.6,-10.4,-.2,-10.8,-2,-8.8,-9.2,-8,-9.7,-6.8,-5.9,-7.5,-7,-1.4,2.2,-.9,-.4,-10.8,-7.7,-9.8,-8.8,-8.9,-7.3,-9.6,-9.1,-10.5,-8.3,-10.2,-10,-0,2.5,.7,.5,-7.5,-5.1,-7.1,-6.7,-7.4,-5.7,-8.1,-7,-50,-5.8,-50,-7,9.4,12.7,10.1,10,-50,-1.5,-11.3,-3.3,-5.4,-4.2,-5.6,-6.8],[-8.4,-6.2,-8.9,-5.9,1.8,.4,2.7,1.2,-9.1,-1.2,-8.8,-1.5,-7.2,-10.5,-4.9,-9.6,-5.7,-7.4,-5.5,-7.4,.3,-.3,1.8,-.4,-9,-8.7,-7.3,-8.9,-5.9,-9.4,-6.4,-8.7,-8.7,-9.1,-8.5,-9.4,1.4,.7,3.5,.7,-6.6,-5.3,-4.7,-5.8,-5.7,-7.5,-5.5,-7.1,-50,-8.9,-50,-8.4,11,10.1,13.2,10.2,-50,-4.2,-6.1,-3.6,-3.5,-8.4,-1.2,-6.8],[-9.1,-5.4,-10.4,-4.2,1,.5,.6,2.4,-9.6,-1.5,-10.5,-.5,-8.9,-10.5,-7.2,-8.3,-6.3,-6.9,-7.7,-5.1,-.5,.1,-.6,2.3,-11.1,-10.2,-10.5,-7,-8.3,-9.4,-9.4,-6.6,-9.6,-9.7,-10,-7.9,.7,.6,.8,2.3,-7.1,-6.5,-7.2,-5,-6.5,-7.4,-7.5,-5.4,-50,-7.6,-50,-4.8,9.8,10,10.2,12.1,-50,-3.1,-11.4,-.7,-4.6,-6.6,-4.9,-3.9],[-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,-50,29.2,-50,28.5,-50,-50,-50,-50,-50,33.3,-50,-50,-50,-50,-50,-50,-50],[-13,-7,-13.1,-8.3,-9.2,-6.5,-8.9,-7.6,-9.8,-.7,-9.2,-2.1,-12.4,-10.3,-12.4,-11.6,-9.5,-4.6,-10.4,-5.7,-13.6,-10.1,-11.4,-10.9,-6.5,-1.5,-6.2,-3.6,-12.8,-8,-12.3,-9.7,-16.5,-12.7,-15.6,-14.3,-8.7,-6,-7.1,-7.5,-9.5,-4.1,-8.4,-6.1,-11,-8.6,-11.3,-9.3,-50,-1.5,-50,-3,-4.8,-1.5,-4.2,-3.1,-50,16.4,-5.1,14.2,-10.1,-4.3,-10,-5.4],[-13.5,-16.3,-11.8,-15.5,-13.6,-15.3,-12.1,-16.1,-7.7,-13.3,-4.2,-12.6,-14.1,-16.2,-10.3,-15.4,-9.6,-11.6,-7.7,-9.8,-14.3,-17.5,-11.1,-17.2,-5.3,-7.1,-2.2,-7.1,-9.6,-11.9,-8.7,-11.4,-17.1,-20.6,-15.3,-19.9,-14.1,-14.8,-12.4,-16.5,-11.7,-12.8,-6.4,-13.4,-14.3,-15.7,-12.7,-14,-50,-7.8,-50,-7.1,-8.7,-11.3,-6.1,-11.4,-50,-5.1,18.6,-4.8,-8.6,-8.1,-4.5,-7.3],[-12.4,-8.2,-13,-5.9,-7.7,-7.8,-7.4,-5.8,-8.8,-2,-9.3,-.4,-11.6,-11.3,-11.6,-9.4,-8.9,-5.6,-10,-3.2,-11.5,-11.1,-10.5,-8.3,-6.3,-4.9,-6.7,-1.2,-10.6,-9.7,-11.3,-8,-14.8,-13.1,-15.5,-11.4,-7.5,-7.5,-7.1,-5.9,-8.4,-5.8,-8.1,-3.6,-9.9,-9.7,-10.1,-8.2,-50,-3,-50,-.1,-3.5,-3.3,-3.6,-.7,-50,14.2,-4.8,16.4,-8.9,-5.8,-8.9,-3.4],[-10.7,-13.2,-12.4,-11.6,-4.8,-8.4,-6.1,-7.2,-10.3,-11.8,-11,-11.6,2.8,-1.7,.7,-1.1,-6.2,-9.7,-7.3,-8.4,-5.3,-8.6,-6.1,-8.3,-10.5,-11.2,-9.8,-10.2,9.5,6.5,7.6,6.8,-12.1,-16,-13,-16.2,-5.2,-8.6,-7.1,-7.8,-12.5,-14.4,-12.1,-13,1.4,-3,-1.6,-2.4,-50,-8.1,-50,-7.3,-0,-5.4,-3.5,-4.6,-50,-10.1,-8.6,-8.9,13.2,-.9,9.7,-.3],[-18.1,-12.3,-19.4,-14.2,-12.2,-9.5,-11.5,-10.8,-17.9,-11.9,-18.2,-13.9,-6.4,-3.7,-6.8,-5.4,-12.8,-5.9,-13.6,-7.4,-13.7,-9.9,-12.9,-12.7,-16.2,-11.6,-15.2,-12.7,-3.2,.5,-3.3,-1.8,-18.9,-16.6,-18.8,-19.2,-12.5,-9.4,-10.6,-11.1,-17.3,-14.1,-16.2,-16,-7.9,-3.7,-7.8,-6.3,-50,3.6,-50,2.3,-8.6,-4.2,-8.4,-6.6,-50,-4.3,-8.1,-5.8,-.9,14.2,-1.8,11.6],[-11.8,-13.1,-11.5,-12,-6.2,-8.3,-5.4,-7.4,-11.8,-12.3,-11.1,-11.4,.5,-2.5,2.4,-1.6,-6.8,-9.9,-6.4,-8.9,-6.1,-8.6,-5,-7.8,-10.4,-11.6,-8.5,-9.9,8.2,6.4,8.7,6.9,-12.4,-17,-12.6,-15.8,-6.5,-8.5,-5,-7.8,-13.2,-13.6,-10.3,-13.7,-.7,-3.2,-.3,-2.4,-50,-9.4,-50,-8.7,-2.1,-5.6,-1.2,-4.9,-50,-10,-4.5,-8.9,9.7,-1.8,11.3,-.9],[-17.2,-13.3,-17.8,-11.6,-11,-11.1,-10.4,-9,-16,-12.7,-16.1,-11.1,-5.2,-5.4,-6,-3.3,-11.8,-7.3,-13.3,-5.9,-12.7,-11.9,-11.9,-9.3,-15.2,-15,-14.9,-11,-2.8,-1.8,-2.9,.4,-17.4,-18.4,-18.3,-15.9,-10.7,-11.2,-10.6,-9,-15.4,-14.8,-15.8,-13.3,-6.8,-5.9,-7.2,-3.9,-50,2,-50,3.9,-7,-6.8,-6.8,-3.9,-50,-5.4,-7.3,-3.4,-.3,11.6,-.9,14.1]];TRANS=[[5,0,0,4],[0,5,4,0],[0,4,5,0],[4,0,0,5]];CONBLO={A:0,R:1,N:2,D:3,C:4,Q:5,E:6,G:7,H:8,I:9,L:10,K:11,M:12,F:13,P:14,S:15,T:16,W:17,Y:18,V:19,B:20,Z:21,X:22,"*":23};CONNUCL={A:0,T:1,C:2,G:3};CONSCHN={AAA:0,AAC:1,AAG:2,AAT:3,ACA:4,ACC:5,ACG:6,ACT:7,AGA:8,AGC:9,AGG:10,AGT:11,ATA:12,ATC:13,ATG:14,ATT:15,CAA:16,CAC:17,CAG:18,CAT:19,CCA:20,CCC:21,CCG:22,CCT:23,CGA:24,CGC:25,CGG:26,CGT:27,CTA:28,CTC:29,CTG:30,CTT:31,GAA:32,GAC:33,GAG:34,GAT:35,GCA:36,GCC:37,GCG:38,GCT:39,GGA:40,GGC:41,GGG:42,GGT:43,GTA:44,GTC:45,GTG:46,GTT:47,TAA:48,TAC:49,TAG:50,TAT:51,TCA:52,TCC:53,TCG:54,TCT:55,TGA:56,TGC:57,TGG:58,TGT:59,TTA:60,TTC:61,TTG:62,TTT:63};fillNeedleman(){for(let e=0;e<=this.len1;e++)this.dpGrid[e][0].value=-e*this.gap,this.dpGrid[e][0].parentI=e-1,this.dpGrid[e][0].parentJ=0;for(let e=1;e<=this.len2;e++)this.dpGrid[0][e].value=-e*this.gap,this.dpGrid[0][e].parentI=0,this.dpGrid[0][e].parentJ=e-1}fillOne(e,t){this.dpGrid[e][t].value=Math.max(this.dpGrid[e-1][t-1].value+this.scores[e-1][t-1],Math.max(this.dpGrid[e-1][t].value-this.gap,this.dpGrid[e][t-1].value-this.gap)),this.dpGrid[e][t].value==this.dpGrid[e-1][t-1].value+this.scores[e-1][t-1]?(this.dpGrid[e][t].parentI=e-1,this.dpGrid[e][t].parentJ=t-1):this.dpGrid[e][t].value==this.dpGrid[e-1][t].value-this.gap?(this.dpGrid[e][t].parentI=e-1,this.dpGrid[e][t].parentJ=t):(this.dpGrid[e][t].parentI=e,this.dpGrid[e][t].parentJ=t-1)}gridFromName(e){switch(e){case"BLOSUM45":this.alignGrid=this.BLOSUM45,this.connections=this.CONBLO,this.step=1;break;case"BLOSUM50":this.alignGrid=this.BLOSUM50,this.connections=this.CONBLO,this.step=1;break;case"BLOSUM62":this.alignGrid=this.BLOSUM62,this.connections=this.CONBLO,this.step=1;break;case"BLOSUM80":this.alignGrid=this.BLOSUM80,this.connections=this.CONBLO,this.step=1;break;case"BLOSUM90":this.alignGrid=this.BLOSUM90,this.connections=this.CONBLO,this.step=1;break;case"PAM30":this.alignGrid=this.PAM30,this.connections=this.CONBLO,this.step=1;break;case"PAM70":this.alignGrid=this.PAM70,this.connections=this.CONBLO,this.step=1;break;case"PAM250":this.alignGrid=this.PAM250,this.connections=this.CONBLO,this.step=1;break;case"NUCLEOTIDES":this.alignGrid=this.NUCLEOTIDES,this.connections=this.CONNUCL,this.step=1;break;case"TRANS":this.alignGrid=this.TRANS,this.connections=this.CONNUCL,this.step=1;break;case"SCHNEIDER":this.alignGrid=this.SCHNEIDER,this.connections=this.CONSCHN,this.step=3}this.fillScores()}constructResult(e,t){let n="",i="",o="";const s=this.dpGrid[e][t].value;for(let e=0;e<this.step;e++)o+="|";for(;e>0||t>0;){this.dpGrid[e][t].parentI==e?(n=o+n,i=this.seq2.substr((t-1)*this.step,this.step)+i):this.dpGrid[e][t].parentJ==t?(i=o+i,n=this.seq1.substr((e-1)*this.step,this.step)+n):(n=e-1>=0?this.seq1.substr((e-1)*this.step,this.step)+n:o+n,i=t-1>=0?this.seq2.substr((t-1)*this.step,this.step)+i:o+i);const s=e;e=this.dpGrid[e][t].parentI,t=this.dpGrid[s][t].parentJ}return new lt(n,i,s)}fillScores(){this.scores=[];for(let e=0;e<this.len1;e++){this.scores.push([]);for(let t=0;t<this.len2;t++)this.scores[e].push(this.alignGrid[this.connections[this.seq1.substr(e*this.step,this.step)]][this.connections[this.seq2.substr(t*this.step,this.step)]])}}typeRec(){if(/[ATGC]*/.test(this.seq1)&&/[ATGC]*/.test(this.seq2))return"NUCLEOTIDES";if(/[ARNDCQEGHILKMFPSTWYVBZX*]*/.test(this.seq1)&&/[ARNDCQEGHILKMFPSTWYVBZX*]*/.test(this.seq2))return"BLOSUM62";throw Error("Can't recognize sequence type")}needlemanWunsch(){this.dpGrid=[];for(let e=0;e<this.len1+1;e++){const e=[];for(let t=0;t<this.len2+1;t++)e.push(new at);this.dpGrid.push(e)}this.fillNeedleman();for(let e=1;e<=this.len1;e++)for(let t=1;t<=this.len2;t++)this.fillOne(e,t);return this.constructResult(this.len1,this.len2)}smithWaterman(){this.dpGrid=[];for(let e=0;e<this.len1+1;e++){const e=[];for(let t=0;t<this.len2+1;t++)e.push(new at);this.dpGrid.push(e)}let e=0,t=0,n=0;for(let i=1;i<=this.len1;i++)for(let o=1;o<=this.len2;o++)this.fillOne(i,o),this.dpGrid[i][o].value<=0?(this.dpGrid[i][o].value=0,this.dpGrid[i][o].parentI=0,this.dpGrid[i][o].parentJ=0):0==this.dpGrid[this.dpGrid[i][o].parentI][this.dpGrid[i][o].parentJ].value&&(this.dpGrid[i][o].parentI=0,this.dpGrid[i][o].parentJ=0),this.dpGrid[i][o].value>e&&(e=this.dpGrid[i][o].value,t=i,n=o);return this.constructResult(t,n)}setSequences(e,t){this.seq1=e,this.seq2=t,this.len1=this.seq1.length/this.step,this.len2=this.seq2.length/this.step,this.fillScores()}setGap(e){this.gap=e}setMethod(e=""){"AUTO"==e&&(e=this.typeRec()),this.gridFromName(e)}constructor(e,t,n,i=""){this.setMethod(i),this.setSequences(e,t),this.setGap(n)}}async function ut(e,t,n="Morgan",i=1,o=.6){const s=e.length,a=Uo.seqHelper.getSeqHandler(e),l=Array(s);let c=1;const u=new Map,h=e.categories,d=e.getRawData();for(let t=0;t<s;t++){if(null==h[d[t]]||e.isNone(t)){l[t]=null;continue}l[t]="";const n=a.getSplitted(t);for(let e=0;e<n.length;e++){const i=n.getCanonical(e);u.has(i)||(u.set(i,String.fromCharCode(c)),c++),l[t]+=u.get(i)}}let m={};if(t===ce.Z.MONOMER_CHEMICAL_DISTANCE||t===ce.Z.NEEDLEMANN_WUNSCH){const e=Array.from(u.keys()),s=await async function(e,t="Morgan"){const n=(await(0,ye.pj)()).getMonomerLib(),i=new Array(e.length).fill(0).map(()=>new Array(e.length).fill(0)),o={},s=e.map(e=>n.getMonomer("PEPTIDE",e)?.molfile||n.getMonomer("PEPTIDE",e)?.smiles||""),a=r.Func.find({package:"Chem",name:"getFingerprints"})[0];if(!a)return console.warn('Function "Chem:getFingerprints" is not found in chem package. falling back to Morgan fingerprints'),await be(e);const l=r.Column.fromStrings("smiles",s),c=(r.DataFrame.fromColumns([l]),(await a.apply({col:l,fingerprintType:t}))?.entries);if(!c)return console.warn(`${t} Fingerprints could not be calculated for monomers from chem package.\n falling back to Morgan fingerprints`),await be(e);for(let t=0;t<c.length;++t)if(i[t][t]=1,o[e[t]]=t,c[t])for(let e=t+1;e<c.length;++e)c[e]&&(i[t][e]=i[e][t]=(0,$.$1)(c[t],c[e]));return{scoringMatrix:i,alphabetIndexes:o}}(e,n),a={};Object.entries(s.alphabetIndexes).forEach(([e,t])=>{a[u.get(e)]=t});const c=l.reduce((e,t)=>Math.max(e,t?.length||0),0);m={scoringMatrix:s.scoringMatrix,alphabetIndexes:a,maxLength:c},t===ce.Z.NEEDLEMANN_WUNSCH&&(m.gapOpen=i,m.gapExtend=o)}return{seqList:l,options:m}}var ht=n(4954);function dt(e){const t=s.divH([],{style:{gap:"10px"}}),n=s.divV([s.divText(e.seqCol.name),s.divText(e.activityCol.name)]);return n.style.fontWeight="bold",n.style.display="flex",n.style.justifyContent="space-between",t.append(n),e.points.forEach(n=>{const i=s.divText(e.activityCol.get(n).toFixed(2));i.style.display="flex",i.style.justifyContent="left",i.style.paddingLeft="30px",t.append(s.divV([s.divText(e.seqCol.get(n)),i]))}),t}function mt(e){const t=s.div();t.append(s.divText(e.seqCol.name,{style:{fontWeight:"bold"}}));const n=new Array(2);e.points.forEach((t,i)=>{n[i]=e.activityCol.get(t)});const i={},o=Uo.seqHelper.getSeqHandler(e.seqCol),r=o.defaultBiotype,a=gt(o.getSplitted(e.points[0]),o.getSplitted(e.points[1]),r,i);return t.append(s.div(a,{style:{width:"300px",overflow:"scroll"}})),t.append(ft(i)),t.append(pt("Activity delta",Math.abs(n[0]-n[1]))),t.append(pt("Cliff",e.sali)),t}function pt(e,t){return s.divH([s.divText(`${e}: `,{style:{fontWeight:"bold",paddingRight:"5px"}}),s.divText(t.toFixed(2))],{style:{paddingTop:"10px"}})}function gt(e,t,n,i){const o=document.createElement("canvas"),s=o.getContext("2d");o.height=30;const r=Uo.monomerLib;return Ke(s,0,0,0,30,ee().count(0).take(e.length).map(t=>e.getCanonical(t)).toArray(),ee().count(0).take(t.length).map(e=>t.getCanonical(e)).toArray(),n,r,!0,i),o}function ft(e){const t=s.div();if(Object.keys(e).length>0){const n=s.divV([]);n.append(s.divH([s.divText("Pos",{style:{fontWeight:"bold",width:"30px",borderBottom:"1px solid"}}),s.divText("Difference",{style:{fontWeight:"bold",borderBottom:"1px solid"}})]));for(const t of Object.keys(e))e[t].style.borderBottom="1px solid lightgray",n.append(s.divH([s.divText((parseInt(t)+1).toString(),{style:{width:"30px",borderBottom:"1px solid lightgray"}}),e[t]]));t.append(n)}return t}function yt(e,t){if(!e.col("seq_diff")){const n=r.Column.string("seq_diff",e.rowCount).init(n=>`${e.get(t[0],n)}#${e.get(t[1],n)}`);n.semType="MacromoleculeDifference",n.meta.units=e.col(t[0]).meta.units,n.setTag(ue.gp.separator,e.col(t[0]).getTag(ue.gp.separator)),e.columns.add(n)}const n=e.plot.grid();return n.col(t[0]).visible=!1,n.col(t[1]).visible=!1,n}class bt extends r.JsViewer{constructor(e,t){super(),this.name="",this.semType="",this.initialized=!1,this.gridSelect=!1,this.maxLimit=100,this.recomputeOnCurrentRowChange=!0,this.skipRecomputingProperies=[],this.debounceTimer=null,this.computeRequested=!1,this.renderPromise=Promise.resolve(),this.limit=this.int("limit",10,{min:1,max:this.maxLimit}),this.targetColumnName=this.string("targetColumnName",null,{...t?{semType:t}:{},nullable:!1}),this.name=e,this.semType=t}init(){this.initialized=!0}detach(){this.subs.forEach(e=>e.unsubscribe())}async onTableAttached(){if(this.init(),this.dataFrame){this.subs.push(r.debounce(this.dataFrame.onRowsRemoved,50).subscribe(e=>this.render(!0)));const e="diversity"!==this.name;this.subs.push(r.debounce(this.dataFrame.onCurrentRowChanged,50).subscribe(t=>{this.gridSelect||this.render(e)})),this.subs.push(r.debounce(this.dataFrame.selection.onChanged,50).subscribe(e=>this.render(!1))),this.subs.push(r.debounce(s.onSizeChanged(this.root),50).subscribe(e=>this.render(!1))),this.targetColumnName??(this.targetColumnName=this.dataFrame.columns.bySemType(this.semType).name),this.targetColumn=this.dataFrame.col(this.targetColumnName),this.getProperty("limit").fromOptions({min:1,max:this.maxLimit})}this.render()}onPropertyChanged(e){if(super.onPropertyChanged(e),this.initialized){if("targetColumnName"===e.name){const t=this.dataFrame.col(e.get(this));t.semType===this.semType&&(this.targetColumn=t)}this.debouncedRender()}}debouncedRender(e=!0){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.render(e),this.debounceTimer=null},100)}render(e=!0){this.renderPromise=this.renderPromise.then(async()=>{this.computeRequested=this.computeRequested||e,await this.renderInt(e)})}async renderInt(e){}beforeRender(){return!(!this.initialized||!this.targetColumnName||this.dataFrame&&this.targetColumnName&&this.dataFrame.col(this.targetColumnName).semType!==this.semType&&(o.shell.error(`${this.targetColumnName} is not ${this.semType} type`),1))}}class wt extends bt{distanceMetric;fingerprint;gapOpen;gapExtend;metricsProperties=["distanceMetric","fingerprint","gapOpen","gapExtend"];fingerprintChoices=["Morgan","RDKit","Pattern","AtomPair","MACCS","TopologicalTorsion"];distanceFunctionChoices=[ce.Z.NEEDLEMANN_WUNSCH,ce.Z.HAMMING,ce.Z.LEVENSHTEIN,ce.Z.MONOMER_CHEMICAL_DISTANCE];tags=[r.TAGS.UNITS,ue.gp.aligned,ue.gp.separator,ue.gp.alphabet,"cell.renderer"];preComputeDistanceMatrix=!1;requiresSampling=!1;constructor(e,t){super(e,t),this.distanceMetric=this.string("distanceMetric",ce.Z.HAMMING,{choices:this.distanceFunctionChoices}),this.fingerprint=this.string("fingerprint",this.fingerprintChoices[0],{choices:this.fingerprintChoices}),this.gapOpen=this.float("gapOpen",1),this.gapExtend=this.float("gapExtend",.6)}async onTableAttached(){if(super.onTableAttached(),this.dataFrame){const e=this.dataFrame.rowCount;this.preComputeDistanceMatrix=e<=1e4,this.requiresSampling=e>1e4}}needsGapPenalties(){return this.distanceMetric===ce.Z.NEEDLEMANN_WUNSCH}needsFingerprint(){return this.distanceMetric===ce.Z.MONOMER_CHEMICAL_DISTANCE||this.distanceMetric===ce.Z.NEEDLEMANN_WUNSCH}}const vt={gapPenalty:1,matchScore:1,gapSymbol:pe.b9[pe.Hi.FASTA],localAlignment:!1};class Ct extends wt{seqHelper;cutoff;hotSearch;similarColumnLabel;sketchedMolecule="";curIdx=0;molCol=null;idxs=null;scores=null;gridSelect=!1;targetMoleculeIdx=0;computeCompleted=new c.Subject;distanceMatrixComputed=!1;mmDistanceMatrix;knn;kPrevNeighbors=0;demo;analysisGrid;subInited=!1;lastDistanceMetric="";lastFingerprint="";lastGapOpen=0;lastGapExtend=0;constructor(e,t){super("similarity",r.SEMTYPE.MACROMOLECULE),this.seqHelper=e,this.cutoff=this.float("cutoff",.01,{min:0,max:1}),this.hotSearch=this.bool("hotSearch",!0),this.similarColumnLabel=this.string("similarColumnLabel",null),this.demo=t}init(){this.hotSearch=!0,this.initialized=!0}async renderInt(e){if(this.beforeRender()&&this.targetColumn){this.curIdx=-1==(this.dataFrame?.currentRowIdx??-1)?0:this.dataFrame.currentRowIdx;const t=this.lastDistanceMetric!==this.distanceMetric||this.lastFingerprint!==this.fingerprint||this.lastGapOpen!==this.gapOpen||this.lastGapExtend!==this.gapExtend;if(e&&!this.gridSelect||t){this.targetMoleculeIdx=(this.dataFrame?.currentRowIdx??-1)<0?0:this.dataFrame.currentRowIdx,await this.computeByMM();const e=null!=this.similarColumnLabel?this.similarColumnLabel:`similar (${this.targetColumn})`;this.molCol=r.Column.string(e,this.idxs.length).init(e=>this.targetColumn?.get(this.idxs?.get(e))),this.molCol.semType=r.SEMTYPE.MACROMOLECULE,this.tags.forEach(e=>this.molCol.setTag(e,this.targetColumn.getTag(e)));const t=r.DataFrame.fromColumns([this.idxs,this.molCol,this.scores]);await t.meta.detectSemanticTypes(),await o.data.detectSemanticTypes(t),this.molCol.temp["reference-sequence"]=this.targetColumn.get(this.targetMoleculeIdx),this.molCol.temp[".mm.cellRenderer.maxMonomerLength"]=4;let n=null;t.onCurrentRowChanged.subscribe(e=>{n&&clearTimeout(n),(t?.currentRowIdx??-1)<0||(this.dataFrame&&(this.dataFrame.currentRowIdx=t.col("indexes").get(t.currentRowIdx)),n=setTimeout(()=>{this.createPropertyPanel(t)},300),this.gridSelect=!0)}),this.analysisGrid?(this.analysisGrid.dataFrame=t,this.analysisGrid.invalidate()):(this.analysisGrid=t.plot.grid(),(0,Ne.Ku)(this.root,this.analysisGrid.root)),this.analysisGrid.col("indexes").visible=!1,(0,Ne.Kd)(this.analysisGrid,this.molCol.name,450,30,!0);const i=this.idxs?.getRawData().findIndex(e=>e==this.targetMoleculeIdx);this.analysisGrid.cell("score",i).cell.value=null;const s=o.shell.tv;this.subInited||(s.grid.root.addEventListener("click",e=>{this.gridSelect=!1}),this.subInited=!0),this.computeCompleted.next(!0)}}}async computeByMM(){const e=this.targetColumn.length,t=Math.min(this.limit,e-1);if(!this.knn||this.kPrevNeighbors!==t||this.lastDistanceMetric!==this.distanceMetric||this.lastFingerprint!==this.fingerprint||this.lastGapOpen!==this.gapOpen||this.lastGapExtend!==this.gapExtend){const e=this.distanceMetric,n=await ut(this.targetColumn,e,this.fingerprint,this.gapOpen,this.gapExtend),i=n.seqList,o=n.options;this.lastDistanceMetric=this.distanceMetric,this.lastFingerprint=this.fingerprint,this.lastGapOpen=this.gapOpen,this.lastGapExtend=this.gapExtend,this.kPrevNeighbors=t,this.knn=await(new F).getKNN(i,e,t,o)}const n=new Array(t).fill(0).map((e,t)=>({idx:this.knn.knnIndexes[this.targetMoleculeIdx][t],score:1-this.knn.knnDistances[this.targetMoleculeIdx][t]}));n.sort((e,t)=>t.score-e.score),n.unshift({idx:this.targetMoleculeIdx,score:r.FLOAT_NULL}),this.idxs=r.Column.int("indexes",t+1).init(e=>n[e].idx),this.scores=r.Column.float("score",t+1).init(e=>n[e].score)}createPropertyPanel(e){const t=s.div(),n={},i=this.molCol?.name,r=e.col(i),a=this.seqHelper.getSeqHandler(this.targetColumn),l=this.seqHelper.getSeqHandler(r),c=a.getSplitted(this.targetMoleculeIdx),u=l.getSplitted(e.currentRowIdx),h=function(e,t,n={}){const i={...vt,...n};function o(e,t){return e===t?i.matchScore:-i.matchScore}const s=e.length,r=t.length,a=Array(s+1).fill(0).map(()=>Array(r+1).fill(0));let l=-9999,c=[1,1];for(let n=1;n<s+1;n++)for(let s=1;s<r+1;s++)a[n][s]=Math.max(0,a[n-1][s-1]+o(e.getCanonical(n-1),t.getCanonical(s-1)),a[n-1][s]-i.gapPenalty,a[n][s-1]-i.gapPenalty),a[n][s]>=l&&(l=a[n][s],c=[n,s]);let u=i.localAlignment?c[0]:s,h=i.localAlignment?c[1]:r,d=new Array(0),m=new Array(0);for(;u>0&&h>0;){const n=Math.max(a[u-1][h-1],a[u-1][h],a[u][h-1]);a[u][h]==a[u-1][h-1]+i.matchScore&&n==a[u-1][h-1]?(d.push(e.getCanonical(u-1)),m.push(t.getCanonical(h-1)),u-=1,h-=1):a[u][h]==a[u-1][h]-i.gapPenalty?(m.push(i.gapSymbol),d.push(e.getCanonical(u-1)),u-=1):a[u][h]==a[u][h-1]-i.gapPenalty?(d.push(i.gapSymbol),m.push(t.getCanonical(h-1)),h-=1):(d.push(e.getCanonical(u-1)),m.push(t.getCanonical(h-1)),u-=1,h-=1)}d=[...ee().count(0).take(u).map(t=>e.getCanonical(t)),...d.reverse(),...i.localAlignment?ee().count(c[0]).take(s).map(t=>e.getCanonical(t)):[]],m=[...ee().count(0).take(h).map(e=>t.getCanonical(e)),...m.reverse(),...i.localAlignment?ee().count(c[1]).take(r).map(e=>t.getCanonical(e)):[]];const p=u,g=h;return p>g?m=[...new Array(p-g).fill(i.gapSymbol.valueOf()),...m]:d=[...new Array(g-p).fill(i.gapSymbol.valueOf()),...d],m.length>d.length?d.push(...new Array(m.length-d.length).fill(i.gapSymbol.valueOf())):m.push(...new Array(d.length-m.length).fill(i.gapSymbol.valueOf())),{seq1:d.join(""),seq2:m.join(""),seq1Splitted:new Oe.Mu(d,i.gapSymbol),seq2Splitted:new Oe.Mu(m,i.gapSymbol)}}(c,u),d=gt(h.seq1Splitted,h.seq2Splitted,l.defaultBiotype,n);t.append(s.div(d,{style:{width:"300px",overflow:"scroll"}})),c.length!==u.length&&t.append(s.divV([s.divText("Different sequence length:",{style:{fontWeight:"bold"}}),s.divText(`target: ${c.length} monomers`),s.divText(`selected: ${u.length} monomers`)],{style:{paddingBottom:"10px"}})),t.append(ft(n));const m=s.accordion(),p=s.element("i");p.className="grok-icon svg-icon svg-view-layout",m.addTitle(s.span([p,s.label("Similarity search")])),m.addPane("Differences",()=>t,!0),o.shell.o=m.root}}class At extends wt{seqHelper;diverseColumnLabel;renderMolIds=null;columnNames=[];computeCompleted=new c.Subject;sampledIndices=null;constructor(e){super("diversity",r.SEMTYPE.MACROMOLECULE),this.seqHelper=e,this.diverseColumnLabel=this.string("diverseColumnLabel",null)}async renderInt(e){if(this.beforeRender()&&this.dataFrame&&e&&this.targetColumn){await this.computeByMM();const e=null!=this.diverseColumnLabel?this.diverseColumnLabel:`diverse (${this.targetColumnName})`,t=r.Column.string(e,this.renderMolIds.length).init(e=>this.targetColumn?.get(this.renderMolIds[e]));t.semType=r.SEMTYPE.MACROMOLECULE,this.tags.forEach(e=>t.setTag(e,this.targetColumn.getTag(e)));const n=r.DataFrame.fromColumns([t]);t.temp[".mm.cellRenderer.maxMonomerLength"]=4,n.onCurrentRowChanged.subscribe(e=>{this.dataFrame.currentRowIdx=this.renderMolIds[n.currentRowIdx]});const i=n.plot.grid();(0,Ne.Kd)(i,t.name,450,30),(0,Ne.Ku)(this.root,i.root),this.computeCompleted.next(!0)}}async computeByMM(){const e=this.targetColumn.length;let t;this.requiresSampling&&e>1e4?(t=this.createRandomSample(e,1e4),this.sampledIndices=t):(t=Array.from({length:e},(e,t)=>t),this.sampledIndices=null);const n=this.distanceMetric,i=await ut(this.targetColumn,n,this.fingerprint,this.gapOpen,this.gapExtend),o=i.seqList,s=i.options,r=t.map(e=>o[e]),a=new D(!0,!1),l=await a.calc(r,n,!0,s);a.terminate();const c=t.length,u=(d=c,(e,t)=>d*e+t-Math.floor((e+2)*(e+1)/2)),h=function(e,t){function n(e,t){let n=null,i=null;for(const o of e){const e=t(o);(null==i||e>i)&&(n=o,i=e)}return n}const i=[(s=e-1,Math.floor(function(e){return Math.random()*e}(s)))],o=new Set;var s;for(let t=0;t<e;++t)i.includes(t)||o.add(t);for(;i.length<t;){const e=n(o.values(),e=>Math.min.apply(Math,i.map(function(t,n){return l[u(e,t)]})));null!=e&&(i.push(e),o.delete(e))}return i}(c,Math.min(c,this.limit));var d;this.renderMolIds=h.map(e=>t[e])}createRandomSample(e,t){const n=[];for(let t=0;t<e;t++)this.targetColumn.isNone(t)||n.push(t);if(n.length<=t)return n;for(let e=n.length-1;e>0;e--){const t=Math.floor(Math.random()*(e+1)),i=n[e];n[e]=n[t],n[t]=i}return n.slice(0,t)}}var Tt=n(5433);var Et=n(3736),St=n(4517);class Mt{constructor(e,t=[],n={}){this.onItemChanged=new c.Subject,this.onAddingItemChanged=new c.Subject,this.onItemAdded=new c.Subject,this.onItemRemoved=new c.Subject,this.options={removeButtonTooltip:"Remove item",addButtonTooltip:"Add item",allowAdd:!0,allowRemove:!0},this.addingItemInputs={},this.properties=e,this.options=Object.assign(Object.assign({},this.options),n),this._root=s.divV([],{style:{display:"grid",gridTemplateColumns:`repeat(${this.properties.length}, 1fr)`,alignItems:"center",gap:"12px"},classes:"ui-items-grid"}),this._items=t,this.render()}get root(){return this._root}get items(){return this._items}set items(e){this._items=e,this.render()}addItem(e,t=!0){this._items.push(e),this.render(),t&&this.onItemAdded.next(e)}removeItem(e,t=!0){-1!==this._items.indexOf(e)&&(this._items.splice(this._items.indexOf(e),1),this.render(),t&&this.onItemRemoved.next(e))}removeAtIndex(e,t=!0){if(e<0||e>=this._items.length)return;const n=this._items.splice(e,1);this.render(),t&&this.onItemRemoved.next(n[0])}removeAllItems(){this._items=[],this.render()}render(){var e,t,n,i,o;if(s.empty(this._root),!this.options.horizontalInputNames)for(const n of this.properties){let i=null!==(e=n.caption)&&void 0!==e?e:n.name;(null===(t=this.options.customLabels)||void 0===t?void 0:t[n.name])&&(i=this.options.customLabels[n.name]);const o=s.divText(i);o.style.fontWeight="bold",this._root.appendChild(o)}for(const e of this._items){const t=this.getItemDiv(e);for(const e of t)this._root.appendChild(e)}if(this.options.allowAdd){const e=this.getItemDiv(null!==(o=null===(i=(n=this.options).newItemFunction)||void 0===i?void 0:i.call(n))&&void 0!==o?o:void 0,!0);for(const t of e)this._root.appendChild(t)}}get addingItem(){const e={};return Object.keys(this.addingItemInputs).forEach(t=>{e[t]=this.addingItemInputs[t].value}),e}getItemDiv(e={},t){var n,i;const o=[],a={};let l=null;for(const c of this.properties){void 0===e[c.name]&&(e[c.name]=null);const u=(null===(n=this.options.customInputs)||void 0===n?void 0:n[c.name])?this.options.customInputs[c.name](e):s.input.forProperty(c,e),h=null===(i=this.options.validators)||void 0===i?void 0:i[c.name];h&&u.addValidator(h),o.push(this.options.horizontalInputNames?u.root:this.hideLabel(u.root)),c.propertyType!==r.TYPE.BOOL&&"color"!==c.name.toLowerCase()&&u.input&&(u.input.style.width="100%"),a[c.name]=u,u.onChanged.subscribe(()=>{e[c.name]=u.value,t?this.onAddingItemChanged.next({item:e,fieldName:c.name}):this.onItemChanged.next({item:e,fieldName:c.name})}),u.root.style.alignItems="center",l=u}let c=null;if(t)this.addingItemInputs=a,c=s.icons.add(()=>{const e=this.options.newItemFunction?this.options.newItemFunction():{};Object.keys(a).forEach(t=>{e[t]=a[t].value}),this._items.push(e),this.onItemAdded.next(e),this.render()},this.options.addButtonTooltip);else{if(!this.options.allowRemove)return o;c=s.icons.delete(()=>{this._items.splice(this._items.indexOf(e),1),this.onItemRemoved.next(e),this.render()},this.options.removeButtonTooltip)}return l&&l.addOptions?l.addOptions(c):null==l||l.root.appendChild(c),c.style.color="#2083d5",o}hideLabel(e){return e.getElementsByTagName("label")[0]&&e.removeChild(e.getElementsByTagName("label")[0]),e}hasErrors(){return this._root.querySelectorAll(".d4-invalid").length>0}}const xt={A:new G.A(new Uint32Array([2,0,0,0,16,0,0,0,134217728,0,0,0,32,0,33554432,0,0,0,0,0,1024,0,0,0,262144,128,0,0,0,0,0,0,0,2,0,0,524288,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1048576,0,536870912,0,0,0,0]),2048),C:new G.A(new Uint32Array([2,0,65536,0,0,0,0,32,0,0,2,0,32,0,0,0,0,0,0,0,1024,0,0,0,262144,128,0,0,0,0,0,0,0,65536,0,0,524288,0,0,0,0,0,0,0,524288,524288,0,0,0,0,0,0,0,0,0,0,0,34603008,0,536870912,64,0,0,0]),2048),D:new G.A(new Uint32Array([2,0,65600,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,1024,0,0,0,262400,128,0,0,0,0,0,0,0,0,0,2097152,524288,0,0,0,1024,0,0,0,524288,0,0,0,0,0,0,0,0,0,512,0,0,34603008,0,536870912,0,0,0,0]),2048),E:new G.A(new Uint32Array([2,0,65536,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,1024,0,0,8,262144,128,0,0,16,134217728,0,0,0,0,0,0,524288,0,0,0,128,0,0,0,524288,0,0,0,268435456,0,0,0,0,0,512,2147483648,0,34603008,0,536870912,0,0,0,0]),2048),F:new G.A(new Uint32Array([2,0,98304,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,1024,0,0,0,262144,128,33554432,0,0,0,0,33554432,0,1024,1,0,524288,32768,32,0,0,0,0,16,524288,0,0,0,0,0,0,0,0,0,71303168,0,0,34603008,131072,536870912,0,0,0,0]),2048),G:new G.A(new Uint32Array([134217728,0,65536,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,1024,0,0,0,0,128,0,0,0,0,2097216,0,0,0,0,0,524288,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,512,0,0,0,0,536870912,0,0,0,0]),2048),H:new G.A(new Uint32Array([2,0,1073840128,0,0,0,0,0,0,0,0,67108864,32,0,0,0,0,0,0,0,1024,0,512,0,262144,192,0,268435456,0,0,8200,0,0,0,67108864,0,524296,0,32,0,0,0,0,16,524288,0,0,2147483648,0,0,8,0,0,0,0,0,0,34603008,131072,536870920,4194304,0,0,0]),2048),I:new G.A(new Uint32Array([2,0,65536,0,0,0,0,0,150994944,64,0,0,32,0,0,0,0,0,0,0,1024,0,8388608,0,327680,128,0,0,0,0,0,0,0,2,0,524288,524288,0,0,0,0,0,0,0,0,0,0,0,256,0,0,0,0,8388608,0,33554432,0,1048576,0,536870912,0,0,0,0]),2048),K:new G.A(new Uint32Array([2,0,65536,0,0,0,0,0,0,0,0,0,268435488,0,0,0,0,0,0,0,1024,0,0,8,262144,128,0,0,0,0,2097152,0,0,67108864,0,0,524288,0,0,0,8,0,0,0,524288,0,0,8192,0,0,0,0,0,0,0,2147483648,0,34668544,0,545259520,0,0,0,0]),2048),L:new G.A(new Uint32Array([2,0,65536,0,0,0,0,0,134217728,0,0,0,32,512,0,0,0,0,0,0,1024,256,0,8388608,262400,128,0,0,0,0,0,0,0,2,0,0,524288,0,0,0,0,0,0,0,524288,0,0,0,0,0,0,0,0,0,0,0,0,42991616,0,536870912,0,0,0,0]),2048),M:new G.A(new Uint32Array([2050,0,65536,1048576,0,0,0,0,0,0,0,0,1056,0,0,0,0,0,0,0,1024,0,0,8,262144,128,0,0,0,0,0,536870912,0,2,0,0,1074266112,0,0,0,0,0,0,0,524288,0,0,0,4194304,0,0,0,0,0,0,2147483648,0,34603008,0,536870912,4194304,0,0,0]),2048),N:new G.A(new Uint32Array([2,0,65536,0,4096,0,0,0,0,0,0,16777216,32,0,0,0,0,0,0,0,1024,0,0,0,262400,128,0,0,0,0,0,0,0,0,0,0,524288,0,0,0,1024,0,0,0,524288,0,0,0,0,0,0,0,0,0,0,0,0,34603008,0,536871936,67108864,0,0,0]),2048),P:new G.A(new Uint32Array([0,0,1024,0,0,0,0,0,0,131072,0,1024,32,0,0,0,0,512,0,0,1024,0,0,64,0,128,0,0,1073741824,0,0,138412032,16,0,67108864,0,0,0,0,0,0,8192,0,0,8388608,0,0,8,0,0,0,0,0,0,256,0,0,0,0,553648128,0,0,0,0]),2048),Q:new G.A(new Uint32Array([2,0,65536,0,4096,0,0,0,0,0,0,0,32,0,0,0,0,2,0,0,1024,0,0,8,262144,128,0,0,16,0,0,0,0,0,0,0,524288,0,0,0,0,0,0,0,524288,0,0,0,268435456,0,0,0,0,0,16777216,2147483648,0,34603008,0,536871936,0,0,0,0]),2048),R:new G.A(new Uint32Array([2,0,65536,0,4096,0,32,0,0,0,0,0,268435488,0,0,0,0,0,0,32768,134218752,0,16,8,262144,128,0,1073741824,0,0,8388608,0,0,0,65536,0,524289,0,0,0,0,0,0,0,524288,2048,0,0,0,0,0,0,0,0,0,2147483648,0,34603008,1048576,545259520,0,0,0,0]),2048),S:new G.A(new Uint32Array([2,0,65536,0,0,0,1073741824,0,0,0,0,0,32,0,0,4,0,0,0,0,1024,0,0,0,262144,128,0,0,0,0,0,0,0,0,0,0,524288,0,0,1048576,0,0,0,0,524288,0,0,0,0,0,0,0,0,0,8388608,0,0,34603008,0,536870912,0,0,0,0]),2048),T:new G.A(new Uint32Array([2,0,0,0,0,0,0,8,134217728,0,0,67108864,32,0,0,0,0,0,0,0,1024,0,8388608,0,262144,128,0,0,0,0,0,0,0,2,0,524288,524288,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,536870912,0,0,0,0,1048576,67108864,536870912,0,0,0,0]),2048),V:new G.A(new Uint32Array([2,0,0,0,0,0,0,0,134217728,0,0,0,32,0,0,0,0,0,0,0,1024,0,8388608,0,262144,128,0,0,0,0,0,1073741824,128,2,0,524288,524288,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8192,0,1048576,0,536870912,0,0,0,0]),2048),W:new G.A(new Uint32Array([2,0,98304,8388608,0,0,0,0,0,0,256,4096,32,0,0,0,0,0,0,0,1024,0,0,0,262144,192,0,0,0,0,0,0,0,0,67108865,0,524288,32768,32,0,0,0,8224,16,524288,0,0,0,0,32,128,0,2097152,0,4194304,8388608,0,34603008,8519680,536870912,131072,262144,0,0]),2048),Y:new G.A(new Uint32Array([2,0,98304,0,0,0,0,0,0,4194304,0,0,32,0,0,0,0,0,0,0,1024,0,0,512,262144,128,33554432,0,0,0,0,33554432,0,0,0,0,524288,0,32,0,0,2,0,16,524288,0,0,0,0,0,4,0,0,0,71303168,262144,0,34603008,131072,536870912,0,0,0,0]),2048)},Pt={RNA:{A:new G.A(new Uint32Array([0,0,0,0,0,0,0,0,0,1024,0,67108864,0,0,0,512,0,0,0,8388608,0,0,512,0,0,64,4,0,0,0,4,0,0,0,67108864,0,524289,0,0,0,0,0,0,16,0,659456,0,256,0,16,0,0,0,268435456,0,0,262144,0,131072,0,0,0,8388608,0]),2048),C:new G.A(new Uint32Array([0,1073741824,0,0,0,0,0,2147483648,4,67108864,0,67108864,0,256,0,0,0,0,0,0,1024,0,128,0,0,64,0,0,0,0,0,0,0,0,67108864,0,524289,0,65536,0,0,0,0,16,0,131072,0,4,0,0,0,0,0,0,4194304,0,0,2147483648,131072,0,4096,0,0,0]),2048),G:new G.A(new Uint32Array([0,0,0,0,1024,0,0,0,0,67109888,16384,67108864,0,0,0,0,0,0,0,33562624,1024,33554432,512,16384,0,64,4,0,0,33554432,0,0,0,0,67108864,0,524289,0,0,0,0,0,0,16,0,135168,0,268435456,0,0,0,0,0,268435456,131072,0,0,2147483648,131072,0,0,0,8388608,0]),2048),T:new G.A(new Uint32Array([8388608,0,0,0,0,0,0,0,0,67108864,0,0,0,4,0,0,0,0,0,0,1024,0,0,16384,0,64,0,0,0,0,0,0,0,2,67108864,0,0,0,0,0,0,0,0,40976,0,0,0,0,0,0,0,0,0,67108864,131072,524288,0,0,8519680,0,1,33554432,1048576,0]),2048),U:new G.A(new Uint32Array([0,0,131072,1073741824,0,0,0,0,0,67108864,0,0,0,0,0,0,0,0,0,0,1024,0,128,0,0,64,0,0,0,0,0,0,0,32768,67108864,0,0,0,0,0,0,0,0,16,0,0,0,4,0,0,2048,0,0,0,4341760,0,0,0,131072,0,0,33554432,1048576,0]),2048)},PEPTIDE:xt};async function Lt(e,t,n=0){if(!Object.keys(Pt).includes(t))return null;const i=await async function(e){const t=r.Func.find({package:"Chem",name:"getMorganFingerprint"})?.[0];if(!t)return null;try{const n=(await t.apply({molString:e}))?.getBuffer().buffer;if(n)return new G.A(new Uint32Array(n),2048)}catch(e){return null}}(e);if(!i)return null;if(!Pt[t])return null;const o=Pt[t];let s=0,a=null;for(const[e,t]of Object.entries(o)){const o=(0,$.$1)(i,t);o>s&&o>=n&&(s=o,a=e)}return a}var It;!function(e){e.TYPE="V2000",e[e.NUM_OF_HEADER_LINES=3]="NUM_OF_HEADER_LINES",e[e.NUM_OF_COUNTS_DIGITS=3]="NUM_OF_COUNTS_DIGITS",e[e.ATOM_TYPE_COL=4]="ATOM_TYPE_COL",e[e.FIRST_BONDED_ATOM_COL=1]="FIRST_BONDED_ATOM_COL",e[e.BOND_TYPE_COL=3]="BOND_TYPE_COL",e[e.RGP_SHIFT=8]="RGP_SHIFT",e[e.MAX_ATOM_COUNT=999]="MAX_ATOM_COUNT",e.RGP_LINE_START="M RGP",e.ATOM_ALIAS_LINE_START="A ",e.END="M END"}(It||(It={}));class _t{constructor(e){this.init(e)}init(e){this.fileContent=e.replace(/\r/g,""),this._atomCount=void 0,this._atomTypes=void 0,this._bondCount=void 0,this._bondTypes=void 0,this.xyzAtomCoordinates=void 0,this._pairsOfBondedAtoms=void 0}get atomCount(){return void 0===this._atomCount&&this.setAtomAndBondCounts(),this._atomCount}get bondCount(){return void 0===this._bondCount&&this.setAtomAndBondCounts(),this._bondCount}get x(){var e;return null!==(e=this.xyzAtomCoordinates)&&void 0!==e||(this.xyzAtomCoordinates=this.parseAtomCoordinates()),this.xyzAtomCoordinates.x}get y(){var e;return null!==(e=this.xyzAtomCoordinates)&&void 0!==e||(this.xyzAtomCoordinates=this.parseAtomCoordinates()),this.xyzAtomCoordinates.y}get z(){var e;return null!==(e=this.xyzAtomCoordinates)&&void 0!==e||(this.xyzAtomCoordinates=this.parseAtomCoordinates()),this.xyzAtomCoordinates.z}get atomTypes(){var e;return null!==(e=this._atomTypes)&&void 0!==e||(this._atomTypes=this.parseAtomTypes()),this._atomTypes}get pairsOfBondedAtoms(){var e;return null!==(e=this._pairsOfBondedAtoms)&&void 0!==e||(this._pairsOfBondedAtoms=this.parseBondedAtomPairs()),this._pairsOfBondedAtoms}get bondTypes(){var e;return null!==(e=this._bondTypes)&&void 0!==e||(this._bondTypes=this.parseBondTypes()),this._bondTypes}setAtomAndBondCounts(){const{atomCount:e,bondCount:t}=this.parseAtomAndBondCounts();this._atomCount=e,this._bondCount=t}getNextColumnIdx(e){for(;!this.isWhitespace(e);)++e;for(;this.isWhitespace(e);)++e;return e}shiftIdxToSpecifiedColumn(e,t){let n=e;const i=this.isWhitespace(n)?t:t-1;for(let e=0;e<i;e++)n=this.getNextColumnIdx(n);return n}parseAtomTypes(){const e=this.atomCount,t=new Array(e);let n=this.getAtomBlockIdx();for(let i=0;i<e;i++)n=this.shiftIdxToAtomType(n),t[i]=this.parseAtomType(n),n=this.getNextLineIdx(n);return t}parseAtomCoordinates(){const e=new Float32Array(this.atomCount),t=new Float32Array(this.atomCount),n=new Float32Array(this.atomCount);let i=this.getAtomBlockIdx();for(let o=0;o<this.atomCount;o++){i=this.shiftIdxToXColumn(i);for(const s of[e,t,n])s[o]=this.parseFloatValue(i),i=this.getNextColumnIdx(i);i=this.getNextLineIdx(i)}return{x:e,y:t,z:n}}parseBondedAtomPairs(){const e=new Array(this.bondCount);let t=this.getBondBlockIdx();for(let n=0;n<this.bondCount;n++){t=this.shiftIdxToBondedAtomsPair(t);const i=new Uint16Array(2);i[0]=this.parseIntValue(t),t=this.getNextColumnIdx(t),i[1]=this.parseIntValue(t),e[n]=i,t=this.getNextLineIdx(t)}return e}parseBondTypes(){const e=this.bondCount,t=new Uint16Array(e);let n=this.getBondBlockIdx();for(let i=0;i<e;i++)n=this.shiftIdxToBondType(n),t[i]=this.parseIntValue(n),n=this.getNextLineIdx(n);return t}isWhitespace(e){const t=this.fileContent[e];return" "===t||"\t"===t}getNextLineIdx(e){return"\n"!==this.fileContent[e]?this.fileContent.indexOf("\n",e)+1:e+1}parseFloatValue(e){return this.parseNumericValue(parseFloat,e)}parseIntValue(e){return this.parseNumericValue(parseInt,e)}parseNumericValue(e,t){let n=t+1;for(;!this.isWhitespace(n);)++n;return e(this.fileContent.substring(t,n))}}class Nt extends _t{constructor(e){super(e),this.init(e)}init(e){super.init(e)}parseAtomType(e){let t=e,n=t;return this.isQuote(t)?(n=this.getNextIdenticalChar(t),t++):n=this.fileContent.indexOf(" ",n),this.fileContent.substring(t,n)}isQuote(e){const t=this.fileContent[e].charCodeAt(0);return 39===t||34===t}getNextIdenticalChar(e){const t=this.fileContent[e];return t?this.fileContent.indexOf(t,e+1):-1}isQuery(){return this.isQueryOrFragment((e,t)=>{return 39===e||34===e||76===e&&!((n=this.fileContent.charCodeAt(t+1))>64&&n<91||n>96&&n<123);var n})}isFragment(){return this.isQueryOrFragment(e=>82===e||42===e)}isQueryOrFragment(e){const t=this.atomCount;let n=this.getAtomBlockIdx();for(let i=0;i<t;i++){if(n=this.shiftIdxToAtomType(n),e(this.fileContent.charCodeAt(n),n))return!0;n=this.getNextLineIdx(n)}return!1}}class Rt extends Nt{constructor(e){super(e)}getAtomLines(){const e=this.getAtomBlockIdx(),t=this.getBondBlockIdx();return this.fileContent.substring(e,t).split("\n").slice(0,this.atomCount)}getBondLines(){const e=this.getBondBlockIdx();return this.fileContent.substring(e).split("\n").slice(0,this.bondCount)}getRGroupIdToAtomicIdxMap(){const e=new Map,t=this.fileContent.split("\n");t.filter(e=>e.startsWith(It.RGP_LINE_START)).forEach(t=>{const n=this.getAtomIdxToRgpIdxList(t);for(const[t,i]of n){if(e.has(t))throw new Error(`R group ${t} is already in the map`);e.set(t,i)}});const n=t.map((e,t)=>{if(e.startsWith(It.ATOM_ALIAS_LINE_START))return t}).filter(e=>void 0!==e),i=n.map(e=>t[e]),o=n.map(e=>t[e+1]);i.forEach((t,n)=>{const i=parseInt(t.split(/\s+/)[1])-1,s=parseInt(o[n].substring(1));if(e.has(s))throw new Error(`R group ${s} is already in the map`);e.set(s,i)});const s=this.getRGroupAtomicIndices().filter(t=>!Array.from(e.values()).includes(t));if(0!==s.length)throw new Error(`Unaccounted R group indices: ${s}`);return e}getAtomIdxToRgpIdxList(e){const t=e.split(/\s+/).filter(e=>e).slice(3).map(e=>parseInt(e)),n=new Array(t.length/2);for(let e=0;e<t.length;e+=2)n[e/2]=[t[e+1],t[e]-1];return n}getRGroupAtomicIndices(){return this.atomTypes.map((e,t)=>{if(e.includes("R#"))return t}).filter(e=>void 0!==e)}static isValidMolfile(e){return-1!==e.indexOf(It.TYPE)&&-1!==e.indexOf(It.END)}shiftIdxToAtomType(e){return this.shiftIdxToSpecifiedColumn(e,It.ATOM_TYPE_COL)}getCountsLineIdx(){let e=0;for(let t=0;t<It.NUM_OF_HEADER_LINES;++t)e=this.getNextLineIdx(e);return e}getAtomBlockIdx(){let e=this.getCountsLineIdx();return e=this.getNextLineIdx(e),e}shiftIdxToXColumn(e){return this.getNextColumnIdx(e)}shiftIdxToBondedAtomsPair(e){return this.shiftIdxToSpecifiedColumn(e,It.FIRST_BONDED_ATOM_COL)}shiftIdxToBondType(e){return this.shiftIdxToSpecifiedColumn(e,It.BOND_TYPE_COL)}getBondBlockIdx(){let e=this.getAtomBlockIdx();for(let t=0;t<this.atomCount;t++)e=this.getNextLineIdx(e);return e}parseAtomAndBondCounts(){let e=this.getCountsLineIdx(),t=e+It.NUM_OF_COUNTS_DIGITS;const n=parseInt(this.fileContent.substring(e,t));return e=t,t+=It.NUM_OF_COUNTS_DIGITS,{atomCount:n,bondCount:parseInt(this.fileContent.substring(e,t))}}}class $t extends Nt{constructor(e){super(e),this.init(e)}getAtomLines(){const e=this.getAtomBlockIdx(),t=this.getBondBlockIdx();return this.fileContent.substring(e,t).split("\n").slice(0,this.atomCount)}getBondLines(){const e=this.getBondBlockIdx();return this.fileContent.substring(e).split("\n").slice(0,this.bondCount)}getRGroupIdToAtomicIdxMap(){const e=new Map;return this.getAtomLines().forEach((t,n)=>{const i=t.match(/RGROUPS=\(([\d\s]+)\)/);if(i){const t=i[1].split(/\s+/).map(e=>parseInt(e));if(t.length>2)throw new Error(`R group data ${t} has more than 2 elements`);const o=t[1];if(e.has(o))throw new Error(`R group ${o} is already in the map`);e.set(o,n)}}),e}shiftIdxToAtomType(e){return this.shiftIdxToSpecifiedColumn(e,4)}getCountsLineIdx(){return this.fileContent.indexOf("M V30 COUNTS ")}getAtomBlockIdx(){let e=this.fileContent.indexOf("M V30 BEGIN ATOM");return e=this.getNextLineIdx(e),e}shiftIdxToXColumn(e){let t=this.shiftIdxToAtomType(e);return this.isQuote(t)?(t=this.getNextIdenticalChar(t),t=this.getNextColumnIdx(t),t):this.shiftIdxToSpecifiedColumn(e,5)}shiftIdxToBondedAtomsPair(e){return this.shiftIdxToSpecifiedColumn(e,5)}shiftIdxToBondType(e){return this.shiftIdxToSpecifiedColumn(e,4)}getBondBlockIdx(){return this.getNextLineIdx(this.fileContent.indexOf("M V30 BEGIN BOND"))}static isValidMolfile(e){return-1!==e.indexOf("V3000")&&-1!==e.indexOf("M END")}parseAtomAndBondCounts(){let e=this.fileContent.indexOf("M V30 COUNTS ")+14,t=this.fileContent.indexOf(" ",e+1);const n=parseInt(this.fileContent.substring(e,t));return e=t+1,t=this.fileContent.indexOf(" ",e+1),{atomCount:n,bondCount:parseInt(this.fileContent.substring(e,t))}}}class Ot{constructor(){}static getInstance(e){if(Ot.isMolfileV2K(e))return new Rt(e);if(Ot.isMolfileV3K(e))return new $t(e);throw new Error("Malformed molfile")}static isMolfileV2K(e){return Rt.isValidMolfile(e)}static isMolfileV3K(e){return $t.isValidMolfile(e)}}var Ht=n(6197),Dt=n(9124),Ft=n(3527);class kt{biotype;id;n;m;type;mt;smiles;get issmiles(){return!!this.smiles}at={R1:"H",R2:"H",R3:"H",R4:"H",R5:"H",R6:"H",R7:"H",R8:"H",R9:"H"};get rs(){return Object.keys(this.at).length}constructor(e,t,n="missing",i=void 0,o=void 0,s=void 0,r){if(this.biotype=e,this.id=t,this.n=n,this.m=i,this.type=o,this.mt=s,this.smiles=r,!this.id)throw new Error("Invalid arg undefined [id].")}static objCounter=-1;objId=++kt.objCounter;className="WebEditorMonomerDummy";toLog(){return`Helm: ${this.className}<${this.objId}>`}}class Gt extends kt{backgroundcolor="#808080";linecolor="#000000";textcolor="#000000";constructor(e,t,n,i,o){super(e,t,i,void 0,void 0,void 0,n),this.at={},o.forEach(e=>{this.at[e]="H"})}}class Bt extends kt{backgroundcolor="#FFFFFF";linecolor="#808080";textcolor="#808080";constructor(e){super(e,"*","gap")}}class Vt extends kt{backgroundcolor="#808080";linecolor="#000000";textcolor="#000000";constructor(e,t){super(e,t,"ambiguous")}}class Ut extends kt{backgroundcolor="#FF4444";linecolor="#800000";textcolor="#FFFFFF";constructor(e,t,n){super(e,t,"missing"),n&&(this.backgroundcolor="#C0C0C0",this.linecolor="#404040",this.textcolor="#404040")}}class qt extends kt{backgroundcolor="#FFFF44";linecolor="#800000";textcolor="#000000";constructor(e,t){super(e,t,"broken")}}class Wt{id;m;n;na;type;mt;at;smiles;get rs(){return Object.keys(this.at).length}get issmiles(){return!!this.smiles}linecolor;backgroundcolor;textcolor;constructor(e,t,n,i,o,s,r,a){this.id=e,this.m=t,this.n=n,this.na=i,this.type=o,this.mt=s,this.at=r,this.smiles=a}static fromMonomer(e,t,n){let i={};const o=t.symbol,s=t.smiles;if(t.rgroups.length>0)t.rgroups.forEach(e=>{i[e.label]=e.capGroupName});else{if(!s){if(t.lib)return new qt(e,o);throw new Error("Unexpected missing monomer without .lib")}i=n.getRS(s)}const r=new Wt(t.symbol,t.molfile,t.name,t.naturalAnalog,t.polymerType,t.monomerType,i),a=n.getMonomerColors(e,t.symbol);return a&&(r.textcolor=a?.textcolor,r.linecolor=a?.linecolor,r.backgroundcolor=a?.backgroundcolor),r}}const Yt={[Fe.o.BASE]:{A:"#20E040",G:"#040404",T:"#FF8080",C:"#2060FF",U:"#FF8080"},[Fe.o.NUCLEOTIDE]:{A:"#20E040",G:"#040404",T:"#FF8080",C:"#2060FF",U:"#FF8080"},[Fe.o.LINKER]:{P:"#9aa5e1",p:"#9aa5e1"},[Fe.o.SUGAR]:{R:"#7a85c1",r:"#7a85c1"},[Fe.o.AA]:{A:"rgb(44,160,44)",R:"rgb(23,190,207)",N:"rgb(235,137,70)",D:"rgb(31,119,180)",C:"rgb(188,189,34)",E:"rgb(31, 120, 150)",Q:"rgb(205, 111, 71)",G:"rgb(214,39,40)",H:"rgb(158,218,229)",I:"rgb(23,103,57)",L:"rgb(30,110,96)",K:"rgb(108, 218, 229)",M:"rgb(60,131,95)",F:"rgb(24,110,79)",P:"rgb(255,152,150)",S:"rgb(255,187,120)",T:"rgb(245,167,100)",W:"rgb(182, 223, 138)",Y:"rgb(152,223,138)",V:"rgb(74,160,74)"},[Fe.o.CHEM]:{R:"#eeeeee"},[Fe.o.BLOB]:{B:"#999999",G:"#e2e2e2"}},jt=/.*\|\$.*R.*\$\|/,Kt=/\[R(\d+)\]/,zt=/\[R(\d+)\]/g,Zt=/\[\*:(\d+)\]/g;function Xt(e,t){const n=Array.from(e.matchAll(zt)).map(e=>e[1]),i={name:"Explicit SMILES Monomer",smiles:e,polymerType:t??"CHEM",molfile:"",rgroups:n.map(e=>({label:`R${e}`,capGroupName:"H",capGroupSmiles:`[*:${e}][H]`,alternateId:`R${e}-H`})),author:"Datagrok auto-generated",id:0,createDate:null,monomerType:"Backbone"};try{let t=e;i.rgroups.forEach(e=>{const n=e.label.substring(1);t=t.replace(`[R${n}]`,`[*:${n}]`)});const n=Dn(o.chem.convert(t,o.chem.Notation.Smiles,o.chem.Notation.MolBlock));i.molfile=n,i.smiles=t}catch(t){Uo.logger.error(`getMonomerFromRSmiles: cannot convert SMILES to Molfile: ${e}\n${t}`)}return i}const Qt=/[\w()]+/,Jt=RegExp(String.raw`\(${Qt}(,${Qt})+\)`),en=e=>{const t=s.canvas(250,250);return o.chem.canvasMol(0,0,250,250,t,e),t},tn=new Ft.Mi([255,255,255]),nn=new Ft.Mi([0,0,0]),on=.7*(0,q.wQ)(tn);class sn{_monomers;source;_isEmpty;get isEmpty(){return this._isEmpty}_onChanged=new c.Subject;get onChanged(){return this._onChanged}constructor(e,t){this._monomers=e,this.source=t,this._isEmpty=!this._monomers||0===Object.keys(this._monomers).length||Object.entries(this._monomers).every(([e,t])=>0===Object.keys(t).length);for(const[e,t]of Object.entries(this._monomers))for(const[e,n]of Object.entries(t))n.lib=this}getMonomerSymbolsByType(e){const t=Object.keys(this._monomers[e]??{});return this._smilesMonomerCache[e]&&t.push(...Object.keys(this._smilesMonomerCache[e])),t}_smilesMonomerCache={};addMissingMonomer(e,t){let n=this._monomers[e];n||(n=this._monomers[e]={});let i=t;t==pe._S||t===pe.b9[pe.Hi.HELM]?i="Gap":("PEPTIDE"===e&&"X"===t||"RNA"===e&&"N"===t)&&(i="Any");const o=function(e,t){try{if(jt.test(e)){const n=e.split("|$"),i=n[0].trim(),o=n[1],s=Array.from(o.matchAll(/R(\d+)/g)),r=Array.from(i.matchAll(/(\*)/g));if(s.length!==r.length)return null;let a=i.replaceAll(/\[\*\]/g,"*");const l=s.map(e=>e[1]);for(let e=0;e<l.length;e++){const t=l[e];a=a.replace("*",`[R${t}]`)}return Xt(a,t)}let n=e;const i=Array.from(e.matchAll(Zt));for(const e of i){const t=e[0],i=e[1];n=n.replace(t,`[R${i}]`)}if(Kt.test(n))return Xt(n,t)}catch(t){Uo.logger.error(`smiles2Monomer: cannot parse SMILES: ${e}\n${t}`)}return null}(t,e);if(o){this._smilesMonomerCache[e]=this._smilesMonomerCache[e]??{};const i=this._smilesMonomerCache[e],s=Object.keys(i).length+1;i[t]=`#${e[0]}${s}`;const r={...o,symbol:i[t]},a=new Gt((0,Oe.MD)(e),r.symbol,t,`SMILES Monomer ${r.symbol}`,r.rgroups.map(e=>e.label));return r.wem=a,n[r.symbol]=r,r}return n[t]={symbol:t,name:i,molfile:"",author:"MISSING",id:-1,rgroups:ee().count(1).take(9).map(e=>({capGroupSmiles:"",alternateId:"",capGroupName:"",label:`R${e.toString()}`})).toArray(),smiles:"",polymerType:e,monomerType:void 0,createDate:null}}getMonomer(e,t){let n=t;"RNA"==e&&"R"==n&&(n="r"),"RNA"==e&&"P"==n&&(n="p");let i=null;if(e){this._smilesMonomerCache[e]?.[n]&&(n=this._smilesMonomerCache[e][n]);const t=this._monomers[e];if(i=t?.[n]??null,!i)return this.getMonomer(null,n)}else for(const[e,t]of Object.entries(this._monomers))if(i=t[n],i)break;return i}getWebEditorMonomer(e,t){const[n,i]=(0,Dt.fA)(e,t),o=(0,Ht.Y)(n);let s=this.getMonomer(o,i);if(s&&n==Fe.o.SUGAR&&(s.rgroups?.length??0)<3)return null;s||(s=this.addMissingMonomer(o,i));let r=s.wem??null;return r||(i===pe._S||"*"==i?r=s.wem=new Bt(n):n===Fe.o.NUCLEOTIDE&&"N"===i||n===Fe.o.AA&&"X"===i||(Fe.o.CHEM,0)||Jt.test(i)?r=s.wem=new Vt(n,i):s.lib||(r=s.wem=new Ut(n,i,this.isEmpty)),r||(r=s.wem=Wt.fromMonomer(n,s,this))),r}getTooltip(e,t){const n=(0,Ht.Y)(e),i=s.div([],{classes:"ui-form ui-tooltip"}),o=this.getWebEditorMonomer(e,t),r=this.getMonomer(n,t);if(r){const e=r.symbol,[t,n,a]=(r.name,o?[o.textcolor,o.backgroundcolor,o.linecolor]:["#202020","#A0A0A0","#202020"]);let l;if(i.append(s.divH([s.div([e],{style:{textWrap:"nowrap",marginLeft:"4px",marginRight:"4px",color:t,backgroundColor:n,borderColor:a,borderWidth:"1px",borderStyle:"solid",borderRadius:"2px",padding:"3px",minWidth:"24px",textAlign:"center"}}),s.div([r.name],{style:{padding:"4px"}})],{style:{display:"flex",flexDirection:"row",justifyContent:"left"}})),l=r.molfile?en(r.molfile):r.smiles?s.divV([en(r.smiles),s.divText("from smiles",{style:{fontSize:"smaller"}})]):s.divText("No structure",{style:{margin:"6px"}}),i.append(s.div(l,{style:{display:"flex",flexDirection:"row",justifyContent:"center",margin:"6px"}})),r.symbol!=pe._S){let e=r.lib?.source;e?(e.endsWith(".json")&&(e=e.substring(0,e.length-5)),e=e.replace(/_/g," ").replace(/-/g," ").replace(/([a-z])([a-z])([A-Z])/g,"$1$2 $3"),r.polymerType&&i.append(s.divText(r.polymerType,{style:{fontStyle:"italic"}})),i.append(s.divText(e))):i.append(s.divText("Missed in libraries"))}}else i.append(s.divV([s.divText(`Monomer '${t}' of type '${n}' not found.`),s.divText("Open the Context Panel, then expand Manage Libraries")]));return i}getMonomerTextColor(e,t){const n=this.getMonomerColors(e,t),i=e=>{const t=/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/.exec(e);if(t)return[parseInt(t[1]),parseInt(t[2]),parseInt(t[3])];const n=r.Color.fromHtml(e);return[r.Color.r(n),r.Color.g(n),r.Color.b(n)]},o=i(n.textcolor),s=new Ft.Mi([...o.map(e=>e+1)]),a=(0,q.KE)(s,tn)/((0,q.wQ)(s)*(0,q.wQ)(tn)),l=i(n.backgroundcolor),c=new Ft.Mi([...l.map(e=>e+.01)]);let u;u=(0,q.KE)(c,tn)/((0,q.wQ)(c)*(0,q.wQ)(tn))<a?l:o;let h=new Ft.Mi(u);const d=(0,q.wQ)(h);return d>on&&(h=(0,q.dC)(nn,h,on/d)),`rgb(${h[0]}, ${h[1]}, ${h[2]})`}getMonomerColors(e,t){const n="default";let i=n;const o=(0,Ht.Y)(e),s=this.getMonomer(o,t);let a;if(s){if(s.meta&&s.meta.colors){if("string"==typeof s.meta.colors)try{s.meta.colors=JSON.parse(s.meta.colors)}catch(e){Uo.logger.error(`Bio: MonomerLib.getMonomerColors() failed to parse monomer.meta.colors: ${e}`)}const e=s.meta.colors;e&&"string"!=typeof e&&!(n in e)&&(i="default"),e&&"string"!=typeof e&&i in e&&(a=e[i])}if(!a){const t=Yt[e],n=t?.[s.symbol];n&&(a={textColor:r.Color.toHtml(r.Color.getContrastColor(r.Color.fromHtml(n))),lineColor:"#202020",backgroundColor:n})}const t=s.naturalAnalog;if(!a&&t&&t!==s.symbol)return this.getMonomerColors(e,t)}return a||(a={textColor:"#202020",lineColor:"#202020",backgroundColor:"#A0A0A0"}),{textcolor:a.text??a.textColor,linecolor:a.line??a.lineColor,backgroundcolor:a.background??a.backgroundColor}}getRS(e){const t=e.match(/(?<=\[)[^\][]*(?=])/gm),n={};let i,o="";if(t)for(let e=0;e<t.length;e++)if(null!=t[e]&&/\d/.test(t[e])){i=t[e][t[e].length-1],t[e]=t[e].replace(/[0-9]/g,"");for(let n=0;n<t[e].length;n++)":"!=t[e][n]&&(o+=t[e][n]);n["R"+i]=o,o=""}return n}}var rn=n(5488),an={};an.styleTagTransform=C(),an.setAttributes=y(),an.insert=g().bind(null,"head"),an.domAPI=m(),an.insertStyleElement=w(),h()(rn.A,an),rn.A&&rn.A.locals&&rn.A.locals;class ln extends sn{error;_duplicateMonomers={};get duplicateMonomers(){return this._duplicateMonomers}_duplicatesHandled=!0;get duplicatesHandled(){return this._duplicatesHandled}duplicatesNotified=!1;constructor(e,t,n=void 0){super(e,t),this.error=n}toJSON(){const e=[];for(const t of Object.values(this._monomers))for(const n of Object.values(t))e.push({...n,lib:void 0,wem:void 0});return e}_monomerSets=null;getMonomerSet(e){const t=(0,Ht.Y)(e);if(this._monomerSets||(this._monomerSets={}),!(e in this._monomerSets))for(const[e,n]of Object.entries(this._monomers[t]));return this._monomerSets[e]}getPolymerTypes(){return Object.keys(this._monomers)}getMonomerMolsByPolymerType(e){const t={};return Object.keys(this._monomers[e]??{}).forEach(n=>{t[n]=this._monomers[e][n].molfile}),t}getMonomerSymbolsByRGroup(e,t,n){let i=this.getMonomerSymbolsByType(t).map(e=>this.getMonomer(t,e));return i=i.filter(e=>null!==e),0===i.length?[]:(i=i.filter(t=>{if(!t?.rgroups)return!1;let n=t?.rgroups.length>=e;var i;return i=Ot.getInstance(t.molfile).atomTypes,i.map((e,t)=>"R#"===e?t:-1).filter(e=>-1!==e),n&&=!0,n}),i.map(e=>e?.symbol))}_updateLibInt(e){const t=e.getPolymerTypes(),n=this.getPolymerTypes();t.forEach(t=>{n.includes(t)||(this._monomers[t]={}),e.getMonomerSymbolsByType(t).forEach(n=>{this._monomers[t][n]&&(this._duplicateMonomers[t]??={},this._duplicateMonomers[t][n]??=[this._monomers[t][n]],this._duplicateMonomers[t][n].push(e.getMonomer(t,n))),this._monomers[t][n]=e.getMonomer(t,n)})}),this._isEmpty=this.isEmpty&&e.isEmpty}async updateLibs(e,t=!1){t&&(this._monomers={},this._isEmpty=!0),this._duplicateMonomers={};for(const t of e)t.error||this._updateLibInt(t);if(Object.entries(this.duplicateMonomers).length>0){const e=await(0,Le.u)();this.assignDuplicatePreferences(e)}else this._duplicatesHandled=!0;this._onChanged.next()}assignDuplicatePreferences(e){let t=!0;for(const n in this.duplicateMonomers)for(const i in this.duplicateMonomers[n])if(e.duplicateMonomerPreferences?.[n]?.[i]){const o=e.duplicateMonomerPreferences[n][i],s=this.duplicateMonomers[n][i].find(e=>e.lib?.source===o);s?this._monomers[n][i]=s:t=!1}else t=!1;return this._duplicatesHandled=t,t}clear(){this._monomers={},this._onChanged.next()}getSummaryObj(){const e={},t=this.getPolymerTypes();for(const n of t)e[n]=this.getMonomerSymbolsByType(n).length;return e}getSummaryDf(){const e=this.getPolymerTypes(),t=new Array(e.length);for(const[n,i]of ee().enumerate(e))t[i]=this.getMonomerSymbolsByType(n).length;return r.DataFrame.fromColumns([r.Column.fromStrings("polymerType",e),r.Column.fromList(r.COLUMN_TYPE.INT,"count",t)])}getSummary(){const e=this.getPolymerTypes();return 0==e.length?"empty":e.map(e=>`${e} ${this.getMonomerSymbolsByType(e).length}`).join("\n")}static overrideCounter=0;override(e,t){return new cn(e,`override: ${++ln.overrideCounter}, ${t}`,this)}}class cn extends sn{data;base;constructor(e,t,n){super(e,t),this.data=e,this.base=n}get onChanged(){return this.base.onChanged}getMonomerSymbolsByType(e){const t=this.base.getMonomerSymbolsByType(e);for(const n of Object.keys(this.data[e]??{}))t.includes(n)||t.push(n);return t}addMissingMonomer(e,t){return this.base.addMissingMonomer(e,t)}getMonomer(e,t){const n=this.data[e]?.[t];return n??this.base.getMonomer(e,t)}}var un=n(8604),hn=n(7433),dn=n.n(hn),mn=n(1913),pn=n.n(mn);class gn{helmMonomerSchema;validateMonomerSchema;constructor(e){this.helmMonomerSchema=e;const t=new(dn())({allErrors:!0,strictTuples:!1,allowUnionTypes:!0});pn()(t),this.validateMonomerSchema=t.compile(this.helmMonomerSchema)}validateFile(e,t){const n=this.parseJson(e,t);return null!=n&&(Array.isArray(n)?this.validateJsonContent(n,t):(console.warn(`Bio: Monomer Library File Validator file '${t}': Invalid JSON format: The file must contain an array of monomers.`),!1))}parseJson(e,t){try{return JSON.parse(e)}catch(e){return console.error(`Bio: Monomer Library File Validator file '${t}': Invalid JSON format:`,e),null}}validateJsonContent(e,t){let n=!0;const i=new Set;for(const o of e){const e=o.symbol??o.id??o.name??"#N/A";if(n=this.validateMonomerSchema(o),!n){console.warn(`Bio: Monomer Library File Validator file ${t}, monomer '${e}' violating JSON schema:`,o,"\nError reason: ",JSON.stringify(this.validateMonomerSchema.errors??{}),`\nThere may be other errors in ${t} since the validation is stopped after the first error.`," Please, verify that the monomer library file satisfies the JSON schema");break}const s=`${o.polymerType??""}-${e}`;i.has(s)&&console.warn(`Bio: Monomer Library File Validator file ${t}, monomer '${e}' is duplicated.`,"Please, verify that the monomer library file does not contain duplicated monomer symbols."),i.add(s)}return n}}class fn{fileValidator;libHelper;logger;get LIB_PATH(){return"System:AppData/Bio/monomer-libraries/"}get SETS_PATH(){return"System:AppData/Bio/monomer-sets/"}static HELM_JSON_SCHEMA_PATH="System:AppData/Bio/tests/libraries/HELMmonomerSchema.json";static _instance=null;filesPromise=Promise.resolve();name=ye.ic;_onChanged=new c.Subject;get onChanged(){return this._onChanged}constructor(e,t,n){this.fileValidator=e,this.libHelper=t,this.logger=n}static async getInstance(e,t){if(null==this._instance){const n=await o.dapi.files.readAsText(fn.HELM_JSON_SCHEMA_PATH),i=JSON.parse(n),s=new gn(i);fn._instance=new fn(s,e,t),fn._instance.refreshLists()}return fn._instance}toLog(){return"MonomerLibFileManager"}async validateAgainstHELM(e,t){if(!this.isValidHELMLibrary(e,t))throw new Error(`File ${t} does not satisfy HELM standard`)}isValidHELMLibrary(e,t){return this.fileValidator.validateFile(e,t)}async refreshLists(){await Promise.all([this.updateValidLibList(),this.updateValidSetList()])}async addOrUpdateLibraryString(e,t){e=e.endsWith(".json")?e:`${e}.json`;try{await this.validateAgainstHELM(t,e),await o.dapi.files.writeAsText(this.LIB_PATH+`${e}`,t),await this.updateValidLibList(),await o.dapi.files.exists(this.LIB_PATH+`${e}`)?o.shell.info(`Added ${e} HELM library`):o.shell.error(`Failed to add ${e} library`)}catch(t){this.logger.error(t),o.shell.error(`Failed to add ${e} library`)}}async addOrUpdateLibrary(e,t){const n=JSON.stringify([...t.map(e=>({...e,wem:void 0,lib:void 0}))],null,2);await this.addOrUpdateLibraryString(e,n)}get loadPromise(){return this.filesPromise}async listLibraries(){return this.validLibList}async listSets(){return this.validSetList}async loadLibraries(e,t=!1){let n=[];e=e.map(e=>e.endsWith(".json")?e:`${e}.json`);const i=t?e:e.map(e=>this.LIB_PATH+e),s=[];for(let e=0;e<i.length;e++){const t={};try{const s=await o.dapi.files.readAsText(i[e]);n=JSON.parse(s),n.forEach(e=>{const n=e.polymerType,i=e.symbol;t[n]||(t[n]={}),t[n][i]=e})}catch(t){this.logger.error(`Failed to load monomer library file: ${i[e]}`),this.logger.error(t);continue}finally{s.push(t)}}return s}async loadSets(e){const t=[],n=this.libHelper.getMonomerLib();for(const i of e){const e=i.endsWith(".json")?i:`${i}.json`,s=this.SETS_PATH+e;try{const e=await o.dapi.files.readAsText(s),i=JSON.parse(e),r=i.description,a=Object.entries(i.placeholders).map(([e,t])=>{const i=e,o=t.polymerType,s=t.monomerType,r=t.set;return new ye.lH(n,i,o,s,r)});t.push(new ye.YS(r,a))}catch(e){this.logger.error(`Failed to load monomer set file: ${s}`),this.logger.error(e);continue}}return t}async deleteLibrary(e){const t=e.endsWith(".json")?e:`${e}.json`;await o.dapi.files.delete(this.LIB_PATH+t),await this.updateValidLibList()}async deleteSet(e){const t=e.endsWith(".json")?e:`${e}.json`;await o.dapi.files.delete(this.SETS_PATH+t),await this.updateValidSetList()}async addOrUpdateSetString(e,t){const n=e.endsWith(".json")?e:`${e}.json`;await o.dapi.files.writeAsText(this.SETS_PATH+n,t),await this.updateValidSetList()}async addOrUpdateSet(e,t){const n=JSON.stringify(t,null,2);await this.addOrUpdateSetString(e,n)}async deleteMonomersFromLibrary(e,t){const n=e.endsWith(".json")?e:`${e}.json`,i=this.LIB_PATH+n,s=await o.dapi.files.readAsText(i);let r=JSON.parse(s);r=r.filter(e=>!t.some(t=>e.polymerType===t.polymerType&&e.symbol===t.symbol));const a=JSON.stringify(r,null,2);await o.dapi.files.writeAsText(i,a),await this.updateValidLibList()}validLibList=[];libListHasChanged(e){const t=this.validLibList;return e.length!==t.length||e.some((e,n)=>e!==t[n])}validSetList=[];setListHasChanged(e){const t=this.validSetList;return e.length!==t.length||e.some((e,n)=>e!==t[n])}async getLibraryAsString(e){const t=e.endsWith(".json")?e:`${e}.json`;return o.dapi.files.readAsText(this.LIB_PATH+t)}async getSingleLibrary(e){return(await this.loadLibraries([e]))?.[0]}async getSingleLibraryWithFullPath(e){return(await this.loadLibraries([e],!0))?.[0]}async updateOrAddMonomersInLibrary(e,t){const n=e.endsWith(".json")?e:`${e}.json`,i=this.LIB_PATH+n,s=await o.dapi.files.readAsText(i),r=JSON.parse(s);for(const e of t){const t=r.findIndex(t=>t.polymerType===e.polymerType&&t.symbol===e.symbol);-1!==t?r[t]={...e,lib:void 0,wem:void 0}:r.push({...e,lib:void 0,wem:void 0})}const a=JSON.stringify(r,null,2);await o.dapi.files.writeAsText(i,a),await this.updateValidLibList()}async updateValidLibList(){const e=`${this.toLog()}.updateValidLibList()`;return this.logger.debug(`${e}, start`),this.filesPromise=this.filesPromise.then(async()=>{this.logger.debug(`${e}, IN`);const t=[],n=await this.getLibFileListAtLocation();if(!this.libListHasChanged(n))return void this.logger.debug(`${e}, end, not changed`);for(const e of n){if(!e.endsWith(".json")){t.push(e);continue}const n=await o.dapi.files.readAsText(this.LIB_PATH+`${e}`);this.isValidHELMLibrary(n,e)||t.push(e)}const i=n.filter(e=>!t.includes(e));if(this.libListHasChanged(i)&&(this.validLibList=i,await this.libHelper.loadMonomerLib(!0)),i.some(e=>!e.endsWith(".json"))&&this.logger.warning(`Wrong validation: ${i}`),t.length>0){const e=`Invalid monomer library files in ${this.LIB_PATH}, consider fixing or removing them: ${t.join(", ")}`;this.logger.warning(e)}this.logger.debug(`${e}, OUT`),this._onChanged.next()}),this.logger.debug(`${e}, end`),this.filesPromise}async updateValidSetList(){const e=`${this.toLog()}.updateValidSetList()`;return this.logger.debug(`${e}, start`),this.filesPromise=this.filesPromise.then(async()=>{this.logger.debug(`${e}, IN`);const t=[],n=await this.getSetFileListAtLocation();if(!this.setListHasChanged(n))return void this.logger.debug(`${e}, end, not changed`);for(const e of n)e.endsWith(".json")||t.push(e);const i=n.filter(e=>!t.includes(e));this.setListHasChanged(i)&&(this.validSetList=i,this.libHelper.loadMonomerSets(!0)),this.logger.debug(`${e}, OUT`),this._onChanged.next()}),this.logger.debug(`${e}, end`),this.filesPromise}async getLibFileListAtLocation(){const e=`${this.toLog()}.getLibFileListAtLocation()`;this.logger.debug(`${e}, start`);const t=await o.dapi.files.list(this.LIB_PATH).then(e=>e.filter(e=>e.isFile).map(e=>e.fullPath)),n=[];return n.push(...t),n.map(e=>e.substring(this.LIB_PATH.length))}async getSetFileListAtLocation(){const e=`${this.toLog()}.getSetFileListAtLocation()`;this.logger.debug(`${e}, start`);const t=await o.dapi.files.list(this.SETS_PATH).then(e=>e.map(e=>e.fullPath)),n=[];return n.push(...t),n.map(e=>e.substring(this.SETS_PATH.length))}}const yn="System:AppData/Bio/monomer-collections/";class bn{logger;_monomerLib=new ln({},"MAIN");_monomerSets=new ye.YS("MAIN",[]);_initialLoadCompleted=!1;get initialLoadCompleted(){return this._initialLoadCompleted}_providersDataChanged=new c.Subject;get providersDataChanged(){return this._providersDataChanged}_fileUploadRequested=new c.Subject;get fileUploadRequested(){return this._fileUploadRequested}requestFileUpload(){this._fileUploadRequested.next()}_selectionChanged=new c.Subject;get librarySelectionChanged(){return this._selectionChanged}notifyLibrarySelectionChanged(){this._selectionChanged.next()}async getAvaliableLibraryNames(e=!1){const t=await this.getProviders(),n=[];for(const i of t){e&&await i.refreshLists();const t=await i.listLibraries();n.push(...t)}return n}async refreshValidLibraryLists(){const e=await this.getProviders();await Promise.all(e.map(async e=>e.refreshLists()))}async getAvailableLibrariesPerProvider(){const e=await this.getProviders(),t=new Map;for(const n of e){const e=await n.listLibraries();t.set(n.name,e)}return t}async awaitLoaded(e=1/0){return e=e===1/0?6e4:e,await Promise.race([(async()=>{const e=await this.getProviders();return await Promise.all(e.map(async e=>e.loadPromise)),await this.loadLibrariesPromise,!0})(),(async()=>(await r.delay(e),!1))()]).then(t=>{if(!t)throw new Error(`Loading monomer libraries timeout ${e} ms.`)})}_monomerLibProviders=null;async getProviders(){if(null==this._monomerLibProviders){const e=r.Func.find({meta:{role:"monomer-lib-provider"}});this._monomerLibProviders=await Promise.all(e.map(async e=>await e.apply({}))),this._monomerLibProviders.push(await fn.getInstance(this,Uo.logger)),r.debounce((0,c.merge)(...this._monomerLibProviders.map(e=>e.onChanged)),200).subscribe(()=>{this._providersDataChanged.next()})}return this._monomerLibProviders}constructor(e){this.logger=e}static objCounter=-1;objId=(()=>{if(++bn.objCounter>0)throw new Error("MonomerLibManager MUST be a singleton.");return bn.objCounter})();toLog(){return`MonomerLibManager<${this.objId}>`}getMonomerLib(){return this._monomerLib}getBioLib(){return this.getMonomerLib()}getMonomerSets(){return this._monomerSets}get duplicateMonomers(){return this._monomerLib.duplicateMonomers}get duplicatesHandled(){return this._monomerLib.duplicatesHandled}assignDuplicatePreferances(e){this._monomerLib.assignDuplicatePreferences(e)}loadLibrariesPromise=Promise.resolve();async loadMonomerLib(e=!1){const t=`${this.toLog()}.loadMonomerLib()`;return this.logger.debug(`${t}, start`),this.loadLibrariesPromise=this.loadLibrariesPromise.then(async()=>{this.logger.debug(`${t}, IN`);const n=r.TaskBarProgressIndicator.create("Loading monomers ...");try{const t=await(0,Le.u)(),i=await this.getProviders(),s=await Promise.all(i.map(async e=>e.listLibraries()));s.forEach((e,n)=>{s[n]=e.filter(e=>{const n=!t.exclude.includes(e),i=0===(t.explicit?.length??0)||t.explicit.includes(e);return n&&i})});let r=0;const a=[];for(let e=0;e<i.length;e++){const t=i[e],l=s[e];try{const e=await t.loadLibraries(l);for(let t=0;t<e.length;t++)a.push(new ln(e[t],l[t]))}catch(e){o.shell.warning(`Loading monomer libraries from provider '${t.name}' failed: `),this.logger.error(`Loading monomer libraries from provider '${t.name}' failed: ${e instanceof Error?e.message:e.toString()}`)}n.update(Math.round(100*++r/i.length),`Loading monomers ${r}/${i.length}`)}this._monomerLib.updateLibs(a,e),this._initialLoadCompleted=!0}catch(e){const t=`Loading monomer libraries error: ${e instanceof Error?e.message:e.toString()}`;o.shell.warning(t);const n=e instanceof Error?e.stack:void 0;this.logger.error(t,void 0,n)}finally{n.close(),this.logger.debug(`${t}, OUT`)}}),this.logger.debug(`${t}, end`),this.loadLibrariesPromise}async loadLibraries(e){return this.loadMonomerLib(e)}loadSetsPromise=Promise.resolve();async loadMonomerSets(e=!1){const t=`${this.toLog()}.loadMonomerSets()`;return this.logger.debug(`${t}, start`),this.loadSetsPromise=this.loadSetsPromise.then(async()=>{this.logger.debug(`${t}, IN`);const e=r.TaskBarProgressIndicator.create("Loading monomer sets ...");try{const t=await this.getProviders(),n=await Promise.all(t.map(async e=>e.listSets())),i=[];let s=0;for(let r=0;r<t.length;r++){const a=t[r],l=n[r];try{const e=await a.loadSets(l);for(let t=0;t<e.length;t++)i.push(e[t])}catch(e){o.shell.warning(`Loading monomer sets from provider '${a.name}' failed: `),this.logger.error(`Loading monomer sets from provider '${a.name}' failed: ${e instanceof Error?e.message:e.toString()}`)}e.update(Math.round(100*++s/t.length),`Loading monomer sets ${s}/${t.length}`)}this._monomerSets.updateSets(i)}catch(e){const t=`Loading monomer sets error: ${e instanceof Error?e.message:e.toString()}`;o.shell.warning(t);const n=e instanceof Error?e.stack:void 0;this.logger.error(t,void 0,n)}finally{e.close(),this.logger.debug(`${t}, OUT`)}}),this.logger.debug(`${t}, end`),this.loadSetsPromise}async loadMonomerLibForTests(){await(0,Le.E)(un.G),await this.awaitLoaded(1e4),await this.loadMonomerLib(!0)}async readSingleLibrary(e,t){const n=(await this.getProviders()).find(t=>t.name===e);if(!n)return this.logger.error(`Provider '${e}' not found.`),null;try{const i=await n.loadLibraries([t]);return 0===i.length?(this.logger.error(`Library '${t}' not found in provider '${e}'.`),null):new ln(i[0],t)}catch(e){return this.logger.error(`Loading monomer library '${t}' from provider '${n.name}' failed: ${e instanceof Error?e.message:e.toString()}`),null}}async readLibraryFromFilePath(e){const t=(await this.getProviders()).find(e=>e.name===ye.ic);if(!t)throw new Error(`Provider '${ye.ic}' not found.`);const n=await t.getSingleLibraryWithFullPath(e);if(!n)throw new Error(`Library at path '${e}' not found.`);return new ln(n,e)}async readSingleLibraryByName(e){const t=await this.getProviders(),n=await(0,ye.pY)(t,e);return n?this.readSingleLibrary(n.name,e):(this.logger.error(`No provider found for library '${e}'.`),null)}async readSingleSet(e,t){const n=(await this.getProviders()).find(t=>t.name===e);if(!n)return this.logger.error(`Provider '${e}' not found.`),null;try{const i=await n.loadSets([t]);return 0===i.length?(this.logger.error(`Set '${t}' not found in provider '${e}'.`),null):i[0]}catch(e){return this.logger.error(`Loading monomer set '${t}' from provider '${n.name}' failed: ${e instanceof Error?e.message:e.toString()}`),null}}async listMonomerCollections(){return(await o.dapi.files.list(yn)).filter(e=>"json"===e.extension||e.name.endsWith(".json")).map(e=>e.name)}async deleteMonomerCollection(e){e.endsWith(".json")||(e+=".json"),await o.dapi.files.exists(yn+e)&&await o.dapi.files.delete(yn+e)}async readMonomerCollection(e){e.endsWith(".json")||(e+=".json");const t=await o.dapi.files.readAsText(yn+e);return JSON.parse(t)}async addOrUpdateMonomerCollection(e,t,n,i){e.endsWith(".json")||(e+=".json");const s=JSON.stringify({description:n,tags:i,monomerSymbols:t,updatedBy:r.User.current().login,updatedOn:(new Date).toISOString()},null,2);await o.dapi.files.writeAsText(yn+e,s)}static async getInstance(){let e=window.$monomerLibHelperPromise;return null==e&&(e=window.$monomerLibHelperPromise=(async()=>new bn(Uo.logger))()),e}}var wn=n(857),vn={};vn.styleTagTransform=C(),vn.setAttributes=y(),vn.insert=g().bind(null,"head"),vn.domAPI=m(),vn.insertStyleElement=w(),h()(wn.A,vn),wn.A&&wn.A.locals&&wn.A.locals;const Cn=[{alternateId:"R1-H",capGroupName:"H",capGroupSmiles:"[*:1][H]",label:"R1"},{alternateId:"R2-OH",capGroupName:"OH",capGroupSmiles:"O[*:2]",label:"R2"},{alternateId:"R3-H",capGroupName:"H",capGroupSmiles:"[*:3][H]",label:"R3"},{alternateId:"R4-H",capGroupName:"H",capGroupSmiles:"[*:4][H]",label:"R4"},{alternateId:"R5-H",capGroupName:"H",capGroupSmiles:"[*:5][H]",label:"R5"},{alternateId:"R6-H",capGroupName:"H",capGroupSmiles:"[*:6][H]",label:"R6"}];function An(e,t,n){let i=t[e]??n[e];if(i&&i.length>0)return i;const s=Fn(e,Cn);if(s!==e){const e=o.chem.convert(s,r.chem.Notation.Unknown,r.chem.Notation.Smiles);if(i=t[e]??n[e],i&&i.length>0)return i}return[]}function Tn(e){const t=new Set;return e.filter(e=>!t.has(e.symbol)&&(t.add(e.symbol),!0))}function En(e,t){const n=new Set;for(const i of e){const e=t[i.symbol];if(e&&e.length>0)for(const t of e){const e=t?.lib?.source;e&&n.add(e)}else i.source&&n.add(i.source)}return Array.from(n).join(", ")}var Sn;!function(e){e.MONOMER="Monomer",e.SYMBOL="Symbol",e.NAME="Name",e.R_GROUPS="~R-Groups",e.MONOMER_TYPE="Monomer Type",e.POLYMER_TYPE="Polymer Type",e.NATURAL_ANALOG="Natural Analog",e.AUTHOR="Author",e.CREATE_DATE="Create Date",e.ID="ID",e.META="Meta",e.SOURCE="Source"}(Sn||(Sn={}));const Mn={[Sn.MONOMER]:r.COLUMN_TYPE.STRING,[Sn.SYMBOL]:r.COLUMN_TYPE.STRING,[Sn.NAME]:r.COLUMN_TYPE.STRING,[Sn.R_GROUPS]:r.COLUMN_TYPE.STRING,[Sn.MONOMER_TYPE]:r.COLUMN_TYPE.STRING,[Sn.POLYMER_TYPE]:r.COLUMN_TYPE.STRING,[Sn.NATURAL_ANALOG]:r.COLUMN_TYPE.STRING,[Sn.AUTHOR]:r.COLUMN_TYPE.STRING,[Sn.CREATE_DATE]:r.COLUMN_TYPE.DATE_TIME,[Sn.ID]:r.COLUMN_TYPE.INT,[Sn.META]:r.COLUMN_TYPE.STRING,[Sn.SOURCE]:r.COLUMN_TYPE.STRING};async function xn(e){const t=await Pn(e);if(e.length!==t.rowCount)throw new Error(`Monomers length ${e.length} does not match dataframe row count ${t.rowCount}`);return await Promise.all(new Array(e.length).fill(null).map(async(e,n)=>kn(t.rows.get(n))))}async function Pn(e){try{const t=r.DataFrame.create(e.length),n=new Set;for(const t of e)t.rgroups.forEach(e=>{e.label&&n.add(e.label)});const i=Array.from(n);i.sort();for(const[e,n]of Object.entries(Mn))if(t.columns.addNew(e,n),e===Sn.R_GROUPS)for(const e of i)t.columns.addNew(e,r.COLUMN_TYPE.STRING);t.col(Sn.SYMBOL).semType="Monomer",t.col(Sn.SYMBOL).setTag(Re.Mn.applyToBackground,"true"),t.col(Sn.SYMBOL).setTag(pe.qE.polymerTypeColumnName,Sn.POLYMER_TYPE);const o=r.TaskBarProgressIndicator.create("Creating Monomers DataFrame...");for(let n=0;n<e.length;n++){n%20==0&&o.update((n+1)/e.length*100,"Creating Monomers DataFrame...");const s=()=>{let o=Hn(e[n].rgroups,e[n].smiles,e[n].molfile);o=In(o),e[n].rgroups=$n(e[n].rgroups);const s=i.map(t=>{const i=e[n].rgroups.find(e=>e.label===t);return i?Nn(i,"capGroupSmiles"):""});let r=null;if(e[n].createDate)try{r=Date.parse(e[n].createDate)}catch(t){console.error(`Error parsing date ${e[n].createDate}`)}t.rows.setValues(n,[o,e[n].symbol,e[n].name,JSON.stringify(e[n].rgroups??[]),...s,e[n].monomerType,e[n].polymerType,e[n].naturalAnalog,e[n].author,r,e[n].id,JSON.stringify(e[n].meta??{}),e[n].lib?.source??""],!1);try{r&&t.col(Sn.CREATE_DATE)?.set(n,r,!1)}catch(t){console.error(`Error setting date ${e[n].createDate}`,t)}};await new Promise(e=>{const t=()=>{try{s(),e()}catch(t){console.error("Error in doFill",t),e()}};n%20==0?setTimeout(()=>{t()}):t()})}return o.close(),t.col(Sn.MONOMER).semType=r.SEMTYPE.MOLECULE,i.forEach(e=>{t.col(e).semType=r.SEMTYPE.MOLECULE}),t}catch(e){throw o.shell.error("Error creating monomers dataframe"),console.error(e),e}}class Ln{monomerLibManamger;adjustTable(){this.tv?.dataFrame&&(o.data.detectSemanticTypes(this.tv.dataFrame),this.tv.dataFrame.meta.detectSemanticTypes()),setTimeout(()=>{this.tv?.grid&&(this.tv.grid.props.allowEdit=!1,this.tv.grid.col(Sn.NAME).width=100,this.tv.grid.col(Sn.SYMBOL).width=70)},200)}static VIEW_NAME="Manage Monomers";_newMonomer=de.pe;_newMonomerForm;monomerLib;tv=null;libInput;static instance;activeMonomerLib=null;constructor(e){this.monomerLibManamger=e,this.monomerLib=e.getBioLib(),this._newMonomerForm=new On(e,()=>this.activeMonomerLib,async e=>{const t=await this.getMonomersDf(this.libInput.value);this.tv?.dataFrame&&(this.tv.dataFrame=t,this.adjustTable(),null!=e&&setTimeout(()=>{const n=t.col(Sn.SYMBOL).toList().indexOf(e);-1!==n&&(this.tv?.grid.scrollToCell(t.columns.byIndex(0),n),t.currentRow=t.rows.get(n))},500))},()=>this.tv?.dataFrame)}static async getInstance(){if(!this.instance){const e=await bn.getInstance();await e.awaitLoaded(),this.instance=new Ln(e)}return this.instance}static async getNewInstance(){const e=await bn.getInstance();return await e.awaitLoaded(),new Ln(e)}async createNewMonomerLib(e,t,n){this.tv?.grid&&s.setUpdateIndicator(this.tv.grid.root,!0);try{const i=(await this.monomerLibManamger.getProviders()).find(t=>t.name===e);if(!i)throw new Error(`Provider ${e} not found`);const s=n.map(e=>({...e,lib:void 0,wem:void 0}));await i.addOrUpdateLibrary(t,s),await this.monomerLibManamger.loadMonomerLib(!1),o.shell.v=await this.getViewRoot(t)}catch(e){o.shell.error("Error creating library"),console.error(e)}finally{this.tv?.grid&&s.setUpdateIndicator(this.tv.grid.root,!1)}}async createNewMonomersCollectionDialog(e){const t=(await this.monomerLibManamger.listMonomerCollections()).map(e=>e.toLowerCase()),n=s.input.string("Collection Name",{tooltipText:"Name of the monomer collection, should be unique",placeholder:"Enter collection name",nullable:!1}),i=s.input.string("Description",{tooltipText:"Description of the monomer collection",placeholder:"Enter collection description",nullable:!0}),r=s.dialog("Create New Monomer Collection").add(n).add(i).addButton("Add",async()=>{if(!n.value||!n.value.trim())return void o.shell.warning("Collection name cannot be empty");const a=async e=>{await this.monomerLibManamger.addOrUpdateMonomerCollection(n.value,e,i.value??void 0),o.shell.info(`Collection ${n.value} saved successfully`)};if(t.includes(n.value.toLowerCase())||t.includes(n.value.toLowerCase()+".json")){const t=s.dialog("Collection already exists").add(s.divText(`A collection with the name ${n.value} already exists. Do you want to merge or overwrite it?`));t.addButton("Merge",async()=>{const i=await this.monomerLibManamger.readMonomerCollection(n.value),s=Array.from(new Set([...i.monomerSymbols??[],...e]));try{await a(s)}catch(e){o.shell.error("Error merging monomer collection"),console.error(e)}t.close()}),t.addButton("Overwrite",async()=>{try{await a(e)}catch(e){o.shell.error("Error overwriting monomer collection"),console.error(e)}t.close()}),t.show()}else try{await a(e)}catch(e){o.shell.error("Error creating monomer collection"),console.error(e)}r.close()}).show()}async createNewLibDialog(e){const t=await this.monomerLibManamger.getAvaliableLibraryNames(),n=s.input.string("Library Name",{placeholder:"Enter library name",nullable:!1,onValueChanged:()=>{const e=i(n.value);l.getButton("Create")?.classList?.toggle("d4-disabled",!!e)}});function i(e){return e&&e.trim()?t.includes(e)||t.includes(e+".json")?"Library with this name already exists":null:"Library name cannot be empty"}n.addValidator(i);const r=(await this.monomerLibManamger.getProviders()).map(e=>e.name),a=s.input.choice("Storage",{items:r,value:r[0],nullable:!1,tooltipText:"Select storage provider for the new library"});1===r.length&&(a.readOnly=!0);const l=s.dialog("Create New Library").add(a).add(n).addButton("Create",async()=>{const t=i(n.value);if(t)o.shell.warning(t);else if(a.value){try{await this.createNewMonomerLib(a.value,n.value,e??[])}catch(e){o.shell.error("Error creating library"),console.error(e)}l.close()}else o.shell.warning("Please select storage provider")}).show();l.getButton("Create")?.classList?.toggle("d4-disabled",!0)}get newMonomer(){return this._newMonomer}getNewMonomerForm(){return this._newMonomerForm}_contextMenuSub=null;async getMonomersTableView(e,t=!0){const n=await this.getMonomersDf(e);return this.tv=r.TableView.create(n,t),this.adjustTable(),this._contextMenuSub?.unsubscribe(),this._contextMenuSub=o.events.onContextMenu.subscribe(({args:e})=>{if(!e||!e.menu||!e.context||e.context.type!==r.VIEWER.GRID||!e.context.tableView||e.context.tableView.id!==(this.tv.id??"")||!e.item||!e.item.isTableCell||(e.item.tableRowIndex??-1)<0)return;const t=e.item.tableRowIndex,n=e.menu;if(n.item("Edit Monomer",async()=>{await this.editMonomer(this.tv.dataFrame.rows.get(t))}),n.item("Fix all monomers",()=>{this.fixAllMonomers()}),this.tv.dataFrame.selection.trueCount>0){const e=n.group("Selected Monomers");e.item("Remove",async()=>{const e=await Promise.all(Array.from(this.tv.dataFrame.selection.getSelectedIndexes()).map(e=>kn(this.tv.dataFrame.rows.get(e))));this._newMonomerForm.removeMonomers(e,this.libInput.value)}),e.item("Create Library",async()=>{const e=await Promise.all(Array.from(this.tv.dataFrame.selection.getSelectedIndexes()).map(e=>kn(this.tv.dataFrame.rows.get(e))));this.createNewLibDialog(e)}),e.item("Create Collection",async()=>{const e=Array.from(this.tv.dataFrame.selection.getSelectedIndexes()).map(e=>this.tv.dataFrame.col(Sn.SYMBOL).get(e)).filter(e=>!!e&&e.trim().length>0);if(0===e.length)return o.shell.warning("No valid monomer symbols found in selection");this.createNewMonomersCollectionDialog(e)})}else n.item("Remove Monomer",async()=>{const e=await kn(this.tv.dataFrame.rows.get(t));this._newMonomerForm.removeMonomers([e],this.libInput.value)})}),this.tv.grid&&(this.tv.grid.props.allowEdit=!1),this.tv}static closeAllMonomerManagers(){Array.from(o.shell.tableViews??[]).filter(e=>e.name===Ln.VIEW_NAME).forEach(e=>e.close())}findActiveManagerView(){if(!this.tv)return null;const e=Array.from(o.shell.tableViews??[]).find(e=>e.id===this.tv.id);return e?o.shell.v=e:Ln.closeAllMonomerManagers(),e??null}_skipLibInputOnchange=!1;async getViewRoot(e,t=!0){const n=await this.monomerLibManamger.getAvaliableLibraryNames();if(this._newMonomerForm.molSketcher.resize(),t&&(this.tv=this.findActiveManagerView())&&(e??this.libInput.value)){try{this._skipLibInputOnchange=!0,this.libInput&&(this.libInput.items=n),e&&(this.libInput.value=e)}catch(e){o.shell.error("Error updating library list"),console.error(e)}finally{this._skipLibInputOnchange=!1}const t=await this.getMonomersDf(e);return this.tv.dataFrame=t,this.adjustTable(),this.tv}e??=n[0],this.tv=await this.getMonomersTableView(e,t);let i=this.tv.getRibbonPanels();i.forEach((e,t)=>{i[t]=e.filter(e=>0!==e.getElementsByClassName("grok-icon-filter").length)}),i=i.filter(e=>e.length>0);const a=s.icons.add(()=>{this._newMonomerForm.setEmptyMonomer()},"Add New Monomer"),l=s.iconFA("wand-magic",()=>{this.fixAllMonomers()},"Fix all monomers"),c=s.icons.edit(async()=>{(this.tv?.dataFrame?.currentRowIdx??-1)<0||await this.editMonomer(this.tv.dataFrame.rows.get(this.tv.dataFrame.currentRowIdx))},"Edit Monomer"),u=s.icons.delete(async()=>{const e=this.tv?.dataFrame?.currentRowIdx??-1,t=Array.from(this.tv?.dataFrame?.selection?.getSelectedIndexes()??[]);if(e<0&&0===t.length)return;if(t.length>0){const e=await Promise.all(t.map(e=>kn(this.tv.dataFrame.rows.get(e))));return void await this._newMonomerForm.removeMonomers(e,this.libInput.value)}const n=await kn(this.tv.dataFrame.rows.get(e));await this._newMonomerForm.removeMonomers([n],this.libInput.value)},"Delete");s.tooltip.bind(u,()=>(this.tv?.dataFrame?.selection?.trueCount??0)>0?"Delete selected monomers":"Delete monomer");const h=async()=>{const e=this.libInput.value;if(!e)return o.shell.error("No library selected");let t=null;try{const n=await(0,ye.pY)(await this.monomerLibManamger.getProviders(),e);if(!n)throw new Error(`Library ${e} not found in any provider`);t=await n.getLibraryAsString(e)}catch(t){return o.shell.error(`Error reading library ${e}`),console.error(t)}if(!t)return o.shell.error(`Library ${e} is empty`);r.Utils.download(e,t,"text/plain")},d=async()=>{const e=this.libInput.value;if(!e)return o.shell.error("No library selected");const t=this.tv?.dataFrame;if(!t)return o.shell.error("No monomer table loaded");const n=t.col(Sn.MONOMER),i=t.col(Sn.R_GROUPS);if(!n||!i)return o.shell.error("Monomer or R-groups column not found");const s=t.clone(t.filter),a=s.col(Sn.MONOMER),l=s.col(Sn.R_GROUPS),c=s.columns.getUnusedName("Capped Molecule"),u=s.columns.addNewString(c);u.semType=r.SEMTYPE.MOLECULE;for(let e=0;e<s.rowCount;e++){const t=a.get(e);if(!t)continue;let n=[];try{const t=l.get(e);n=t?JSON.parse(t):[]}catch(e){n=[]}try{u.set(e,Fn(t,n),!1)}catch(t){console.error(`Error capping monomer at row ${e}`,t)}}const h=s.columns.names(),d=h.indexOf(Sn.MONOMER);if(d>=0){const e=h.filter(e=>e!==c);e.splice(d+1,0,c),s.columns.setOrder(e)}const m=e.toLowerCase().endsWith(".json")?e.replace(/\.json$/i,".csv"):`${e}.csv`;r.Utils.download(m,s.toCsv(),"text/csv")},m=s.iconFA("arrow-to-bottom",()=>{r.Menu.popup().item("JSON",()=>{h()}).item("CSV",()=>{d()}).show()},"Download Monomer Library");i.push([a,c,l,u,m]),this.tv.setRibbonPanels(i),this.tv.name=Ln.VIEW_NAME,this.libInput=s.input.choice("Monomer Library",{value:e,items:n,nullable:!1,onValueChanged:async()=>{try{if(this._skipLibInputOnchange)return;const e=await this.getMonomersDf(this.libInput.value);this.tv.dataFrame=e,this.adjustTable()}catch(e){console.error(e)}}}),this.libInput.addOptions(s.icons.add(()=>{this.createNewLibDialog()},"Create new monomer library..."));const p=this._newMonomerForm.form;return p.prepend(this.libInput.root),s.tools.waitForElementInDom(this.tv.root).then(()=>{this.tv.dockManager.dock(p,r.DOCK_TYPE.LEFT,null,void 0,.4)}),this.tv}async editMonomer(e){return this._newMonomer=await kn(e),this._newMonomerForm.setMonomer(this._newMonomer),this._newMonomer}async getMonomersDf(e){this.tv?.grid&&s.setUpdateIndicator(this.tv.grid.root,!0);try{let t=null;const n=await this.monomerLibManamger.getProviders();if(0===n.length)throw new Error("No monomer library providers available");if(e){if(t=await(0,ye.pY)(n,e),!t)throw new Error(`Library ${e} not found in any provider`)}else t=n[0],e=(await t.listLibraries())[0];if(this.activeMonomerLib=await this.monomerLibManamger.readSingleLibrary(t.name,e),!this.activeMonomerLib)return o.shell.error(`Library ${e} not found`),r.DataFrame.create();const i=this.activeMonomerLib.getPolymerTypes().flatMap(e=>this.activeMonomerLib.getMonomerSymbolsByType(e).map(t=>this.activeMonomerLib.getMonomer(e,t)));return await Pn(i)}catch(e){throw o.shell.error("Error creating monomers dataframe"),console.error(e),e}finally{this.tv?.grid&&s.setUpdateIndicator(this.tv.grid.root,!1)}}async fixAllMonomers(){s.dialog("Fix All Monomers").add(s.divText("This action will fix all monomers in the library, standardize their smiles, molblocks and r-groups, assign correct natural analogs and save the library.")).add(s.divText("Do you wish to continue?")).onOK(async()=>{const e=this.tv?.dataFrame,t=this.libInput.value;if(e&&t){this.tv?.grid&&s.setUpdateIndicator(this.tv.grid.root,!0);try{const n=await(0,ye.pY)(await this.monomerLibManamger.getProviders(),t);if(!n)throw new Error(`Library ${t} not found in any provider`);const i=(await Promise.all(new Array(e.rowCount).fill(0).map((t,n)=>kn(e.rows.get(n))))).map(e=>({...e,lib:void 0,wem:void 0}));await n.addOrUpdateLibrary(t,i),await this.monomerLibManamger.loadMonomerLib(!0),o.shell.v=await this.getViewRoot(t)}catch(e){o.shell.error("Error saving library"),console.error(e)}finally{this.tv?.grid&&s.setUpdateIndicator(this.tv.grid.root,!1)}}else o.shell.error("No monomer library loaded")}).show()}resetCurrentRowFollowing(){this._newMonomerForm.molChanged=!1}}function In(e){let t=e.replaceAll(/\[R[1-9]\]/g,e=>`[*:${e[2]}]`);return t=t.replaceAll(/\[\d\*\]/g,e=>`[*:${e[1]}]`),t.replaceAll(/\[\d\*\:\d\]/g,e=>`[*:${e[1]}]`)}const _n=["alternateId","capGroupName","capGroupSMILES","label"];function Nn(e,t){const n=Object.keys(e).find(e=>e.toLowerCase()===t.toLowerCase());if(n)return e[n]}function Rn(e,t,n){const i=Object.keys(e).find(e=>e.toLowerCase()===t.toLowerCase());i?e[i]=n:e[t]=n}function $n(e){return e.map(e=>{const t=function(e,t){const n={};return e.forEach(e=>{const i=Object.keys(t).find(t=>t.toLowerCase()===e.toLowerCase());i&&(n[e]=t[i])}),n}(_n,e),n=Nn(t,"capGroupSMILES"),i=Nn(t,"alternateId"),o=Nn(t,"capGroupName"),s=Nn(t,"label")??"R1";if(n&&i&&o||s.length<2)return t;if(i&&-1!==i.indexOf(`${s}-`)){const e=i.replace(`${s}-`,"");o||(t.capGroupName=e),n||(t.capGroupSMILES=`[*:${s.substring(1)}][${e}]`)}else o&&(n||(t.capGroupSMILES=`[*:${s.substring(1)}][${o}]`),i||(t.alternateId=`${s}-${o}`));return t}).sort((e,t)=>e.label?.localeCompare(t.label??"")??0)}class On{monomerLibManager;getMonomerLib;refreshTable;getMonomersDataFrame;molSketcher;monomerTypeInput;polymerTypeInput;monomerSymbolInput;monomerNameInput;monomerIdInput;monomerNaturalAnalogInput;rgroupsGrid;metaGrid;colors;colorsEditor;saveButton;rgroupsGridRoot;_molChanged=!1;get molChanged(){return this._molChanged}set molChanged(e){this._molChanged=e}saveValidationResult=null;triggerMolChange=!0;inputsTabControl;constructor(e,t,n,i){this.monomerLibManager=e,this.getMonomerLib=t,this.refreshTable=n,this.getMonomersDataFrame=i,this.colors={line:"#000000",background:"#000000",text:"#000000"},this.colorsEditor=new Gn(this.colors),this.molSketcher=new r.chem.Sketcher,this.molSketcher.root.classList.add("monomer-manager-sketcher"),this.polymerTypeInput=s.input.choice("Polymer Type",{value:"PEPTIDE",items:["PEPTIDE","RNA","CHEM","BLOB","G"],onValueChanged:()=>this.onMonomerInputChanged(),nullable:!1}),this.monomerTypeInput=s.input.choice("Monomer Type",{value:"Backbone",items:["Backbone","Branch","Terminal"],onValueChanged:()=>this.onMonomerInputChanged(),nullable:!1}),this.monomerSymbolInput=s.input.string("Monomer Symbol",{nullable:!1,onValueChanged:()=>this.onMonomerInputChanged()}),this.monomerNameInput=s.input.string("Monomer Name",{nullable:!1,onValueChanged:()=>this.onMonomerInputChanged()}),this.monomerNameInput.nullable=!1,this.monomerIdInput=s.input.int("Monomer ID",{nullable:!0,value:0,onValueChanged:()=>this.onMonomerInputChanged()}),this.monomerNaturalAnalogInput=s.input.string("Natural Analog",{nullable:!0,onValueChanged:()=>this.onMonomerInputChanged()}),this.saveButton=s.bigButton("Save",async()=>{const e=this.validateInputs();e?o.shell.warning(e):await this.saveMonomer()}),this.molSketcher.subs.push(this.molSketcher.onChanged.subscribe(async()=>{if(this.triggerMolChange){try{this.rgroupsGridRoot.style.display="none";const e=this.inputsTabControl.panes.find(e=>"r-groups"===e.name?.toLowerCase());e&&e.header.style.removeProperty("background-color");let t=this.molSketcher.getSmiles();if(!t)return this.rgroupsGrid.items=[],this.rgroupsGrid.render(),this.saveValidationResult="Monomer molecule is required",void this.invalidateSaveButton();t=Hn([],t);const n=this.findRgroupsInSmiles(t);if(0===n.length)return this.rgroupsGrid.items=[],this.rgroupsGrid.render(),this.saveValidationResult="At least one R-group is required",e&&e.header.style.setProperty("background-color","#ff000030"),void this.invalidateSaveButton();if(new Set(n.map(e=>e[0])).size!==n.length)return this.saveValidationResult="Duplicate R-groups are not allowed",this.rgroupsGridRoot.style.display="flex",e&&e.header.style.setProperty("background-color","#ff000030"),void this.invalidateSaveButton();const i=n.map(e=>Number.parseInt(e[0].match(/[1-9]/g)[0])).map(e=>this.rgroupsGrid.items.find(t=>t.label===`R${e}`)??{capGroupSMILES:`[*:${e}][H]`,alternateId:`R${e}-H`,capGroupName:"H",label:`R${e}`});this.rgroupsGrid.items=i.sort((e,t)=>e.label?.localeCompare(t.label??"")??0),this.rgroupsGrid.render(),this.rgroupsGridRoot.style.display="flex";const o=await Lt(Fn(t,i),this.polymerTypeInput.value??"");o&&(this.monomerNaturalAnalogInput.value=o)}catch(e){console.error(e)}this.onMonomerInputChanged(),this._molChanged=!0}else this.triggerMolChange=!0}));const a=[r.Property.js("capGroupSMILES",r.TYPE.STRING,{caption:"R-group SMILES",nullable:!1}),r.Property.js("alternateId",r.TYPE.STRING,{caption:"Alternate ID",nullable:!1}),r.Property.js("capGroupName",r.TYPE.STRING,{caption:"R-group name",nullable:!1}),r.Property.js("label",r.TYPE.STRING,{fieldName:"R-group Label",nullable:!1,userEditable:!1})];this.rgroupsGrid=new Mt(a,[],{allowAdd:!1,allowRemove:!1,validators:{capGroupSMILES:e=>e?o.chem.checkSmiles(e)?null:"Invalid SMILES":"Cap group smiles is required",alternateId:e=>e?null:"Alternate ID is required",capGroupName:e=>e?null:"Cap group name is required",label:e=>e?null:"R-group label is required"},customLabels:{capGroupSMILES:"R-group SMILES",alternateId:"Alternate ID",capGroupName:"Cap Group Name",label:"Label"}}),this.rgroupsGrid.onItemChanged.subscribe(()=>this.onMonomerInputChanged()),this.rgroupsGridRoot=s.divV([this.rgroupsGrid.root]),this.rgroupsGridRoot.style.display="none";const l=[r.Property.js("Property",r.TYPE.STRING,{caption:"Property",nullable:!0}),r.Property.js("Value",r.TYPE.STRING,{caption:"Value",nullable:!0})];this.metaGrid=new Mt(l,[]),this.onMonomerInputChanged();const c=s.divV([this.polymerTypeInput,this.monomerTypeInput,this.monomerSymbolInput,this.monomerNameInput,this.monomerIdInput,this.monomerNaturalAnalogInput]);this.inputsTabControl=s.tabControl({Monomer:c,"R-groups":this.rgroupsGridRoot,Meta:s.divV([this.metaGrid.root]),Colors:this.colorsEditor.form},!1)}invalidateSaveButton(){this.saveValidationResult?this.saveButton.classList.add("d4-disabled"):this.saveButton.classList.remove("d4-disabled")}onMonomerInputChanged(){setTimeout(()=>{this.saveValidationResult=this.validateInputs(),this.invalidateSaveButton();const e=this.polymerTypeInput.value&&this.polymerTypeInput.value&&!!this.getMonomerLib()?.getMonomer(this.polymerTypeInput.value,this.monomerSymbolInput.value);this.saveButton.textContent=e?"Save Monomer":"Add Monomer"},200)}setEmptyMonomer(){this.triggerMolChange=!1,this.molSketcher.setSmiles(""),this.monomerSymbolInput.value="",this.monomerNameInput.value="",this.monomerIdInput.value=null,this.monomerNaturalAnalogInput.value=null,this.rgroupsGrid.items=[],this.metaGrid.items=[],this.rgroupsGrid.render(),this.metaGrid.render(),this.rgroupsGridRoot.style.display="none",this.onMonomerInputChanged(),this.colorsEditor.colors={line:"#000000",background:"#000000",text:"#000000"}}setMonomer(e){this.triggerMolChange=!1,this.molSketcher.setSmiles(e.smiles),this.polymerTypeInput.value=e.polymerType,this.monomerTypeInput.value=e.monomerType,this.monomerSymbolInput.value=e.symbol,this.monomerNameInput.value=e.name,this.monomerIdInput.value=e.id,this.monomerNaturalAnalogInput.value=e.naturalAnalog??null,this.rgroupsGrid.items=$n(e.rgroups),this.metaGrid.items=Object.entries(e.meta??{}).filter(([e,t])=>"colors"!==e?.toLowerCase()).map(([e,t])=>({Property:e,Value:t})),this.rgroupsGrid.render(),this.metaGrid.render(),this.rgroupsGridRoot.style.display="flex",this.onMonomerInputChanged(),!e.naturalAnalog&&e.polymerType&&Lt(Fn(e.smiles,this.rgroupsGrid.items),e.polymerType).then(e=>{e&&(this.monomerNaturalAnalogInput.value=e)});const t=e.meta?.colors??"";let n={};try{n=t?JSON.parse(t)?.default:{}}catch(e){console.error(e)}this.colorsEditor.colors={line:n.line??"#000000",background:n.background??"#000000",text:n.text??"#000000"}}validateInputs(){const e=this.inputsTabControl.panes.find(e=>"r-groups"===e.name?.toLowerCase());if(e&&e.header.style.removeProperty("background-color"),!this.molSketcher.getSmiles())return"Monomer Molecule field is required";for(const e of[this.polymerTypeInput,this.monomerTypeInput,this.monomerSymbolInput,this.monomerNameInput])if(null==e.value||""===e.value)return`${e.caption} field is required`;let t=null;if(this.rgroupsGrid.items.length<1&&(t="At least one R-group is required"),!t)e:for(const e of this.rgroupsGrid.items)for(const[n,i]of Object.entries(e))if(!i){t=`R-group ${n} field is required for ${e.label}`;break e}return!t&&this.rgroupsGrid.hasErrors()&&(t="R-group fields contain errors"),t?(e&&e.header.style.setProperty("background-color","#ff000030"),t):null}findRgroupsInSmiles(e){return[...Array.from(e.matchAll(/\[[1-9]\*\]/g)),...Array.from(e.matchAll(/\[\*\:[1-9]\]/g))]}get form(){this.inputsTabControl.root.classList.add("monomer-manager-form-tab-control"),this.inputsTabControl.header.style.marginBottom="10px";const e=s.buttonsInput([this.saveButton]);return s.tooltip.bind(e,()=>this.saveValidationResult??"Save monomer to library"),s.divV([this.molSketcher.root,this.inputsTabControl.root,e],{classes:"ui-form",style:{paddingLeft:"10px",overflow:"scroll",maxWidth:"unset"}})}get fieldInputs(){return{molecule:this.molSketcher,polymerType:this.polymerTypeInput,monomerType:this.monomerTypeInput,symbol:this.monomerSymbolInput,name:this.monomerNameInput,id:this.monomerIdInput,naturalAnalog:this.monomerNaturalAnalogInput}}get metaInputs(){return[]}get rgroupInputs(){return[]}getMonomerInfoTable(e){const t=Hn(e.rgroups,e.smiles,e.molfile),n=o.chem.drawMolecule(t,150,150),i=s.tableFromMap({name:e.name,author:e.author,createDate:e.createDate});return s.divH([n,i],{style:{alignItems:"center"}})}async removeMonomers(e,t,n=!0){const i=await(0,ye.pY)(await this.monomerLibManager.getProviders(),t);if(!i)return void o.shell.error(`Library ${t} not found in any provider`);const r=s.divV(e.map(e=>this.getMonomerInfoTable(e)),{style:{maxHeight:"500px",overflow:"scroll"}}),a=e.length>1,l=a?`Are you sure you want to remove monomers ${e.map(e=>e.symbol).join(", ")} from ${t} library?`:`Are you sure you want to remove monomer with symbol ${e[0].symbol} from ${t} library?`,c=s.dialog("Remove Monomer"+(a?"s":"")).add(s.h1(l)).add(r).addButton("Remove",async()=>{await i.deleteMonomersFromLibrary(t,e),await this.monomerLibManager.loadMonomerLib(!0),await this.refreshTable(),n&&o.shell.info(`Monomer${a?"s":""} ${e.map(e=>e.symbol).join(", ")} ${a?"were":"was"} successfully removed from ${t} library`),c.close()}).show()}async addMonomerToLib(e,t){const n=this.getMonomersDataFrame();if(!n)return void o.shell.error("No monomer library loaded");const i=n?.col(Sn.POLYMER_TYPE)?.toList()??[],r=n?.col(Sn.SYMBOL)?.toList()??[],a=n?.col(Sn.MONOMER)?.toList()??[];if(i.length!==r.length||i.length!==a.length)return void o.shell.error("Monomer library data frame is corrupted");const l=i.findIndex((t,n)=>t===e.polymerType&&r[n]===e.symbol),c=a.findIndex(t=>t===e.smiles),u=async()=>{try{const n=await(0,ye.pY)(await this.monomerLibManager.getProviders(),t);if(!n)return void o.shell.error(`Library ${t} not found in any provider`);await n.updateOrAddMonomersInLibrary(t,[{...e,lib:void 0,wem:void 0}]),await this.monomerLibManager.loadMonomerLib(!0),await this.refreshTable(e.symbol),this._molChanged=!1,o.shell.info(`Monomer ${e.symbol} was successfully saved in library ${t}`)}catch(e){o.shell.error("Error saving monomer"),console.error(e)}this.onMonomerInputChanged()};let h=null,d="";if(l>=0)h=this.getMonomerInfoTable(await kn(n.row(l))),d=`Monomer with symbol '${e.symbol}' already exists in library ${t}.\nAre you sure you want to overwrite it?`;else if((c??-1)>=0){const e=await kn(this.getMonomersDataFrame().rows.get(c));h=this.getMonomerInfoTable(e),d=`Monomer with the same structure already exists in library ${t} with different symbol (${e.symbol}).\nAre you sure you want to duplicate it?`}if(h){const e=s.dialog("Save Monomer").add(s.divText(d)).add(h).addButton("Save",()=>{e.close(),u()}).show()}else await u()}async saveMonomer(){let e=this.molSketcher.getSmiles();if(!e||!o.chem.checkSmiles(e))return void o.shell.warning("Invalid SMILES");e=Hn([],e);let t=o.chem.convert(e,r.chem.Notation.Smiles,r.chem.Notation.MolBlock);t=Dn(t);const n={};this.metaGrid.items.filter(e=>!!e.Property&&!!e.Value).forEach(e=>{n[e.Property]=e.Value});const i=this.metaGrid.addingItem;i&&i.Property&&i.Value&&(n[i.Property]=i.Value),"#000000"===this.colorsEditor.colors.line&&"#000000"===this.colorsEditor.colors.background&&"#000000"===this.colorsEditor.colors.text||(n.colors={default:this.colorsEditor.colors});const s={symbol:this.monomerSymbolInput.value,name:this.monomerNameInput.value,molfile:t,smiles:e,polymerType:this.polymerTypeInput.value,monomerType:this.monomerTypeInput.value,naturalAnalog:this.monomerNaturalAnalogInput.value?this.monomerNaturalAnalogInput.value:void 0,id:this.monomerIdInput.value??0,rgroups:this.rgroupsGrid.items,author:r.User.current().friendlyName,createDate:(new Date).toISOString(),meta:n},a=this.getMonomerLib()?.source;a?await this.addMonomerToLib(s,a):o.shell.warning("Monomer library source is not specified")}}function Hn(e,t,n){t&&(t=function(e){return e.replaceAll(/\[Allyl\:\d\]/g,e=>`[*:${e[e.length-2]}]`)}(t));const i=!t||!o.chem.checkSmiles(t);if(i&&!n)throw new Error("Both SMILES and MOL block are empty or malformed");let s=i?o.chem.convert(n,r.chem.Notation.Unknown,r.chem.Notation.Smiles):t;return s=function(e,t){let n=e;return t.forEach(e=>{const t=e.label[1]??"1";n=n.replace(`[${e.capGroupName}:${t}]`,`[*:${t}]`)}),n=n.replaceAll(/\[\d[A-Z]{1,2}\]/g,e=>`[*:${e[1]}]`),n}(s,e),s=In(s),i?s:o.chem.convert(s,r.chem.Notation.Unknown,r.chem.Notation.Smiles)}function Dn(e){const t=e.split("\n"),n=t.findIndex(e=>e.startsWith("M")&&e.includes("ISO"));if(-1!==n){const e=t[n].trim().split(" ").filter(Boolean);if(e.length>=5&&Number.parseInt(e[4])<9){const e=t[n].indexOf("ISO");t[n]=t[n].substring(0,e)+"RGP"+t[n].substring(e+3)}}const i=t.findIndex(e=>e.includes("V2000"));if(-1===i)return console.error("Mol start line not found"),e;const o=Number.parseInt(t[i].trim().split(" ")[0].slice(0,3).trim()),s={};for(let e=i+1;e<i+1+o;e++){const n=t[e].indexOf("R ");if(-1===n)continue;"#"!==t[e][n+1]&&(t[e]=t[e].replace("R ","R#"));const o=t[e].trim().split(" ").map(e=>e.trim()).filter(Boolean);if(s[e-i]=1,o.length<14)continue;const r=Number.parseInt(o[13]);Number.isNaN(r)||(s[e-i]=r)}const r=Object.keys(s);if(-1===t.findIndex(e=>e.startsWith("M")&&e.includes("RGP"))){const e=`M RGP${r.length.toString().padStart(3," ")}${Object.entries(s).map(([e,t])=>`${e.toString().padStart(4," ")}${t.toString().padStart(4," ")}`).join("")}`,n=t.findIndex(e=>e.startsWith("M")&&e.includes("END"));t.splice(n,0,e)}return r.filter(e=>!!Number.parseInt(e)).map(e=>Number.parseInt(e)+i).forEach(e=>{const n=t[e].split(" "),i=n.findIndex(e=>"R#"===e);if(-1!==i){for(let e=i+1;e<n.length;e++)n[e]&&1==n[e].length&&(Number.parseInt(n[e])??0)>0&&(n[e]="0");t[e]=n.join(" ")}}),t.join("\n")}function Fn(e,t){let n=e;return t.forEach((e,t)=>{const i=e.label[1]??`${t+1}`,o=Nn(e,"capGroupName"),s=Nn(e,"capGroupSMILES");n="allyl"===o?.toLowerCase()||"c=c"===s?.replace(`[*:${i}]`,"")?.toLowerCase()||"[c=c]"===s?.replace(`[*:${i}]`,"")?.toLowerCase()?n.replace(`[*:${i}]`,"C=C"):n.replace(`[*:${i}]`,`[${o}]`)}),n}async function kn(e){let t;try{t=JSON.parse(e.get(Sn.META)??"{}");for(const e in t)"object"==typeof t[e]&&(t[e]=JSON.stringify(t[e])),("string"!=typeof t[e]||t[e]!==r.INT_NULL.toString()&&t[e]!==r.FLOAT_NULL.toString())&&("number"!=typeof t[e]||t[e]!==r.INT_NULL&&t[e]!==r.FLOAT_NULL)||(t[e]=null)}catch(e){console.error(e)}const n=e.get(Sn.MONOMER);if(!n)throw new Error("Monomer SMILES is empty");let i="";try{i=o.chem.convert(n,r.chem.Notation.Smiles,r.chem.Notation.MolBlock),i=Dn(i)}catch(e){o.shell.error(`Error converting SMILES to molfile, \n ${n}`),console.error(e)}let s=e.get(Sn.NATURAL_ANALOG);const a=e.get(Sn.POLYMER_TYPE);let l=[];try{l=JSON.parse(e.get(Sn.R_GROUPS)??"[]")}catch(e){l??=[]}!function(e){function t(e,t){return e.replace(/\[([A-Z][a-z]?):(\d+)\]/g,(e,n,i)=>parseInt(i)===t?`${n?.toLowerCase&&"h"===n?.toLowerCase()?"[H]":n}[*:${i}]`:e)}e.forEach((e,n)=>{const i=Nn(e,"capGroupSMILES"),o=e.label[1]??`${n+1}`;if(!i||i.includes(`[*:${o}]`))return;const s=new RegExp(`\\[[A-Za-z]{1,2}:${o}\\]`);i.includes(`[*${o}]`)?Rn(e,"capGroupSMILES",i.replace(`[*${o}]`,`[*:${o}]`)):i.includes(`[R${o}]`)?Rn(e,"capGroupSMILES",i.replace(`[R${o}]`,`[*:${o}]`)):s.test(i)?Rn(e,"capGroupSMILES",t(i,Number.parseInt(o))):`[${i}]`.match(s)?.[0].length===i.length+2&&Rn(e,"capGroupSMILES",t(`[${i}]`,Number.parseInt(o)))}),e.forEach(e=>{const t=Nn(e,"capGroupSMILES"),n=t.match(/\[\*\:?(\d+)\]/);n&&t===n[0]&&Rn(e,"capGroupSMILES",`${Nn(e,"capGroupName")}${t}`)})}(l);try{if(!s&&a){const e=await Lt(Fn(n,l),a);e&&(s=e)}}catch(e){console.error(e)}return{symbol:e.get(Sn.SYMBOL),name:e.get(Sn.NAME),molfile:i,smiles:n,polymerType:a,monomerType:e.get(Sn.MONOMER_TYPE),naturalAnalog:s,id:e.get(Sn.ID),rgroups:l,meta:t,author:e.get(Sn.AUTHOR),createDate:e.get(Sn.CREATE_DATE)}}class Gn{_colors;_colorInputs;constructor(e){this._colors=e,this._colorInputs={line:s.input.color("Line",{value:e.line,onValueChanged:e=>this._colors.line=e}),background:s.input.color("Background",{value:e.background,onValueChanged:e=>this._colors.background=e}),text:s.input.color("Text",{value:e.text,onValueChanged:e=>this._colors.text=e})}}get colors(){return this._colors}set colors(e){const t={line:r.Color.toHtml(r.Color.fromHtml(e.line??"#000000")),background:r.Color.toHtml(r.Color.fromHtml(e.background??"#000000")),text:r.Color.toHtml(r.Color.fromHtml(e.text??"#000000"))};this._colors=t;for(const e in this._colorInputs)this._colorInputs[e].value=t[e]}get colorsMetaFormat(){return{colors:{default:this._colors}}}get form(){return s.form(Object.values(this._colorInputs))}}function Bn(e){const t={Symbol:e.symbol,Name:e.name,"Polymer Type":e.polymerType,"Monomer Type":e.monomerType};if(e.author&&(t.Author=e.author),e.naturalAnalog&&(t["Natural Analog"]=e.naturalAnalog),e.lib?.source){let n=e.lib.source;n.endsWith(".json")&&(n=n.substring(0,n.length-5)),t.Library=n}e.molfile?t.Structure=o.chem.drawMolecule(e.molfile,150,150):e.smiles&&(t.Structure=o.chem.drawMolecule(e.smiles,150,150));const n=e.rgroups;if(n&&n.length>0)for(const e of n)t[e.label??"?"]=e.alternateId??"";return s.tableFromMap(t)}function Vn(e){const t=function(e){try{return Fn(Hn(e.rgroups,e.smiles,e.molfile),e.rgroups)}catch{}return null}(e);if(!t)return s.divText("No molecular structure available");const n=r.SemanticValue.fromValueType(t,r.SEMTYPE.MOLECULE);return s.panels.infoPanel(n).root}var Un=n(3890),qn=n(1687);function Wn(e){return e.split(/,(?![^(]*\))/).map(e=>('"'===(e=e.trim()).slice(0,1)&&'"'===e.slice(-1)&&(e=e.slice(1,-1)),"'"===e.slice(0,1)&&"'"===e.slice(-1)&&(e=e.slice(1,-1)),e.trim())).filter(e=>!!e)}class Yn{constructor(e,t,n,i){this.currentMenu=null,this.menuItems=[],this.highlightedIndex=-1,this.monomerLib=e,this.polymerType=t,this.helmType=(0,Oe.MD)(t),this.allSymbols=e.getMonomerSymbolsByType(t),this.libHelper=i,this.selectedMonomers=n?[...n]:[],this.tagsHost=s.div([],{style:{display:"flex",flexWrap:"wrap",gap:"4px",marginTop:"4px",maxHeight:"150px",overflowY:"auto"}}),this.countLabel=s.divText("",{style:{fontSize:"11px",color:"var(--grey-4)",marginTop:"4px"}});const o=s.input.string("Search",{value:""});this.inputEl=o.input,this.inputEl.setAttribute("autocomplete","off"),this.inputEl.placeholder="Type to search monomers...",this.setupInputListeners();const r=this.createLibrarySection(),a=this.createCollectionSection(),l=s.button("Clear all",()=>{this.selectedMonomers.length=0,this.renderTags()});l.style.fontSize="11px",l.style.marginTop="4px",this.renderTags(),this.root=s.div([o.root,r,a,s.divH([this.countLabel,l],{style:{justifyContent:"space-between",alignItems:"center"}}),this.tagsHost],{style:{minWidth:"300px"}})}getSelectedMonomers(){return[...this.selectedMonomers]}setSelectedMonomers(e){this.selectedMonomers.length=0,this.selectedMonomers.push(...e),this.renderTags()}setPolymerType(e){this.polymerType=e,this.helmType=(0,Oe.MD)(e),this.allSymbols=this.monomerLib.getMonomerSymbolsByType(e)}focus(){this.inputEl.focus()}updateCountLabel(){this.countLabel.textContent=this.selectedMonomers.length>0?`${this.selectedMonomers.length} monomer(s) selected`:""}renderTags(){this.tagsHost.innerHTML="";for(const e of this.selectedMonomers){const t=s.iconFA("times",()=>{const t=this.selectedMonomers.indexOf(e);t>=0&&(this.selectedMonomers.splice(t,1),this.renderTags(),this.updateCountLabel())},"Remove");t.style.marginLeft="4px",t.style.cursor="pointer";const n=s.div([s.span([e]),t],{style:{display:"inline-flex",alignItems:"center",padding:"2px 6px",borderRadius:"4px",backgroundColor:"var(--grey-2)",border:"1px solid var(--grey-3)",fontSize:"12px",cursor:"default"}});n.addEventListener("mouseenter",()=>{const t=this.monomerLib.getTooltip(this.helmType,e);s.tooltip.show(t,n.getBoundingClientRect().left,n.getBoundingClientRect().bottom+16)}),n.addEventListener("mouseleave",()=>{s.tooltip.hide()}),this.tagsHost.appendChild(n)}this.updateCountLabel()}addMonomer(e){this.selectedMonomers.includes(e)||(this.selectedMonomers.push(e),this.renderTags()),this.inputEl.value="",this.hideMenu(),this.inputEl.focus()}addMonomers(e){let t=!1;for(const n of e)this.selectedMonomers.includes(n)||(this.selectedMonomers.push(n),t=!0);t&&this.renderTags()}hideMenu(){this.currentMenu&&(this.currentMenu.hide(),this.currentMenu=null),this.menuItems=[],this.highlightedIndex=-1}getSuggestions(e){const t=e.toLowerCase(),n=[];for(const e of this.allSymbols){if(this.selectedMonomers.includes(e))continue;const i=this.monomerLib.getMonomer(this.polymerType,e),o=e.toLowerCase(),s=i?.name?.toLowerCase()??"";o.startsWith(t)?n.push({symbol:e,monomer:i,rank:0}):o.includes(t)?n.push({symbol:e,monomer:i,rank:1}):s.includes(t)&&n.push({symbol:e,monomer:i,rank:2})}return n.sort((e,t)=>e.rank-t.rank||e.symbol.localeCompare(t.symbol)),n.slice(0,20)}showSuggestions(){this.hideMenu();const e=this.inputEl.value.trim();if(!e)return;const t=this.getSuggestions(e);if(0===t.length)return;this.currentMenu=r.Menu.popup();const n=t.reduce((e,t)=>{const n=t.monomer?.name?`${t.symbol} - ${t.monomer.name}`:t.symbol;return e.length<n.length?n:e},"");this.currentMenu.item(n,()=>{});const i=new MouseEvent("mousemove",{clientX:this.inputEl.getBoundingClientRect().left,clientY:this.inputEl.getBoundingClientRect().bottom});this.currentMenu.show({causedBy:i,y:this.inputEl.offsetHeight+this.inputEl.offsetTop,x:this.inputEl.offsetLeft}),setTimeout(()=>{this.currentMenu?.clear();for(const e of t){const t=e.monomer?.name?`${e.symbol} - ${e.monomer.name}`:e.symbol;this.currentMenu?.item(t,()=>{this.addMonomer(e.symbol)})}const e=document.querySelector(".d4-menu-popup:last-of-type");e&&(this.menuItems=Array.from(e.querySelectorAll(".d4-menu-item"))),this.highlightedIndex=-1},0)}updateHighlight(e){0!==this.menuItems.length&&(this.highlightedIndex>=0&&this.highlightedIndex<this.menuItems.length&&this.menuItems[this.highlightedIndex].classList.remove("d4-menu-item-hover"),this.highlightedIndex=e,this.highlightedIndex>=0&&this.highlightedIndex<this.menuItems.length&&(this.menuItems[this.highlightedIndex].classList.add("d4-menu-item-hover"),this.menuItems[this.highlightedIndex].scrollIntoView({block:"nearest"})))}setupInputListeners(){this.inputEl.addEventListener("input",()=>{this.showSuggestions()}),this.inputEl.addEventListener("paste",e=>{const t=e.clipboardData?.getData("text");if(!t)return;const n=t.split(/[\n\r]+/).map(e=>e.trim()).filter(e=>e.length>0),i=[];for(const e of n){const t=Wn(e);1===t.length&&e.includes(" ")&&!e.includes(",")?i.push(...e.split(/\s+/).map(e=>e.trim()).filter(e=>e.length>0)):i.push(...t)}if(!(i.length<=1)){e.preventDefault();for(const e of i)this.selectedMonomers.includes(e)||this.selectedMonomers.push(e);this.renderTags(),this.inputEl.value="",this.hideMenu(),this.inputEl.focus()}}),this.inputEl.addEventListener("keydown",e=>{if("ArrowDown"===e.key){if(e.preventDefault(),this.menuItems.length>0){const e=(this.highlightedIndex+1)%this.menuItems.length;this.updateHighlight(e)}}else if("ArrowUp"===e.key){if(e.preventDefault(),this.menuItems.length>0){const e=(this.highlightedIndex-1+this.menuItems.length)%this.menuItems.length;this.updateHighlight(e)}}else if("Enter"===e.key)if(e.preventDefault(),e.stopPropagation(),this.highlightedIndex>=0&&this.highlightedIndex<this.menuItems.length)this.menuItems[this.highlightedIndex].click();else{const e=this.inputEl.value.trim();e&&this.addMonomer(e)}else"Escape"===e.key&&this.hideMenu()})}createLibrarySection(){const e=s.div([],{style:{marginTop:"8px"}});if(!this.libHelper)return e;const t=this.libHelper,n=s.input.choice("Add from library",{items:[],nullable:!0}),i=s.divText("",{style:{fontSize:"11px",color:"var(--green-2)",marginLeft:"8px",minHeight:"16px"}});return t.getAvaliableLibraryNames().then(e=>{n.items=e}),n.onChanged.subscribe(async()=>{const e=n.value;if(e){i.textContent="Loading...";try{const n=await t.readSingleLibraryByName(e);if(n){const t=n.getMonomerSymbolsByType(this.polymerType),o=this.selectedMonomers.length;this.addMonomers(t);const s=this.selectedMonomers.length-o;i.textContent=`Added ${s} monomer(s) from "${e}"`}else i.textContent=`Library "${e}" not found`}catch(e){i.textContent="Error loading library"}n.value=null,setTimeout(()=>{i.textContent=""},4e3)}}),e.appendChild(s.divV([n.root,i])),e}createCollectionSection(){const e=s.div([],{style:{marginTop:"4px"}});if(!this.libHelper)return e;const t=this.libHelper,n=s.input.choice("Add from collection",{items:[],nullable:!0}),i=s.divText("",{style:{fontSize:"11px",color:"var(--green-2)",marginLeft:"8px",minHeight:"16px"}});return t.listMonomerCollections().then(e=>{n.items=e}),n.onChanged.subscribe(async()=>{const e=n.value;if(e){i.textContent="Loading...";try{const n=(await t.readMonomerCollection(e)).monomerSymbols??[],o=this.selectedMonomers.length;this.addMonomers(n);const s=this.selectedMonomers.length-o,r=e.replace(/\.json$/,"");i.textContent=`Added ${s} monomer(s) from "${r}"`}catch(e){i.textContent="Error loading collection"}n.value=null,setTimeout(()=>{i.textContent=""},4e3)}}),e.appendChild(s.divV([n.root,i])),e}}class jn extends r.ObjectHandler{get type(){return"MonomerCollection"}get name(){return"Monomer Collection"}isApplicable(e){return Array.isArray(e)?e.length>0&&e.every(e=>this.isSingleCollection(e)):this.isSingleCollection(e)}isSingleCollection(e){return null!=e&&"object"==typeof e&&"name"in e&&"displayName"in e&&"data"in e&&void 0!==e.data?.monomerSymbols}getCaption(e){return Array.isArray(e)?`${e.length} collections`:e.displayName}renderProperties(e,t=null){return Array.isArray(e)?this.renderMultiProperties(e):this.renderSingleProperties(e)}renderSingleProperties(e){const t=s.accordion("Monomer Collection"),n=r.User.current().login,i=e.data.updatedBy===n;return t.addPane("Details",()=>{const t={Name:e.displayName};if(e.data.description&&(t.Description=e.data.description),e.data.tags&&e.data.tags.length>0&&(t.Tags=e.data.tags.join(", ")),t.Monomers=`${e.data.monomerSymbols.length}`,e.data.updatedBy&&(t["Updated by"]=e.data.updatedBy),e.data.updatedOn)try{t["Updated on"]=new Date(e.data.updatedOn).toLocaleString()}catch{}return s.tableFromMap(t)},!0),t.addPane("Monomers",()=>{const t=s.div([],{style:{display:"flex",flexWrap:"wrap",gap:"4px"}}),n=this.getMonomerLib();for(const i of e.data.monomerSymbols){const e=s.div([i],{style:{display:"inline-block",padding:"2px 8px",borderRadius:"4px",background:"var(--grey-1)",border:"1px solid var(--grey-2)",fontSize:"11px",color:"var(--grey-5)",cursor:"pointer"}});e.addEventListener("mouseenter",()=>{if(n){const t=jn.getMonomerTooltipSafe(n,i);if(t){const n=e.getBoundingClientRect();s.tooltip.show(t,n.left,n.bottom+4)}}}),e.addEventListener("mouseleave",()=>s.tooltip.hide()),e.addEventListener("click",()=>{o.shell.o=r.SemanticValue.fromValueType(i,Ve.uF.MONOMER)}),t.appendChild(e)}return t},!0),t.addPane("Actions",()=>{const t=[],n=s.button("Edit",async()=>{i&&await this.editCollection(e)},i?"Edit this collection":"Only the author can edit");i||jn.disableButton(n),t.push(n);const o=s.button("Delete",async()=>{i&&await this.deleteCollection(e)},i?"Delete this collection":"Only the author can delete");return i||jn.disableButton(o),t.push(o),t.push(s.button("Duplicate",async()=>{await this.duplicateCollection(e)},"Create a copy of this collection")),s.divH(t)},!0),t.root}renderMultiProperties(e){const t=s.accordion("Monomer Collections"),n=r.User.current().login,i=e.every(e=>e.data.updatedBy===n);return t.addPane("Selection",()=>{const t=s.list(e.map(e=>e.displayName));return s.divV([s.divText(`${e.length} collections selected`),t])},!0),t.addPane("Actions",()=>{const t=[];t.push(s.button("Merge",async()=>{await this.mergeCollections(e)},"Merge selected collections into one"));const n=s.button("Delete All",async()=>{i&&await this.deleteMultipleCollections(e)},i?"Delete all selected collections":"Only the author can delete (you must be author of all)");return i||jn.disableButton(n),t.push(n),s.divH(t)},!0),t.root}async editCollection(e){const t=Array.from(o.shell.views).find(e=>"Monomer Collections"===e.name);if(t&&t._mcView)t._mcView.editCollectionPublic(e.name,e.data);else{const t=await bn.getInstance();await t.awaitLoaded();const n=t.getMonomerLib();this.showEditDialog(e,t,n)}}showEditDialog(e,t,n){const i=s.input.string("Name",{value:e.displayName,nullable:!1}),r=s.input.string("Description",{value:e.data.description??"",nullable:!0}),a=s.input.string("Tags",{value:(e.data.tags??[]).join(", "),nullable:!0,placeholder:"Comma-separated tags"}),l=s.input.choice("Polymer Type",{items:["PEPTIDE","RNA","CHEM"],value:"PEPTIDE",nullable:!1}),c=new Yn(n,l.value,[...e.data.monomerSymbols??[]],t);l.onChanged.subscribe(()=>c.setPolymerType(l.value)),s.dialog({title:`Edit Collection: ${e.displayName}`}).add(s.divV([i,r,a,l,s.element("hr"),c.root])).onOK(async()=>{const n=i.value?.trim();if(!n)return void o.shell.warning("Collection name is required");const s=c.getSelectedMonomers();if(0===s.length)return void o.shell.warning("Please select at least one monomer");const l=this.parseTags(a.value);try{n!==e.displayName&&await t.deleteMonomerCollection(e.name),await t.addOrUpdateMonomerCollection(n,s,r.value??void 0,l.length>0?l:void 0),o.shell.info(`Collection "${n}" saved successfully`),await this.refreshView()}catch(e){o.shell.error("Error saving collection")}}).show({resizable:!0}).root.style.width="550px",c.focus()}async deleteCollection(e){s.dialog({title:"Delete Collection"}).add(s.divText(`Are you sure you want to delete "${e.displayName}"?`)).onOK(async()=>{try{const t=await bn.getInstance();await t.deleteMonomerCollection(e.name),o.shell.info(`Collection "${e.displayName}" deleted`),await this.refreshView()}catch(e){o.shell.error("Error deleting collection")}}).show()}async duplicateCollection(e){const t=s.input.string("New Name",{value:`${e.displayName} (copy)`,nullable:!1});s.dialog({title:"Duplicate Collection"}).add(t).onOK(async()=>{const n=t.value?.trim();if(n)try{const t=await bn.getInstance();await t.addOrUpdateMonomerCollection(n,[...e.data.monomerSymbols],e.data.description,e.data.tags?[...e.data.tags]:void 0),o.shell.info(`Collection "${n}" created`),await this.refreshView()}catch(e){o.shell.error("Error duplicating collection")}else o.shell.warning("Name is required")}).show()}async mergeCollections(e){const t=s.input.string("Merged Name",{value:"Merged Collection",nullable:!1}),n=s.input.string("Description",{nullable:!0,placeholder:"Optional description"});s.dialog({title:`Merge ${e.length} Collections`}).add(s.divV([s.divText(`Merging: ${e.map(e=>e.displayName).join(", ")}`),t,n])).onOK(async()=>{const i=t.value?.trim();if(i)try{const t=[...new Set(e.flatMap(e=>e.data.monomerSymbols))],s=[...new Set(e.flatMap(e=>e.data.tags??[]))],r=await bn.getInstance();await r.addOrUpdateMonomerCollection(i,t,n.value??void 0,s.length>0?s:void 0),o.shell.info(`Merged collection "${i}" created with ${t.length} monomers`),await this.refreshView()}catch(e){o.shell.error("Error merging collections")}else o.shell.warning("Name is required")}).show()}async deleteMultipleCollections(e){s.dialog({title:"Delete Collections"}).add(s.divText(`Are you sure you want to delete ${e.length} collections?\n${e.map(e=>e.displayName).join(", ")}`)).onOK(async()=>{try{const t=await bn.getInstance();for(const n of e)await t.deleteMonomerCollection(n.name);o.shell.info(`${e.length} collections deleted`),await this.refreshView()}catch(e){o.shell.error("Error deleting collections")}}).show()}async refreshView(){const e=Array.from(o.shell.views).find(e=>"Monomer Collections"===e.name);if(e&&e._mcView){const t=e._mcView;await t.refresh()}}parseTags(e){return e?e.split(",").map(e=>e.trim()).filter(e=>e.length>0):[]}getMonomerLib(){return Uo.monomerLib??null}static getMonomerTooltipSafe(e,t){const n=[Fe.o.AA,Fe.o.NUCLEOTIDE,Fe.o.CHEM,Fe.o.BLOB];for(const i of n)try{if(e.getWebEditorMonomer(i,t))return e.getTooltip(i,t)}catch{}return null}static disableButton(e){e.style.opacity="0.4",e.style.cursor="default"}static buildContextMenu(e,t,n){const i=r.User.current().login,o=t.data.updatedBy===i;e.item("Edit",()=>{o&&n.editCollection(t)},null,{isEnabled:()=>o?null:"Only the author can edit"}),e.item("Delete",()=>{o&&n.deleteCollection(t)},null,{isEnabled:()=>o?null:"Only the author can delete"}),e.item("Duplicate",()=>n.duplicateCollection(t))}static buildMultiContextMenu(e,t,n){const i=r.User.current().login,o=t.every(e=>e.data.updatedBy===i);e.item("Merge",()=>n.mergeCollections(t)),e.item("Delete All",()=>{o&&n.deleteMultipleCollections(t)},null,{isEnabled:()=>o?null:"Only the author can delete (you must be author of all)"})}}var Kn=n(1757),zn=n.n(Kn);class Zn{monomer;root=s.divV([],{classes:"monomer-card-root"});_selected=!1;get selected(){return this._selected}set selected(e){this._selected=e,this.root.style.border=e?"2px solid var(--green-2)":"2px solid var(--grey-2)"}constructor(e){this.monomer=e}render(){s.empty(this.root);const e=this.monomer.smiles&&o.chem.checkSmiles(this.monomer.smiles)?o.chem.drawMolecule(this.monomer.smiles,200,200):o.chem.drawMolecule(this.monomer.molfile??"",200,200);this.root.appendChild(e);const t=s.divH([s.divText("Monomer Name: "),s.divText(this.monomer.name)],{classes:"monomer-card-info-row"});if(this.root.appendChild(t),s.tooltip.bind(t,this.monomer.name),this.monomer.lib?.source){const e=s.divH([s.divText("Source: "),s.divText(this.monomer.lib.source)],{classes:"monomer-card-info-row"});this.root.appendChild(e),s.tooltip.bind(e,this.monomer.lib.source)}const n=s.divH([s.divText("Polymer Type: "),s.divText(this.monomer.polymerType)],{classes:"monomer-card-info-row"});this.root.appendChild(n),s.tooltip.bind(n,this.monomer.polymerType),s.tooltip.bind(this.root,"Select Monomer")}}class Xn{monomerSymbol;monomers;root=s.divH([],{style:{alignItems:"center",width:"100%",overflow:"hidden",visibility:"visible"},classes:"duplicate-monomer-symbol-row"});monomerCards;constructor(e,t,n,i){this.monomerSymbol=e,this.monomers=t,this.monomerCards=t.map(e=>new Zn(e));const o=s.divH([],{style:{overflowX:"auto",width:"100%"}}),r=s.h1(e,{style:{lineHeight:"2em",fontSize:"1.5em",marginRight:"20px",width:"100px",overflow:"hidden",textOverflow:"elipsis"}});s.tooltip.bind(r,e),this.root.appendChild(r),this.root.appendChild(o),this.monomerCards.forEach(e=>{e.root.onclick=()=>{this.monomerCards.forEach(e=>e.selected=!1),e.selected=!0,i(e.monomer)},n&&e.monomer===n&&(e.selected=!0),o.appendChild(e.root)})}render(){this.monomerCards.forEach(e=>e.render())}}class Qn{monomerCardRows=[];saveSettingsPromise=Promise.resolve();searchInput;_root;monomers;settings;filteredMonomerRows=[];static _instance;vv;static async getInstance(){return Qn._instance||(Qn._instance=new Qn,await Qn._instance.refresh(),(await bn.getInstance()).getMonomerLib().onChanged.subscribe(async()=>await Qn._instance.refresh())),Qn._instance.refresh(),Qn._instance}async refresh(){this.settings=await(0,Le.u)();const e=await bn.getInstance();await e.awaitLoaded(),this.monomers=e.duplicateMonomers,this.monomerCardRows=[];for(const t in this.monomers)for(const n in this.monomers[t]){const i=this.settings.duplicateMonomerPreferences?.[t]?.[n]??null,s=i?this.monomers[t][n].find(e=>e.lib?.source===i)??null:null;this.monomerCardRows.push(new Xn(n,this.monomers[t][n],s,async i=>{this.saveSettingsPromise=this.saveSettingsPromise.then(async()=>{i.lib?.source&&(this.settings.duplicateMonomerPreferences=this.settings.duplicateMonomerPreferences??{},this.settings.duplicateMonomerPreferences[t]=this.settings.duplicateMonomerPreferences[t]??{},this.settings.duplicateMonomerPreferences[t][n]=i.lib.source,await(0,Le.E)(this.settings),e.assignDuplicatePreferances(this.settings),o.shell.info(`Monomer '${i.name}' from source '${i.lib.source}' selected for symbol '${n}'.`))})}))}const t=s.divText("Set Default");if(t.addEventListener("click",async()=>{if(0===Object.keys(this.monomers??{}).length)return void o.shell.info("No Duplicate Monomers found");const t=new Set;for(const e in this.monomers)for(const n in this.monomers[e])for(const i of this.monomers[e][n])i.lib?.source&&t.add(i.lib.source);if(0===t.size)return void o.shell.info("No Duplicate Monomers found");const n=Array.from(t),i=s.input.choice("Default Library",{items:n,nullable:!0});s.dialog("Set Default Monomer Source for Duplicates").add(i).onOK(async()=>{if(i.value){for(const e in this.monomers)for(const t in this.monomers[e]){const n=this.monomers[e][t];n?.some(e=>e.lib?.source===i.value)&&(this.settings.duplicateMonomerPreferences=this.settings.duplicateMonomerPreferences??{},this.settings.duplicateMonomerPreferences[e]=this.settings.duplicateMonomerPreferences[e]??{},this.settings.duplicateMonomerPreferences[e][t]=i.value)}await(0,Le.E)(this.settings),e.assignDuplicatePreferances(this.settings),o.shell.info(`Default Monomer Source for Duplicates set to '${i.value}'.`),setTimeout(()=>this.refresh(),100)}else o.shell.info("No library selected")}).show()}),this.filteredMonomerRows=this.monomerCardRows,this.vv)this.vv.setData(this.filteredMonomerRows.length,e=>(this.filteredMonomerRows[e].render(),this.filteredMonomerRows[e].root));else{this.vv=s.virtualView(this.monomerCardRows.length,e=>(this.monomerCardRows[e].render(),this.monomerCardRows[e].root)),this.vv.root.classList.add("duplicate-monomers-virtual-view"),this.searchInput=s.input.string("Search",{placeholder:"Monomer Symbol",value:"",onValueChanged:()=>e(this.searchInput.value)}),this.searchInput.root.style.justifyContent="center",this.searchInput.addOptions(t),this.searchInput.input.style.width="200px",this._root=s.divV([s.h1("Manage Duplicate Monomer Symbols",{style:{textAlign:"center"}}),this.searchInput.root,s.divV([this.vv.root],{style:{overflowY:"auto",height:"100%"}})],{style:{height:"100%"}});const e=e=>{this.filteredMonomerRows=this.monomerCardRows.filter(t=>t.monomerSymbol.toLowerCase().includes(e.toLowerCase())),this.vv.setData(this.filteredMonomerRows.length,e=>(this.filteredMonomerRows[e].render(),this.filteredMonomerRows[e].root))}}}constructor(){}get root(){return this._root}}var Jn=n(3017),ei={};async function ti(){await ri.showDialog()}async function ni(e=!0){return await ai.showView(e)}ei.styleTagTransform=C(),ei.setAttributes=y(),ei.insert=g().bind(null,"head"),ei.domAPI=m(),ei.insertStyleElement=w(),h()(Jn.A,ei),Jn.A&&Jn.A.locals&&Jn.A.locals;class ii{_widget;get widget(){return this._widget}constructor(){}static instancePromise;libHelper;static async getInstance(){return null==ii.instancePromise&&(ii.instancePromise=(async()=>{const e=new ii,t=await(0,ye.pj)();return e.libHelper=t,e._widget=await e.createWidget(),e})()),ii.instancePromise}static async reloadWidget(){const e=await ii.getInstance();e._widget=await e.createWidget()}_fileUploadSubscription=null;async createWidget(){const e=await this.getWidgetContent(),t=await(0,ye.pj)();return this._fileUploadSubscription?.unsubscribe(),this._fileUploadSubscription=t.fileUploadRequested.subscribe(()=>this.promptToAddLibraryFiles()),new r.Widget(e)}async getWidgetContent(){const e=await oi.createControlsForm();return zn()(e).addClass("monomer-lib-controls-form").addClass("d4-dialog-contents"),setTimeout(()=>{e&&zn()(e)&&zn()(e).removeClass("ui-form-condensed")},200),s.divV([e])}async promptToAddLibraryFiles(){r.Utils.openFile({accept:".json",open:async e=>{const t=async t=>{const n=e.name;if((await t.listLibraries()).includes(n)&&!await new Promise(e=>{s.dialog("Confirm Library Update").add(s.divText(`Library '${n}' already exists. Do you want to overwrite it?`)).onOK(()=>e(!0)).onCancel(()=>e(!1)).show()}))return;const i=await e.text(),a=r.TaskBarProgressIndicator.create(`Adding ${n} as a monomer library`);try{await t.addOrUpdateLibraryString(n,i)}catch(e){o.shell.error(`File ${n} is not a valid monomer library, verify it is aligned to HELM JSON schema.`),console.error(e)}finally{a.close()}},n=await this.libHelper.getProviders();if(0===n.length)return void o.shell.error("No monomer library providers available to add the library.");if(1===n.length)return void await t(n[0]);const i=s.dialog("Select storage for new monomer library"),a=s.input.choice("Storage",{items:n.map(e=>e.name),value:n[0].name,nullable:!1,tooltipText:"Storage provider for new monomer library"});i.add(a).onOK(async()=>{const e=n.find(e=>e.name===a.value);await t(e)}).show()}})}}class oi{libHelper;userLibSettings;constructor(e,t){this.libHelper=e,this.userLibSettings=t,this.libHelper.providersDataChanged.subscribe(async()=>{await this.updateControlsForm()})}toLog(){return"LibraryControlsManager<#>"}static async createControlsForm(){Uo.logger.debug("LibraryControlsForm.createControlsForm(), start");const e=await(0,Le.u)(),t=await(0,ye.pj)();return new oi(t,e)._createControlsForm()}async _createControlsForm(){const e=await this.createLibraryControls(),t=s.wideForm(e,void 0);return zn()(t).addClass("monomer-lib-controls-form").addClass("d4-dialog-contents"),t}async updateControlsForm(){const e=await this._createControlsForm();zn()(".monomer-lib-controls-form").replaceWith(e)}async createLibraryControls(){return(await this.libHelper.getAvaliableLibraryNames()).map(e=>this.createLibInput(e))}createLibInput(e){const t=`${this.toLog()}.createLibInput()`;Uo.logger.debug(`${t}, libFileName = '${e}', start`);const n=!this.userLibSettings.exclude.includes(e),i=s.input.bool(e,{value:n,onValueChanged:()=>{si(i.value,e)}});s.tooltip.bind(i.root,`Include monomers from ${e}`);const r=s.iconFA("trash-alt",()=>this.promptForLibraryDeletion(e),"Delete"),a=s.icons.edit(async()=>{o.shell.v=await(await Ln.getInstance()).getViewRoot(e)},"Edit monomer library");return s.tooltip.bind(r,`Delete ${e}`),i.addOptions(a),i.addOptions(r),Uo.logger.debug(`${t}, libFileName = '${e}', end`),i}promptForLibraryDeletion(e){s.dialog("Warning").add(s.divText(`Are you sure you want to delete library "${e}"?`)).onOK(async()=>{try{const t=r.TaskBarProgressIndicator.create(`Deleting ${e} library`);await si(!1,e);const n=await(0,ye.pY)(await this.libHelper.getProviders(),e);if(!n)throw new Error(`Cannot find provider for library ${e}`);await n.deleteLibrary(e),t.close()}catch(t){console.error(t),o.shell.error(`Failed to delete ${e} library`)}}).showModal(!1)}}async function si(e,t){const n=await(0,Le.u)();!function(e,t,n){t?e.exclude=e.exclude.filter(e=>e!==n):e.exclude.includes(n)||e.exclude.push(n)}(n,e,t),await(0,Le.E)(n);const i=await(0,ye.pj)();await i.loadMonomerLib(!0),o.shell.info("Monomer library user settings saved"),i.notifyLibrarySelectionChanged()}class ri{constructor(){}static _instance;dialog;closeDialogSubject$=new c.Subject;static async showDialog(){ri._instance||(ri._instance=new ri,ri._instance.closeDialogSubject$.subscribe(()=>{ri._instance.dialog=void 0})),ri._instance.dialog||(ri._instance.dialog=await ri._instance.getDialog()),ri._instance.dialog.show()}async getDialog(){const e=(await ii.getInstance()).widget,t=await(0,ye.pj)(),n=s.dialog({title:"Manage monomer libraries",helpUrl:"/help/datagrok/solutions/domains/bio/bio.md#manage-monomer-libraries"});zn()(n.root).css("width","350px"),n.clear(),n.addButton("Add",()=>t.requestFileUpload(),void 0,"Upload new HELM monomer library"),n.add(e);const i=n.onClose.subscribe(()=>{this.closeDialogSubject$.next(),i.unsubscribe()});return n}}class ai{constructor(){}static _instance;static viewName="Manage Monomer Libraries";_view;_duplicateManager;libManager;async getView(e=!0){const t=(await ii.getInstance()).widget,n=s.bigButton("Add",()=>this.libManager.requestFileUpload(),"Upload new HELM monomer library"),i=s.bigButton("Merge",()=>{this.mergeSelectedLibs()},"Merge selected libraries into one"),a=s.splitH([s.divV([t.root,s.buttonsInput([n,i])],{classes:"ui-form"}),this._duplicateManager.root],{style:{width:"100%",height:"100%"}},!0);if(this._view)try{this._view.subs.forEach(e=>e.unsubscribe()),this._view.detach(),this._view.close()}catch(e){}return this._view=r.View.fromRoot(a),this._view.name=ai.viewName,e&&o.shell.addView(this._view),s.tools.waitForElementInDom(a).then(()=>{setTimeout(()=>{const e=Array.from(a.children).filter(e=>e.classList.contains("ui-box"));if(2!==e.length)return;const[t,n]=e,i=t.getBoundingClientRect().width+n.getBoundingClientRect().width,o=.3*i;t.style.width=`${o}px`;const s=i-o;n.style.width=`${s}px`},100),this._view.subs.push(o.events.onCurrentViewChanged.subscribe(()=>{try{const e=ai._instance;e&&e._view&&o.shell.v&&"id"in o.shell.v&&o.shell.v.id===e._view.id&&e._duplicateManager?.refresh()}catch(e){console.error(e)}}))}),this._view}static async showView(e=!0){return ai._instance||(ai._instance=new ai),ai._instance._duplicateManager||(ai._instance._duplicateManager=await Qn.getInstance()),ai._instance.libManager||(ai._instance.libManager=await bn.getInstance()),e&&ai._instance._view&&Array.from(o.shell.views).find(e=>e.id&&e.id===ai._instance._view.id)?(o.shell.v=ai._instance._view,await ai._instance._duplicateManager.refresh(),ai._instance._view):(ai.closeExistingViews(),ai._instance.getView(e))}static closeExistingViews(){Array.from(o.shell.views).filter(e=>e.name===ai.viewName).forEach(e=>e.close())}async mergeSelectedLibs(){const e="Library with this name already exists",t=await bn.getInstance();if(await t.awaitLoaded(),!t.duplicatesHandled)return void o.shell.warning("Selected libraries contain repeating symbols with different monomers.\n Please choose the correct monomer for each symbol using duplicate monomomer manager.");const n=t.getBioLib().toJSON(),i=s.dialog("Merge selected libraries"),a=s.input.string("Library Name",{placeholder:"Enter new library name",nullable:!1,onValueChanged:()=>{const t=c(a.value);i.getButton("Download")?.classList?.toggle("d4-disabled",!!t&&t!==e),i.getButton("Save")?.classList?.toggle("d4-disabled",!!t)}}),l=await this.libManager.getAvaliableLibraryNames();function c(t){return t&&t.trim()?l.includes(t)||l.includes(t+".json")?e:null:"Library name cannot be empty"}a.addValidator(c);const u=await this.libManager.getProviders();if(0===u.length)return void o.shell.error("No monomer library providers available to save the merged library.");const h=s.input.choice("Storage",{items:u.map(e=>e.name),value:u[0].name,nullable:!1,tooltipText:"Storage provider for saving new monomer library"});i.add(h).add(a).add(s.divText(`Total monomers: ${n.length}`)).addButton("Download",()=>{r.Utils.download((()=>{let e=a.value.trim();return e||(e="New"),e.toLowerCase().endsWith(".json")||(e+=".json"),e})(),JSON.stringify(n))}).addButton("Save",async()=>{if(!a.value||!a.value.trim()||!h.value)return h.validate(),void a.validate();i.close();const e=a.value,t=JSON.stringify(n);this._view&&s.setUpdateIndicator(this._view.root,!0);try{const n=u.find(e=>e.name===h.value);await n.addOrUpdateLibraryString(e,t);const i=await(0,Le.u)();i.exclude=l,await(0,Le.E)(i),await this.libManager.loadMonomerLib(!0),await ii.reloadWidget()}catch(t){o.shell.error(`Failed to save library ${e}. see console for details.`),console.error(t)}finally{this._view&&s.setUpdateIndicator(this._view.root,!1)}}).show(),i.getButton("Download")?.classList?.add("d4-disabled"),i.getButton("Save")?.classList?.add("d4-disabled")}}var li,ci=function(e,t,n,i){return new(n||(n=Promise))(function(o,s){function r(e){try{l(i.next(e))}catch(e){s(e)}}function a(e){try{l(i.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(r,a)}l((i=i.apply(e,t||[])).next())})};class ui{_setBreadcrumbsInViewName(){var e,t;const n=["Home","Demo",...(null!==(e=this._path)&&void 0!==e?e:"").split("/")],i=s.breadcrumbs(n);if(i.onPathClick.subscribe(e=>ci(this,void 0,void 0,function*(){const t=e[e.length-1];if(t===i.path[i.path.length-1])return;const n=o.shell.browsePanel.mainTree.getOrCreateGroup("Apps").getOrCreateGroup("Demo");n.currentItem="Demo"===t?n:n.items.find(e=>e.text===t)})),o.shell.v){if(0!==i.path.length&&"Home"===i.path[0]){const e=s.iconFA("home",()=>{o.shell.v.close(),o.shell.v=r.View.createByType(r.VIEW_TYPE.HOME)});e.classList.add("demo-breadcrumbs-home-element"),i.root.firstElementChild.replaceWith(e)}const e=null===(t=o.shell.v.ribbonMenu.root.parentElement)||void 0===t?void 0:t.getElementsByClassName("d4-ribbon-name")[0];e&&(e.textContent="",e.appendChild(i.root))}}constructor(e,t,n=!1,i){var o,r;this.name="",this.description="",this._isAutomatic=!1,this._autoStartFirstStep=!1,this._currentStep=0,this._isStopped=!1,this._isCancelled=!1,this._isStepProcessed=!1,this._root=s.div([],{id:"demo-script",classes:"tutorials-root tutorials-track demo-app-script"}),this._steps=[],this._mainHeader=s.panel([],"tutorials-main-header"),this._header=s.h2(""),this._headerDiv=s.divH([],"tutorials-root-header"),this._stopStartBtn=s.button(s.iconFA("pause"),()=>ci(this,void 0,void 0,function*(){return yield this._changeStopState()}),"Play / pause"),this._restartBtn=s.button(s.iconFA("redo"),()=>ci(this,void 0,void 0,function*(){return yield this._restartScript()}),"Restart"),this._nextStepBtn=s.button(s.iconFA("play"),()=>ci(this,void 0,void 0,function*(){this._isStepProcessed||(yield this._nextStep())}),"Next step"),this._activity=s.panel([],"tutorials-root-description"),this._progressDiv=s.divV([],"tutorials-root-progress"),this._progress=s.element("progress"),this._progressSteps=s.divText(""),this._closeBtn=s.button(s.iconFA("chevron-left"),()=>this._closeDock(),"Back to demo"),this.DEMO_PATH="apps/Tutorials/Demo",this.name=e,this.description=t,this._isAutomatic=n,this._autoStartFirstStep=null!==(o=null==i?void 0:i.autoStartFirstStep)&&void 0!==o&&o,this._path=null!==(r=null==i?void 0:i.path)&&void 0!==r?r:"",this._progress.max=0,this._progress.value=1,ui.currentObject=this}get steps(){return this._steps}get stepNumber(){return this._steps.length}_addHeader(){this._createHeaderDiv(),this._createProgressDiv(),this._mainHeader.append(this._headerDiv,this._progressDiv)}_createHeaderDiv(){this._header.innerText=this.name,this._headerDiv.append(this._closeBtn),this._headerDiv.append(this._header),this._nextStepBtn.firstChild.className="grok-icon fas fa-play",this._headerDiv.append(this._isAutomatic?this._stopStartBtn:this._nextStepBtn)}_createProgressDiv(){this._progress.max=this.stepNumber,this._progressDiv.append(this._progress),this._progressSteps=s.divText(`Step: ${this._progress.value} of ${this.stepNumber}`),this._progressDiv.append(this._progressSteps)}_addDescription(){var e;this._activity.append(s.div(this.description,"tutorials-root-description"));for(let t=0;t<this.stepNumber;t++){let n=s.iconFA("clock");this._isAutomatic||0===t&&(n=s.iconFA("play",()=>this._nextStep(),"Next step"),n.className="grok-icon fas fa-play");const i=s.div(this._steps[t].name,"grok-tutorial-entry-instruction"),o=s.div(null===(e=this._steps[t].options)||void 0===e?void 0:e.description,"grok-tutorial-step-description hidden"),r=s.divH([n,i],"grok-tutorial-entry");this._activity.append(r,o)}}_initRoot(){o.shell.windows.showContextPanel=!0,o.shell.windows.showHelp=!1,this._node=o.shell.dockManager.dock(this._root,r.DOCK_TYPE.FILL,o.shell.dockManager.findNode(o.shell.browsePanel.root),this.name),this._node.container.containerElement.classList.add("tutorials-demo-script-container"),this._addHeader(),this._root.append(this._mainHeader),this._addDescription(),this._root.append(this._activity)}_setViewParams(){var e;o.shell.v&&(o.shell.v.name=this.name,o.shell.v.path=`${this.DEMO_PATH}/${(null!==(e=this._path)&&void 0!==e?e:"").replaceAll(" ","-")}`,this._setBreadcrumbsInViewName())}_nextStep(){return ci(this,void 0,void 0,function*(){var e,t;this._isStepProcessed=!0,this._isAutomatic||(this._nextStepBtn.classList.add("disabled"),this._nextStepBtn.firstChild.classList.add("fa-disabled"));const n=this._activity.getElementsByClassName("grok-tutorial-entry")[this._currentStep],i=this._activity.getElementsByClassName("grok-icon")[this._currentStep],a=this._activity.getElementsByClassName("grok-tutorial-step-description")[this._currentStep];i.className="grok-icon far fa-spinner-third fa-spin",a.classList.remove("hidden"),a.classList.add("visible");const l=n,c=(null===(e=this._steps[this._currentStep].options)||void 0===e?void 0:e.delay)?null===(t=this._steps[this._currentStep].options)||void 0===t?void 0:t.delay:2e3;try{this._setViewParams(),yield this._steps[this._currentStep].func(),this._setViewParams()}catch(e){console.error(e)}this._scrollTo(this._root,l.offsetTop-this._mainHeader.offsetHeight),this._isAutomatic&&(yield this._countdown(n,i,c),yield r.delay(c));const u=s.iconFA("check");if(i.replaceWith(u),u.className="grok-icon far fa-check",this._progress.value++,this._progressSteps.innerText=`Step: ${this._progress.value} of ${this.stepNumber}`,this._currentStep++,this._isStepProcessed=!1,this._currentStep===this.stepNumber)return this._restartBtn.disabled=!1,void(this._isAutomatic?this._stopStartBtn.replaceWith(this._restartBtn):this._nextStepBtn.replaceWith(this._restartBtn));if(!this._isAutomatic){const e=this._activity.getElementsByClassName("grok-icon")[this._currentStep],t=s.iconFA("play",()=>this._nextStep(),"Next step");t.className="grok-icon fas fa-play",e.replaceWith(t),this._nextStepBtn.classList.remove("disabled"),this._nextStepBtn.firstChild.classList.remove("fa-disabled")}o.shell.v instanceof r.TableView&&(yield o.data.detectSemanticTypes(o.shell.tv.dataFrame))})}_startScript(){return ci(this,void 0,void 0,function*(){for(let e=this._currentStep;e<this.stepNumber&&!this._isStopped&&!this._isCancelled;e++)yield this._nextStep()})}_scrollTo(e,t){e.focus(),e.scrollTop=t}_countdown(e,t,n){return ci(this,void 0,void 0,function*(){const i=s.div([],"demo-script-countdown");t.classList.add("hidden");let o=n/1e3;const r=this._createSVGIndicator(o);i.append(r),e.prepend(i);const a=setInterval(()=>{o--,0===o&&(clearInterval(a),i.remove(),t.classList.remove("hidden"),t.classList.add("visible"))},1e3)})}_createSVGIndicator(e){const t=document.createElementNS("http://www.w3.org/2000/svg","svg"),n=document.createElementNS("http://www.w3.org/2000/svg","circle");return n.setAttributeNS(null,"cx","7"),n.setAttributeNS(null,"cy","7"),n.setAttributeNS(null,"r","6"),n.setAttributeNS(null,"style",`animation: countdown ${e}s linear infinite forwards`),t.append(n),t}_changeStopState(){return ci(this,void 0,void 0,function*(){const e=this._stopStartBtn.getElementsByClassName("grok-icon");e[0].className="grok-icon fas fa-play",this._isStopped=!this._isStopped,this._isStopped||(e[0].className="grok-icon fal fa-pause",this._isStepProcessed||(yield this._startScript()))})}_restartScript(){return ci(this,void 0,void 0,function*(){this._restartBtn.disabled=!0,o.shell.dockManager.close(this._node),this._clearRoot(),this._setInitParams(),yield this.start()})}_clearRoot(){this._root=s.div([],{id:"demo-script",classes:"tutorials-root tutorials-track demo-app-script"}),this._mainHeader=s.panel([],"tutorials-main-header"),this._header=s.h2(""),this._headerDiv=s.divH([],"tutorials-root-header"),this._activity=s.panel([],"tutorials-root-description"),this._progressDiv=s.divV([],"tutorials-root-progress"),this._progress=s.element("progress"),this._progressSteps=s.divText(""),this._progress.max=0,this._progress.value=1}_setInitParams(){this._currentStep=0,this._isStopped=!1,this._isCancelled=!1,this._stopStartBtn.getElementsByClassName("grok-icon")[0].className="grok-icon fal fa-pause",this._nextStepBtn.classList.remove("disabled")}_closeDock(){o.shell.dockManager.close(this._node),this.cancelScript()}cancelScript(){this._isCancelled=!0,ui.currentObject=null}step(e,t,n){return this._steps[this.steps.length]={name:e,func:t,options:n},this}start(){return ci(this,void 0,void 0,function*(){var e;(null===(e=o.shell.v)||void 0===e?void 0:e.name)===this.name&&o.shell.v.close(),this._initRoot(),this._isAutomatic?yield this._startScript():this._autoStartFirstStep&&(yield this._nextStep())})}}ui.currentObject=null,function(e){e.X="Embed_X",e.Y="Embed_Y"}(li||(li={}));var hi=n(5749),di=n(966),mi=n(608),pi=n(1619),gi=n(8152);class fi{urlParams;funcName;options;df;view;constructor(e,t,n={}){this.urlParams=e,this.funcName=t,this.options=n}async init(e){this.df=e,await this.buildView()}async buildView(){const e=ee()(this.urlParams.entries()).map(([e,t])=>`${e}=${encodeURIComponent(t)}`).toArray().join("&");this.view=o.shell.addTableView(this.df),this.view.path=this.view.basePath=`func/${Uo.name}.${this.funcName}?${e}`;const t={...this.options,sequenceColumnName:"sequence"};for(const[e,n]of this.urlParams.entries())switch(e){case tt.n5.fixWidth:case tt.n5.fitArea:t[e]=(e=>["1","on","true"].includes(e.toLowerCase()))(n);break;default:t[e]=n}const n=await this.view.dataFrame.plot.fromType("WebLogo",t);this.view.dockManager.dock(n,r.DOCK_TYPE.DOWN,null,"WebLogo",.35)}}class yi{tableInput;seqColInput;funcParamsDiv;get funcParams(){return{table:this.tableInput.value,sequence:this.seqColInput.value}}get paramsUI(){return this.funcParamsDiv}constructor(){this.tableInput=s.input.table("Table",{value:o.shell.tv.dataFrame,onValueChanged:()=>{this.onTableInputChanged()}});const e=this.tableInput.value.columns.bySemType(r.SEMTYPE.MACROMOLECULE);this.seqColInput=s.input.column("Sequence",{table:this.tableInput.value,value:e,filter:e=>e.semType===r.SEMTYPE.MACROMOLECULE}),this.funcParamsDiv=s.inputs([this.tableInput,this.seqColInput],{style:{minWidth:"320px"}})}onTableInputChanged(){this.seqColInput=s.input.column("Sequence",{table:this.tableInput.value,value:this.tableInput.value.columns.bySemType(r.SEMTYPE.MACROMOLECULE)})}}var bi=n(6869);const wi="-";class vi extends Be{constructor(e,t){super(e,t)}static _canonLoadingKey=pe.sc+".loading";getCanonicalizer(e){const t=e.temp[pe.sc]??null;if(t)return t;if(e.temp[vi._canonLoadingKey])return null;const n=e.getTag(pe.jz);if(!n)return null;const i=n.includes(":")?n.split(":"):[void 0,n],o=r.Func.find({name:i[1],package:i[0]});return 0===o.length||(e.temp[vi._canonLoadingKey]=!0,o[0].apply({}).then(t=>{e.temp[pe.sc]=t,e.temp[vi._canonLoadingKey]=!1,this.gridCol?.grid?.invalidate&&this.gridCol.grid.invalidate()}).catch(()=>{e.temp[vi._canonLoadingKey]=!1})),null}render(e,t,n,i,o,s,r){e.save(),e.beginPath(),e.rect(t,n,i,o),e.clip();try{if(!s.isTableCell)return;const r=s.cell?.column&&s.cell.column?.dart&&"true"===s.cell.column.getTag(Re.Mn.applyToBackground);e.font="12px monospace",e.textBaseline="middle",e.textAlign="left";const a=e.measureText("M"),l=a.actualBoundingBoxAscent+a.actualBoundingBoxDescent+8;let c=s.cell.value;c&&c!==pe._S||(c=wi);const u=c.split(pe.ot).map(e=>e&&e!==pe._S?e.trim():wi),h=u.map(e=>(0,ue.zS)(e,Math.max(2,Math.floor(.15*i/u.length)))),d=h.map(t=>e.measureText(t).width+4),m=d.reduce((e,t)=>e+t,0);let p=t+(i-m)/2+2;const g=this.tableCol.getTag(pe.gp.alphabet),f=g===ue.YI.RNA||g===ue.YI.DNA?bi.o.NUCLEOTIDE:bi.o.AA;for(let a=0;a<h.length;a++){const c=u[a],m=this.getHelmType(s,f);let g=$e.S$,y="rgb(255, 255, 255)";if(this.monomerLib)if(r){const e=this.monomerLib.getMonomerColors(m,c);g=e?.textcolor??g,y=e?.backgroundcolor??y}else g=this.monomerLib.getMonomerTextColor(m,c);if(r)if(e.fillStyle=y,i<30||o<30)e.fillRect(t+a*i/h.length,n,i/h.length,o);else{const t=2;e.roundRect(p-2,n+o/2-l/2,d[a],l,t),e.fill()}e.fillStyle=g,e.fillText(h[a],p,n+o/2,i),p+=d[a]}}finally{e.restore()}}onMouseMove(e,t){const[n,i,o]=(0,De.BG)(e);if(e.grid.dart!=this.gridCol?.grid.dart||n?.dart!=this.gridCol?.dart||!i||!e.isTableCell)return!1;const r=i.getTag(pe.gp.alphabet),a=e.cell.value,l=this.getCanonicalizer(i),c=l&&a?l.canonicalize(a):a,u=e.grid.canvas.getBoundingClientRect(),h=e.bounds.right+u.left-4,d=e.bounds.bottom+u.top-4;if(!a||a==pe._S||a==wi||null!=l&&l.isGap(a))return s.tooltip.show(s.divText("gap"),h,d),!0;if(!this.monomerLib)return s.tooltip.show(s.divText("Monomer library is not available."),h,d),!0;const m=r===ue.YI.RNA||r===ue.YI.DNA?bi.o.NUCLEOTIDE:bi.o.AA,p=c.split(pe.ot).map(t=>{if(!t||t===pe._S||t===wi)return s.divText("gap");const n=this.getHelmType(e,m);return this.monomerLib.getTooltip(n,t)}),g=s.divH(p,{style:{alignItems:"top",flexWrap:"wrap",gap:"4px"}}),f=Array.from(g.querySelectorAll("canvas"));if(f.length>2){const e=Math.floor(550/f.length);f.forEach(t=>{t.style.setProperty("max-width",`${e}px`,"important"),t.style.setProperty("max-height",`${e}px`,"important")})}return s.tooltip.show(g,h,d),!0}getHelmType(e,t){let n=t;const[i,o,s]=(0,De.BG)(e);if((e.tableRowIndex??-1)>-1&&o?.getTag(pe.qE.polymerTypeColumnName)){const t=o.getTag(pe.qE.polymerTypeColumnName),i=o.dataFrame?.col(t);if(i){const t=i.get(e.tableRowIndex);t&&["BLOB","CHEM","G","PEPTIDE","RNA"].includes(t)&&(n=(0,Oe.MD)(t))}}return n}async awaitRendered(e=1e4,t=`${e} timeout`){return Promise.resolve()}static getOrCreate(e){const[t,n,i]=(0,De.BG)(e);let o=i.rendererBack;return o||(o=i.rendererBack=new vi(t,n)),o}}class Ci extends r.GridCellRenderer{get name(){return Ve.uF.MONOMER}get cellType(){return Ve.uF.MONOMER}get defaultHeight(){return 15}get defaultWidth(){return 40}render(e,t,n,i,o,s,r){vi.getOrCreate(s).render(e,t,n,i,o,s,r)}onMouseMove(e,t){vi.getOrCreate(e).onMouseMove(e,t),t.preventDefault()}}class Ai{constructor(e,t,n=""){this.target=e,this.debugEnabled=t,this.prefix=n}error(e,t,n){return this.target.error(this.prefix+e,t,n)}warning(e,t){return this.target.warning(this.prefix+e,t)}info(e,t){return this.target.info(this.prefix+e,t)}debug(e,t){if(this.debugEnabled)return this.target.debug(this.prefix+e,t)}}class Ti extends Map{_onPropertyChanged=new c.Subject;get onPropertyChanged(){return this._onPropertyChanged}get fontSize(){const e=super.get("FontSize");return e&&!isNaN(e)?Number.parseInt(e):12}set fontSize(e){super.set("FontSize",e),this._onPropertyChanged.next("FontSize")}get maxMonomerLength(){const e=super.get("MaxMonomerLength");return"long"===e?null:parseInt(e)}set maxMonomerLength(e){const t=null==e?"long":e.toString();super.set("MaxMonomerLength",t),this._onPropertyChanged.next("MaxMonomerLength")}get tooltipWebLogo(){return super.get("TooltipWebLogo")}set tooltipWebLogo(e){super.set("TooltipWebLogo",e),this._onPropertyChanged.next("TooltipWebLogo")}get defaultSeparator(){return super.get("DefaultSeparator")}set defaultSeparator(e){if(1!==e.length)throw new Error("The separator must be of length one.");super.set("DefaultSeparator",e),this._onPropertyChanged.next("DefaultSeparator")}constructor(e){super(Object.entries(e))}}class Ei extends r.Package{_properties;_seqHelper;get seqHelper(){if(!this._seqHelper)throw new Error("Package Bio .seqHelper is not initialized.");return this._seqHelper}_monomerLib;get monomerLib(){if(!this._monomerLib)throw new Error("Package Bio .monomerLib is not initialized.");return this._monomerLib}_monomerSets;get monomerSets(){if(!this._monomerSets)throw new Error("Package Bio .monomerSets is not initialized.");return this._monomerSets}_rdKitModule;get rdKitModule(){if(!this._rdKitModule)throw new Error("Package Bio .rdKitModule is not initialized.");return this._rdKitModule}get properties(){return this._properties}set properties(e){this._properties=e}_initialized=!1;get initialized(){return this._initialized}constructor(e={debug:!1}){super(),super._logger=new Ai(super.logger,e.debug)}completeInit(e,t,n,i){this._seqHelper=e,this._monomerLib=t,this._monomerSets=n,this._rdKitModule=i,this._initialized=!0}handleErrorUI(e){const[t,n]=(0,we.AP)(e);o.shell.error(t),this.logger.error(t,void 0,n)}}var Si=n(6307),Mi=n(5999),xi={};xi.styleTagTransform=C(),xi.setAttributes=y(),xi.insert=g().bind(null,"head"),xi.domAPI=m(),xi.insertStyleElement=w(),h()(Mi.A,xi),Mi.A&&Mi.A.locals&&Mi.A.locals;class Pi extends r.Widget{seqCol;seqHelper;get type(){return"MacromoleculeColumnWidget"}viewed=!1;wlViewer=null;constructor(e,t){super(s.divV([])),this.seqCol=e,this.seqHelper=t}async init(){const e=this.seqHelper.getSeqHandler(this.seqCol),t=Uo.properties.tooltipWebLogo,n=this.seqCol.getTag(Qe.gp.tooltipWebLogo);!1===t||["false","off","disable","disabled"].includes(n)||(this.wlViewer=await this.seqCol.dataFrame.plot.fromType("WebLogo",{sequenceColumnName:this.seqCol.name,backgroundColor:0,positionHeight:"Entropy",positionWidth:e.getAlphabetIsMultichar()?24:16,fixWidth:!0,fitArea:!1,positionNames:"",endPositionName:"50"}),this.wlViewer.root.style.height="50px",this.root.appendChild(this.wlViewer.root),this.root.style.width="100%")}detach(){this.wlViewer&&(this.wlViewer.detach(),this.wlViewer=null),super.detach()}}var Li=n(4951);function Ii(e,t,n,i){const o=Uo.seqHelper.getSeqHandler(e);let s=null,a=null;for(let e=0;e<o.posList.length;++e)o.posList[e]==t&&(s=e),o.posList[e]==n&&(a=e);if(null==s&&null!==t)throw new Error(`Start position ${t} not found.`);if(null==a&&null!==n)throw new Error(`End position ${n} not found.`);if(o.posList.length<a)throw new Error(`End position ${a} exceeds positions length`);const l=i||`${e.name}: (${t??""}-${n??""})`,c=function(e,t,n,i,o){if(!n||!i||!e.dataFrame)return null;const s=e.getTag(ue.gp.annotations);if(!s)return null;let a;try{a=JSON.parse(s)}catch{return null}const l=a.find(e=>e.category===St.eI.Structure&&e.start===n&&e.end===i);if(!l)return null;const c=(0,Et.VT)(e.name);let u=null;try{u=e.dataFrame.columns.byName(c)}catch{return null}if(!u)return null;const h=(0,Et.wi)(u);if(!h.some(e=>e?.some(e=>e.annotationId===l.id&&null!=e.endPositionIndex)))return null;const d=e.dataFrame,m=r.Column.fromType(r.COLUMN_TYPE.STRING,o,d.rowCount);for(let e=0;e<d.rowCount;e++){const n=h[e],i=n?.find(e=>e.annotationId===l.id&&null!=e.endPositionIndex);if(i){const n=t.getSplitted(e),o=[];for(let e=i.positionIndex;e<=i.endPositionIndex;e++)e<n.length&&o.push(n.getOriginal(e));m.set(e,o.join(t.separator||""))}else m.set(e,"")}return m}(e,o,t,n,l);return c||o.getRegion(s,a,l)}const _i={df:r.DataFrame.fromCsv("seq,value\nATCCGTCGT,0.5\nTGTTCGTCA,0.4\nATGGTCGTA,0.7\nATCCGTGCA,0.1"),colName:"seq",positionNames:["1","1A","1C","2","4","4A","4B","5","6"].join(ue.z1),regions:[{name:"first region",start:"1",end:"2"},{name:"second region",start:"1C",end:"4"},{name:"overlapping second",start:"1C",end:"4A"},{name:"whole sequence",start:"1",end:"6"},{name:"bad start",start:"0",end:"6"},{name:"bad end",start:"1",end:"4C"},{name:"bad start & end",start:"0",end:"4C"}]};class Ni{urlParams;funcName;view;data;constructor(e,t){this.urlParams=e,this.funcName=t}async init(e){this.data=e??_i;const t=this.data.df.getCol(this.data.colName);this.data.positionNames&&t.setTag(ue.gp.positionNames,this.data.positionNames),this.data.regions&&t.setTag(ue.gp.regions,JSON.stringify(this.data.regions)),await this.buildView()}async buildView(){await o.data.detectSemanticTypes(this.data.df),this.view=o.shell.addTableView(this.data.df),this.view.path=this.view.basePath=`func/${Uo.name}.${this.funcName}`;const e=await this.view.dataFrame.plot.fromType("WebLogo",{sequenceColumnName:this.data.colName});this.view.dockManager.dock(e,r.DOCK_TYPE.DOWN,null,"WebLogo",.35)}}class Ri{call;seqHelper;inputs=new class{table;sequence;region;start;end;name};constructor(e,t){this.call=e,this.seqHelper=t;const n=e=>this.call.inputParams[e].property.description;this.inputs.table=s.input.table("Table",{value:this.call.inputParams.table.value??o.shell.tv.dataFrame});const i=this.call.inputParams.sequence.value??this.inputs.table.value.columns.bySemType(r.SEMTYPE.MACROMOLECULE);this.inputs.sequence=s.input.column("Sequence",{table:o.shell.tv.dataFrame,value:i,onValueChanged:this.sequenceInputChanged.bind(this),filter:e=>e.semType===r.SEMTYPE.MACROMOLECULE}),this.inputs.start=s.input.choice("Start",{onValueChanged:this.startInputChanged.bind(this)}),this.inputs.end=s.input.choice("End",{onValueChanged:this.endInputChanged.bind(this)}),this.inputs.region=s.input.choice("Region",{value:null,items:[],onValueChanged:this.regionInputChanged.bind(this)}),this.inputs.name=s.input.string("Column name",{value:this.getDefaultName(),onValueChanged:this.nameInputChanged.bind(this),clearIcon:!0}),this.inputs.name.onInput.subscribe(()=>this.nameInputInput.bind(this));for(const e in this.call.inputParams)s.tooltip.bind(this.inputs[e].captionLabel,n(e));this.sequenceInputChanged()}sequenceInputChanged(){const e=this.inputs.sequence.value;e&&this.seqHelper.getSeqHandler(e),this.updateRegionItems(),this.updateStartEndInputItems(),this.updateRegion(!0),this.updateNameInput()}fixRegion=!1;regionInputChanged(){this.fixRegion=!0;try{const e=this.inputs.region.stringValue,t=e?JSON.parse(e):null;if(null!==t)this.inputs.start.value=t?.start,this.inputs.end.value=t?.end;else{const e=this.seqHelper.getSeqHandler(this.inputs.sequence.value);this.inputs.start.value=e.posList[0],this.inputs.end.value=e.posList[e.posList.length-1]}}finally{this.fixRegion=!1}}startInputChanged(){this.updateRegion(!1),this.updateNameInput()}endInputChanged(){this.updateRegion(!1),this.updateNameInput()}nameInputChanged(){this.defaultNameUpdating||(this.defaultName=!1)}nameInputInput(){this.inputs.name.value||(this.defaultName=!0,this.inputs.name.input.focus())}updateStartEndInputItems(){const e=this.inputs.sequence.value,t=e?this.seqHelper.getSeqHandler(e):null,n=this.inputs.start.input,i=this.inputs.end.input;for(let e=n.options.length-1;e>=0;--e)n.options.remove(e);for(let e=i.options.length-1;e>=0;--e)i.options.remove(e);for(const e of t?.posList??[]){const t=document.createElement("option"),o=document.createElement("option");t.text=o.text=e,t.value=o.value=e,n.options.add(t),i.options.add(o)}n.value=t?.posList[0]??"",i.value=t?.posList[t?.posList.length-1]??""}updateRegionItems(){const e=this.inputs.sequence.value;let t=null;const n=e?e.getTag(ue.gp.annotations):null;if(n)try{const e=JSON.parse(n).filter(e=>"structure"===e.category&&e.start&&e.end);e.length>0&&(t=e.map(e=>({name:e.name,description:e.description??"",start:e.start,end:e.end})))}catch{}if(!t){const n=e?e.getTag(ue.gp.regions):null;t=n?JSON.parse(n):null}const i=this.inputs.region.input;for(let e=i.options.length-1;e>=0;--e)i.options.remove(e);const o=document.createElement("option");if(o.text="",o.value=JSON.stringify(null),i.options.add(o),null!=t){this.inputs.region.root.style.removeProperty("display");for(const e of t){const t=document.createElement("option");t.text=`${e.name}: ${e.start}-${e.end}`,t.value=JSON.stringify(e),i.options.add(t)}}else this.inputs.region.root.style.display="none"}updateRegion(e){const t=this.inputs.start.stringValue??"",n=this.inputs.end.stringValue??"";if(!this.fixRegion){const e=this.inputs.region.input;e.selectedIndex=-1;for(let i=e.options.length-1;i>=0;--i){const o=e.options[i],s=JSON.parse(o.value);s&&t===s.start&&n===s.end&&(e.selectedIndex=i)}}}defaultName=!0;defaultNameUpdating=!1;updateNameInput(){this.defaultNameUpdating=!0;try{this.defaultName&&(this.inputs.name.value=this.getDefaultName())}finally{this.defaultNameUpdating=!1}}getDefaultName(){const e=this.inputs.region.stringValue,t=e?JSON.parse(e):null,n=this.inputs.sequence.value,i=this.inputs.start.stringValue??"",o=this.inputs.end.stringValue??"";return null!=t?`${n.name}(${t.name}): ${t.start}-${t.end}`:`${n?.name}: (${i}-${o})`}getParams(){return{table:this.inputs.table.value,sequence:this.inputs.sequence.value,start:this.getStart(),end:this.getEnd(),name:this.getName()}}getStart(){return this.inputs.start.stringValue}getEnd(){return this.inputs.end.stringValue}getName(){const e=this.inputs.name.stringValue;return""==e?null:e}dialog(){const e=s.inputs(Object.values(this.inputs),{style:{minWidth:"320px"}});s.dialog({title:"Get Region"}).add(e).onOK(()=>{(async()=>{const e=this.getParams();await this.call.func.prepare(e).call(!0)})().catch(e=>{Uo.handleErrorUI(e)})}).show()}widget(){const e=s.inputs(Object.entries(this.inputs).filter(([e,t])=>!["table","sequence"].includes(e)).map(([e,t])=>t)),t=s.button("Get Region",()=>{(async()=>{const e=this.getParams();await this.call.func.prepare(e).call(!0)})().catch(e=>{Uo.handleErrorUI(e)})});return r.Widget.fromRoot(s.divV([e,s.div(t)]))}}var $i=n(8754);async function Oi(e,t,n,i,s){const a=await async function(e,t,n,i,s){const a=ge(t,s),l=s.getSeqHandler(t).getNewColumnFromList("ref",[n]),c=s.getSeqHandler(l).getSplitted(0),u=i===fe.IDENTITY?function(e,t){const n=t.columns.length,i=new Array(n),o=new Array(n),s=new Array(n);for(let r=0;r<n;++r){const n=t.columns.byIndex(r);i[r]=n.getRawData(),o[r]=n.categories.indexOf("");const a=r<e.length?e.getOriginal(r):pe._S;s[r]=n.categories.indexOf(a)}const a=r.Column.float("Identity",t.rowCount),l=a.getRawData();for(let n=0;n<t.rowCount;++n){l[n]=0;for(let t=0;t<e.length;++t)(i[t]?i[t][n]:0)===s[t]&&++l[n];l[n]/=e.length}return a}(c,a):i===fe.SIMILARITY?await async function(e,t,n){const i=t.columns.toList(),s=await async function(e,t,n){e instanceof r.Column&&(e=ge(e,n).columns.toList());const i=(await(0,ye.pj)()).getMonomerLib(),s=new Array(e.length),a=e[0].length,l=new Float32Array(a);for(let n=0;n<e.length;++n){const c=n<t.length?t.getCanonical(n):pe._S,u=i.getMonomer("PEPTIDE",c)?.smiles??"",h=e[n],d=h.getRawData(),m=h.categories,p=m.indexOf("");if(s[n]={categories:m,data:d,emptyIndex:p},void 0===c)continue;const g=r.Column.fromStrings("smiles",m.map(e=>i.getMonomer("PEPTIDE",e)?.smiles??"")),f=(r.DataFrame.fromColumns([g]),await o.chem.getSimilarities(g,u)),y=f?f.getRawData():null;for(let e=0;e<a;++e){const t=d[e];c!==pe._S&&t!==p?l[e]+=y[t]:c===pe._S&&t===p&&(l[e]+=1)}}for(let n=0;n<l.length;++n){let i=l[n]/t.length;for(let o=0;o<e.length;++o){const e=s[o];if(o>=t.length&&e.data[n]!==e.emptyIndex||e.data[n]===e.emptyIndex&&o<t.length){i=r.FLOAT_NULL;break}}l[n]=i}return r.Column.fromFloat32Array("Similarity",l)}(i,e,n);return s}(c,a,s):null;if(null==u)throw new Error(`In bio library: Unknown sequence scoring method: ${i}`);return u.name=e.columns.getUnusedName(u.name),e.columns.add(u),u}(e,t,n,i,s);for(let e=0;e<a.length;e++)t.isNone(e)&&a.set(e,null,!1);return a}var Hi=n(294),Di=n(330);const Fi=OCL;var ki=n(2582);class Gi{monomerSymbol;constructor(e){this.monomerSymbol=e}atoms;bonds;rGroups;get atomCount(){return this.atoms.count}get bondCount(){return this.bonds.count}shiftR1GroupToOrigin(){const e=this.rGroups.getAtomicIdx(1);if(null==e)return;const{x:t,y:n}=this.atoms.atomCoordinates[e];this.atoms.shift({x:-t,y:-n})}alignR2AlongX(){const e=this.rGroups.getAtomicIdx(2);if(null==e)throw new Error(`Cannot find R2 group for monomer ${this.monomerSymbol}`);const t=this.atoms.atomCoordinates[e],n=t.y/t.x,i=Math.atan(n);if(isNaN(i))throw new Error(`Cannot calculate angle for R2 group for monomer ${this.monomerSymbol}`);this.rotateCoordinates(-i)}shiftMonomerToDefaultPosition(){this.shiftR1GroupToOrigin(),null!==this.rGroups.getAtomicIdx(2)&&this.alignR2AlongX()}deleteBondLineWithSpecifiedRGroup(e){this.rGroups.deleteBondLineWithSpecifiedRGroup(e)}shiftCoordinates(e){this.atoms.shift(e)}rotateCoordinates(e){this.atoms.rotate(e)}getBondLines(){return this.bonds.getBondLines()}getAtomLines(){return this.atoms.atomLines}removeRGroups(e){this.rGroups.removeRGroups(e)}replaceRGroupWithAttachmentAtom(e,t){this.rGroups.replaceRGroupWithAttachmentAtom(e,t)}getAttachmentAtomByRGroupId(e){return this.rGroups.getAttachmentAtomIdByRGroupId(e)}shiftBonds(e){this.bonds.shift(e)}capRGroups(e,t){this.rGroups.capRGroups(e,t)}}var Bi=n(6956);class Vi{atoms;bonds;constructor(e,t,n){this.atoms=t,this.bonds=n,this.rGroupIdToAtomicIndexMap=e.getRGroupIdToAtomicIdxMap()}rGroupIdToAtomicIndexMap;rGroupBondPositionMap=new Map;getAtomicIdx(e){const t=this.rGroupIdToAtomicIndexMap.get(e);return null==t?null:t}removeRGroupsFromAtomBlock(e){e.forEach(e=>{if(null==this.rGroupIdToAtomicIndexMap.get(e))throw new Error(`Cannot find atomic index for R group ${e}`)});const t=Array.from(this.rGroupIdToAtomicIndexMap.entries()).filter(([t,n])=>e.includes(t)).map(([e,t])=>t);this.atoms.deleteAtoms(t)}removeRGroups(e){this.removeRGroupsFromAtomBlock(e),e.forEach(e=>{const t=this.replaceRGroupInBondsByDummy(e);this.rGroupBondPositionMap.set(e,t)})}replaceRGroupInBondsByDummy(e){const t=this.rGroupIdToAtomicIndexMap.get(e);if(this.rGroupBondPositionMap.has(e))throw new Error(`R group ${e} is already handled`);const n=this.bonds.getPositionsInBonds(t+1);if(0===n.length)throw new Error(`Cannot find position for R group ${e}`);if(n.length>1)throw new Error(`More than one position for R group ${e}`);const i=n[0];return this.bonds.replacePositionsInBondsByDummy([i]),this.bonds.removeAtomIdFromBonds(t+1),this.removeRGroupFromAtomicIdxMap(e,t),i}removeRGroupFromAtomicIdxMap(e,t){this.rGroupIdToAtomicIndexMap.delete(e);for(const[e,n]of this.rGroupIdToAtomicIndexMap)n>t&&this.rGroupIdToAtomicIndexMap.set(e,n-1)}deleteBondLineWithSpecifiedRGroup(e){const t=this.rGroupBondPositionMap.get(e);if(!t)throw new Error(`Cannot find position for R group ${e}`);const{bondLineIdx:n}=t;this.bonds.deleteBondLines([n]),this.rGroupBondPositionMap.delete(e),this.rGroupIdToAtomicIndexMap.delete(e),this.rGroupBondPositionMap.forEach(e=>{e.bondLineIdx>n&&(e.bondLineIdx-=1)})}replaceRGroupWithAttachmentAtom(e,t){const n=this.rGroupBondPositionMap.get(e);if(!n)throw new Error(`Cannot find position for R group ${e}`);const{bondLineIdx:i,nodeIdx:o}=n;this.bonds.bondedAtoms[i][o]=t}getAttachmentAtomIdByRGroupId(e){const t=this.rGroupBondPositionMap.get(e);if(!t)throw new Error(`Cannot find position for R group ${e}`);const{bondLineIdx:n,nodeIdx:i}=t;return this.bonds.bondedAtoms[n][(i+1)%2]}capRGroups(e,t){this.rGroupIdToAtomicIndexMap.forEach((n,i)=>{const o=e.find(e=>e.rGroupId===i)??e[i-1];o.isSimple?o.element===Bi.m?(this.removeRGroups([i]),this.deleteBondLineWithSpecifiedRGroup(i)):this.atoms.replaceRGroupSymbolByElement(n,o.element):this.capWithComplexGroup(n,o.smiles,t)})}capWithComplexGroup(e,t,n){const i=t.replace(/\[\*:\d+\]/g,"[Xe]"),o=n.get_mol(i);if(!o)throw new Error(`Cannot parse cap group SMILES: ${t}`);let s;try{s=o.get_v3Kmolblock()}finally{o.delete()}const r=Ot.getInstance(s),a=r.getAtomLines(),l=r.pairsOfBondedAtoms,c=r.getBondLines(),u=r.x,h=r.y,d=r.atomTypes;let m=-1;for(let e=0;e<d.length;e++)if("Xe"===d[e]){m=e;break}if(-1===m)throw new Error(`Cannot find placeholder atom in cap group SMILES: ${t}`);let p=-1;for(let e=0;e<l.length;e++){const[t,n]=l[e];if(t===m+1){p=n-1;break}if(n===m+1){p=t-1;break}}if(-1===p)throw new Error(`Cannot find attachment atom in cap group SMILES: ${t}`);const g=this.atoms.atomCoordinates[e],f=g.x-u[p],y=g.y-h[p],b=d[p];this.atoms.replaceRGroupSymbolByElement(e,b);const w=new Map;w.set(p+1,e+1);let v=this.atoms.count+1;for(let e=0;e<a.length;e++){if(e===m||e===p)continue;const t=u[e]+f,n=h[e]+y;this.atoms.appendAtomLine(a[e],t,n),w.set(e+1,v),v++}for(let e=0;e<l.length;e++){const[t,n]=l[e];if(t===m+1||n===m+1)continue;const i=w.get(t),o=w.get(n);this.bonds.appendBondLine(c[e],[i,o])}}}class Ui{coordinates=[];rawAtomLines=[];get count(){return this.coordinates.length}get atomCoordinates(){return this.coordinates}replaceRGroupSymbolByElement(e,t){this.rawAtomLines[e]=this.rawAtomLines[e].replace("R#",t)}appendAtomLine(e,t,n){this.rawAtomLines.push(e),this.coordinates.push({x:t,y:n})}deleteAtoms(e){this.coordinates=this.coordinates.filter((t,n)=>!e.includes(n)),this.rawAtomLines=this.rawAtomLines.filter((t,n)=>!e.includes(n))}shift(e){this.coordinates=this.coordinates.map(t=>{const n=t.x+e.x,i=t.y+e.y;if(isNaN(n)||isNaN(i))throw new Error(`Cannot shift coordinates by ${e.x}, ${e.y}`);return{x:n,y:i}})}rotate(e){this.coordinates=this.coordinates.map(t=>{const n=t.x,i=t.y,o=n*Math.cos(e)-i*Math.sin(e),s=n*Math.sin(e)+i*Math.cos(e);if(isNaN(o)||isNaN(s))throw new Error(`Cannot rotate coordinates by ${e}`);return{x:o,y:s}})}}class qi extends Ui{constructor(e){super(),this.rawAtomLines=e.getAtomLines(),this.coordinates=this.rawAtomLines.map(e=>({x:parseFloat(e.substring(0,10)),y:parseFloat(e.substring(10,20))}))}get atomLines(){return this.rawAtomLines.map((e,t)=>{const n=this.coordinates[t];return`${n.x.toFixed(4).padStart(10," ")}${n.y.toFixed(4).padStart(10," ")}${e.substring(20)}`})}}class Wi{bondedAtomPairs=[];rawBondLines=[];get count(){return this.bondedAtomPairs.length}get bondedAtoms(){return this.bondedAtomPairs}appendBondLine(e,t){this.rawBondLines.push(e),this.bondedAtomPairs.push(t)}deleteBondLines(e){this.rawBondLines=this.rawBondLines.filter((t,n)=>!e.includes(n)),this.bondedAtomPairs=this.bondedAtomPairs.filter((t,n)=>!e.includes(n))}getPositionsInBonds(e){const t=[];return this.bondedAtomPairs.forEach((n,i)=>{n.forEach((n,o)=>{n===e&&t.push({bondLineIdx:i,nodeIdx:o})})}),t}replacePositionsInBondsByDummy(e,t){null==t&&(t=-1),e.forEach(e=>{const{bondLineIdx:n,nodeIdx:i}=e;this.bondedAtomPairs[n][i]=t})}removeAtomIdFromBonds(e){this.bondedAtomPairs=this.bondedAtomPairs.map(t=>t.map(t=>t>e?t-1:t))}shift(e){this.bondedAtomPairs=this.bondedAtomPairs.map(t=>t.map(t=>t+e))}}class Yi extends Wi{constructor(e){super(),this.rawBondLines=e.getBondLines(),this.bondedAtomPairs=this.rawBondLines.map(e=>[parseInt(e.substring(0,3)),parseInt(e.substring(3,6))])}getBondLines(){return this.bondedAtomPairs.map((e,t)=>{if(e.some(e=>-1===e))throw new Error(`Bonded pair ${e} contains -1`);return`${e[0].toString().padStart(3," ")}${e[1].toString().padStart(3," ")}${this.rawBondLines[t].substring(6)}`})}}class ji extends Gi{constructor(e,t){super(t);const n=Ot.getInstance(e);this.atoms=new qi(n),this.bonds=new Yi(n),this.rGroups=new Vi(n,this.atoms,this.bonds),this.shiftMonomerToDefaultPosition()}}class Ki extends Ui{molfileHandler;constructor(e){super(),this.molfileHandler=e,this.rawAtomLines=e.getAtomLines(),this.coordinates=this.getCoordinates()}getCoordinates(){const e=this.molfileHandler.x,t=this.molfileHandler.y;return Array.from(e).map((e,n)=>({x:e,y:t[n]}))}get atomLines(){const e=/^(M V30 [^-]*)(-?\d+\.\d+)( )(-?\d+\.\d+)( -?\d+\.\d+.*)$/,t=/\sRGROUPS=\(\d+(\s+\d+)*\)/;return this.rawAtomLines.map((n,i)=>{const o=this.coordinates[i],s=o.x.toFixed(4)+"00",r=o.y.toFixed(4)+"00";return n.replace(e,(e,t,n,i,o,a)=>t+s+i+r+a).replace(t,"")})}replaceRGroupSymbolByElement(e,t){super.replaceRGroupSymbolByElement(e,t);const n=this.rawAtomLines[e].substring(3).split(" ");n.length>7&&(this.rawAtomLines[e]=`M ${n.slice(0,7).join(" ")}`)}}class zi extends Wi{molfileHandler;constructor(e){super(),this.molfileHandler=e,this.rawBondLines=e.getBondLines(),this.bondedAtomPairs=this.getBondedAtomPairs()}getBondedAtomPairs(){return this.molfileHandler.pairsOfBondedAtoms.map(e=>[e[0],e[1]])}getBondLines(){const e=/^(M\s+V30\s+\d+\s+\d+\s+)(\d+)(\s+)(\d+)(.*)$/;return this.bondedAtomPairs.map((t,n)=>{if(t.some(e=>-1===e))throw new Error(`Bonded pair ${t} contains -1`);return this.rawBondLines[n].replace(e,(e,n,i,o,s,r)=>`${n}${t[0]}${o}${t[1]}${r}`)})}}class Zi extends Gi{constructor(e,t){super(t);const n=Ot.getInstance(e);this.atoms=new Ki(n),this.bonds=new zi(n),this.rGroups=new Vi(n,this.atoms,this.bonds),this.shiftMonomerToDefaultPosition()}}class Xi{static getInstance(e,t){if(Ot.isMolfileV2K(e))return new ji(e,t);if(Ot.isMolfileV3K(e))return new Zi(e,t);throw new Error("Unsupported molfile version")}}class Qi{monomerSymbol;monomerIdx;helm;rdKitModule;monomerLib;molfileWrapper;capGroupInfo=[];static molfileV2KToV3KCache=new Map;constructor(e,t,n,i,o,s){this.monomerSymbol=e,this.monomerIdx=t,this.helm=n,this.rdKitModule=o,this.monomerLib=s;const r=this.getLibraryMonomerObject();let a=r.molfile;Ot.isMolfileV2K(a)&&(a=this.convertMolfileToV3KFormat(a,e,o)),this.molfileWrapper=Xi.getInstance(a,e),this.capGroupInfo=this.getCapGroupInfo(r),this.removeRGroups(n.bondedRGroupsMap[t]),this.capRemainingRGroups(),this.shiftCoordinates(i)}get atomCount(){return this.molfileWrapper.atomCount}get bondCount(){return this.molfileWrapper.bondCount}convertMolfileToV3KFormat(e,t,n){if(Qi.molfileV2KToV3KCache.has(e))return Qi.molfileV2KToV3KCache.get(e);let i=null;try{if(i=n.get_mol(e,JSON.stringify({mergeQueryHs:!0})),i){const t=i.get_v3Kmolblock();return Qi.molfileV2KToV3KCache.set(e,t),t}throw new Error(`Cannot convert ${t} to molV3000`)}finally{i?.delete()}}getLibraryMonomerObject(){const e=this.helm.getPolymerTypeByMonomerIdx(this.monomerIdx),t=this.monomerLib.getMonomer(e,this.monomerSymbol);if(!t)throw new Error(`Monomer ${this.monomerSymbol} is not found in the library`);return t}getCapGroupInfo(e){return e.rgroups.map((e,t)=>{const n=e.capGroupSmiles||e.capGroupSMILES;let i=e.label[1];if(!i||!parseInt(i)||isNaN(parseInt(i))){const e=n?.match(/\[\*:(\d)\]/);e&&e[1]&&(i=e[1])}i&&parseInt(i)&&!isNaN(parseInt(i))||(i=`${t+1}`);const o=n.replace(/(\[|\]|\*|:|\d)/g,"");return{element:o,smiles:n,isSimple:(s=o,/^[A-Z][a-z]?$/.test(s)),rGroupId:parseInt(i)};var s})}shiftCoordinates(e){this.molfileWrapper.shiftCoordinates(e)}getAtomLines(){return this.molfileWrapper.getAtomLines()}getBondLines(){return this.molfileWrapper.getBondLines()}removeRGroups(e){this.molfileWrapper.removeRGroups(e)}capRemainingRGroups(){this.molfileWrapper.capRGroups(this.capGroupInfo,this.rdKitModule)}replaceRGroupWithAttachmentAtom(e,t){this.molfileWrapper.replaceRGroupWithAttachmentAtom(e,t)}getAttachmentAtomByRGroupId(e){return this.molfileWrapper.getAttachmentAtomByRGroupId(e)}deleteBondLineWithSpecifiedRGroup(e){this.molfileWrapper.deleteBondLineWithSpecifiedRGroup(e)}shiftBonds(e){this.molfileWrapper.shiftBonds(e)}}class Ji{rdKitModule;monomerLib;constructor(e,t,n){this.rdKitModule=t,this.monomerLib=n,this.helm=new ki.f(e)}monomerWrappers=[];helm;addMonomer(e,t,n){if(e===pe.b9[ue.Hi.HELM])return;const i=this.monomerWrappers.length,o=new Qi(e,i,this.helm,n,this.rdKitModule,this.monomerLib);this.monomerWrappers.push(o)}getAtomNumberShifts(){const e=[];let t=0;return this.monomerWrappers.forEach(n=>{e.push(t),t+=n.getAtomLines().length}),e}restoreBondsBetweenMonomers(){this.helm.bondData.forEach(e=>{const t=e.map(e=>e.monomerIdx),n=e.map(e=>e.rGroupId),i=t.map(e=>this.monomerWrappers[e]),o=i[1].getAttachmentAtomByRGroupId(n[1]);i[0].replaceRGroupWithAttachmentAtom(n[0],o),i[1].deleteBondLineWithSpecifiedRGroup(n[1])})}compileToMolfile(){const e=[],t=[],n=this.getAtomNumberShifts();this.monomerWrappers.forEach((e,t)=>{e.shiftBonds(n[t])}),this.restoreBondsBetweenMonomers();const i=new Hi.Cg;for(const[n,o]of ee().enumerate(this.monomerWrappers)){const s=e.length,r=t.length;e.push(...n.getAtomLines()),t.push(...n.getBondLines());const a="RNA"==this.helm.getPolymerTypeByMonomerIdx(o)?Fe.o.NUCLEOTIDE:Fe.o.AA;i.set(o,{biotype:a,symbol:n.monomerSymbol,atoms:ee().count(s).take(n.atomCount).toArray(),bonds:ee().count(r).take(n.bondCount).toArray()})}const o=e.length,s=t.length;return{molfile:[this.getV3KHeader(o,s),this.getV3KAtomBlock(e),this.getV3KBondBlock(t),"M V30 END CTAB\nM END"].join("\n"),monomers:i}}getV3KHeader(e,t){return`\n Datagrok\n\n 0 0 0 0 0 0 0 0 0 0999 V3000\nM V30 BEGIN CTAB\nM V30 COUNTS ${e} ${t} 0 0 1`}getV3KAtomBlock(e){const t=/^(M V30 )(\d+)( .*)$/;return["M V30 BEGIN ATOM",...e.map((e,n)=>{const i=n+1;return e.replace(t,(e,t,n,o)=>t+i+o)}),"M V30 END ATOM"].join("\n")}getV3KBondBlock(e){const t=/^(M V30 )(\d+)( .*)$/;return["M V30 BEGIN BOND",...e.map((e,n)=>{const i=n+1;return e.replace(t,(e,t,n,o)=>t+i+o)}),"M V30 END BOND"].join("\n")}}class eo{constructor(e){this.molfileHandler=Ot.getInstance(e)}molfileHandler;get monomerSymbols(){return this.molfileHandler.atomTypes}getMonomerShifts(e){return{x:this.molfileHandler.x[e],y:this.molfileHandler.y[e]}}}class to{helmHelper;rdKitModule;monomerLib;constructor(e,t,n){this.helmHelper=e,this.rdKitModule=t,this.monomerLib=n}convertToSmiles(e){const t=e.dataFrame,n=this.getSmilesList(e),i=`smiles(${e.name})`,o=t?t.columns.getUnusedName(i):i;return r.Column.fromStrings(o,n.map(e=>null==e?"":e))}getSmilesList(e){return this.convertToMolfileV3KColumn(e).toList().map(e=>r.chem.convert(e,r.chem.Notation.MolBlock,r.chem.Notation.Smiles))}molV3KtoMolV3KOCL(e){try{if(!e)return"";return Fi.Molecule.fromMolfile(e).toMolfileV3().replace("STERAC1","STEABS")}catch(e){const[t,n]=(0,we.AP)(e);return Uo.logger.error(t,void 0,n),""}}getMolV3000ViaOCL(e,t){const n=e.map(e=>{if(null==e)return"";const t=e.get_v3Kmolblock();return e.delete(),t}),i=new Array(n.length),o=r.TaskBarProgressIndicator.create("Handling chirality...");for(let e=0;e<n.length;e++){i[e]=this.molV3KtoMolV3KOCL(n[e]);const t=e/n.length*100;o.update(t,`${t?.toFixed(2)}% of molecules completed`)}return o.close(),r.Column.fromStrings(t,i)}convertToRdKitBeautifiedMolfileColumn(e,t,n,i){const o=e.dataFrame,s=this.convertToMolfileV3KColumn(e).toList().map(e=>{if(""===e)return null;const t=n.get_mol(e);return t?(t.set_new_coords(),t.normalize_depiction(1),t.straighten_depiction(!0),t):null}),a=`molfile(${e.name})`,l=o?o.columns.getUnusedName(a):a;return t?this.getMolV3000ViaOCL(s,l):r.Column.fromStrings(l,s.map(e=>{if(null==e)return"";const t=e.get_v3Kmolblock();return e.delete(),t}))}convertToMolfileV3KColumn(e){const t=e.dataFrame,n=this.convertToMolfileV3K(e.toList()).map(e=>e.molfile),i=(0,Di.kA)(t,`molfileV3K(${e.name})`);return r.Column.fromList("string",i,n)}convertToMolfileV3K(e){const t=new Array(e.length);for(let n=0;n<e.length;++n){const i=e[n];if(!i){t[n]=Hi.vF.createEmpty();continue}let o;try{o=this.getPolymerMolfile(i)}catch(e){const[t,n]=(0,we.AP)(e);Uo.logger.error(t,void 0,n),o=Hi.vF.createEmpty()}t[n]=o}return t}getPolymerGraphColumn(e){const t=e.toList(),n=this.helmHelper.getMolfiles(t);return r.Column.fromStrings("mols",n)}getPolymerMolfile(e){const t=this.helmHelper.removeGaps(e),n=t.resHelm,i=new Map;for(const[e,n]of t.monomerMap?.entries()??[])i.set(n,e);const o=this.helmHelper.getMolfiles([n])[0],s=new eo(o),r=new Ji(n,this.rdKitModule,this.monomerLib);s.monomerSymbols.forEach((e,t)=>{const n=s.getMonomerShifts(t);r.addMonomer(e,t,n)});const a=r.compileToMolfile(),l=new Hi.Cg;for(const[e,t]of a.monomers.entries()){const n=i.get(e);l.set(n,t)}return new Hi.vF(a.molfile,l)}}var no=n(2738);class io{seqHelper;_column;_units;_notation;_defaultGapOriginal;_notationProvider=null;_tempReadForNotProvider=!1;get notationProvider(){return this._tempReadForNotProvider||(this._tempReadForNotProvider=!0,this._notationProvider=this._notationProvider??this._column.temp[me.j.notationProvider]??null),this._notationProvider}set notationProvider(e){this._notationProvider=e}_splitter=null;_refinerPromise=Promise.resolve();get refinerPromise(){return this._refinerPromise}runInnerDetector(){if(!this._column.temp.seqHandlerDetectorRun){this._column.temp.seqHandlerDetectorRun=!0;const e=r.Func.find({name:"detectMacromolecule",meta:{role:"semTypeDetector"}})[0];e&&e.applySync({col:this._column})}}constructor(e,t){if(this.seqHelper=t,e.type!==r.TYPE.STRING)throw new Error(`Unexpected column type '${e.type}', must be '${r.TYPE.STRING}'.`);this._column=e;let n=this._column.meta.units;if(!n&&(this.runInnerDetector(),n=this._column.meta.units,!n))throw new Error("Units are not specified in column");if(this._units=n,this._notation=this.getNotation(),[ue.Hi.BILN,ue.Hi.CUSTOM,ue.Hi.SEPARATOR].includes(this._notation)&&!this.column.getTag(ue.gp.separator)&&(this.runInnerDetector(),!this.column.getTag(ue.gp.separator)))throw new Error(`Separator tag '${ue.gp.separator}' is not set for notation '${this._notation}'.`);(this.isCustom()||this.isBiln())&&(this.notationProvider=this.column.temp[me.j.notationProvider]??null);const i=this.isFasta()?pe.b9[ue.Hi.FASTA]:this.isSeparator()?pe.b9[ue.Hi.SEPARATOR]:this.isHelm()?pe.b9[ue.Hi.HELM]:this.isCustom()||this.isBiln()?this.notationProvider?.defaultGapOriginal??pe.b9[ue.Hi.SEPARATOR]:void 0;if(null==i)throw new Error(`Unexpected defaultGapOriginal for notation '${this.notation}'`);if(this._defaultGapOriginal=i,!this.column.tags.has(ue.gp.aligned)||!this.column.tags.has(ue.gp.alphabet)||!this.column.tags.has(ue.gp.alphabetIsMultichar)&&!this.isHelm()&&this.alphabet===ue.YI.UN)if(this.isFasta())this.seqHelper.setUnitsToFastaColumn(this);else if(this.isSeparator()){const t=e.getTag(ue.gp.separator);this.seqHelper.setUnitsToSeparatorColumn(this,t)}else if(this.isHelm())this.seqHelper.setUnitsToHelmColumn(this);else{if(!this.isCustom()&&!this.isBiln())throw new Error(`Unexpected units '${this.column.meta.units}'.`);this.notationProvider?.setUnits(this)}if(!this.column.tags.has(ue.gp.alphabetIsMultichar))if(this.isHelm())this.column.setTag(ue.gp.alphabetIsMultichar,"true");else if(["UN"].includes(this.alphabet))throw new Error(`For column '${this.column.name}' of alphabet '${this.alphabet}' tag '${ue.gp.alphabetIsMultichar}' is mandatory.`);this.columnVersion=this.column.version,!this.isSeparator()||(this.isCustom()||this.isBiln())&&this.notationProvider||e.temp.seqHandlerRefined||(this._refinerPromise=this.refineSeparatorNotation(),e.temp.seqHandlerRefined=!0)}async refineSeparatorNotation(){const e=((e,t,n)=>{const i={};let o=!0,s=null;for(const t of e){const e=t?n(t):[];if(null==s?s=e.length:e.length!==s&&(o=!1),e.length>=3)for(const t of e)t in i||(i[t]=0),i[t]+=1}return{freq:i,sameLength:o}})([...new Set((this.column.length<100?ee().count(0).take(Math.min(100,this.column.length)).map(e=>this.column.get(e)):this.column.categories.slice(0,100)).map(e=>e?e.substring(0,500):"").filter(e=>0!==e.length))],0,e=>e.split(this.separator));let t=!1;const n=r.Func.find({meta:{role:"notationRefiner"}});for(const i of n)try{const n=i.prepare({col:this.column,stats:e,separator:this.separator}),o=(await n.call()).getOutputParamValue();t||=o}catch(e){console.error(e)}t&&(this._tempReadForNotProvider=!1,delete this.column.temp[me.j.seqHandler],this.column.fireValuesChanged())}static setTags(e){const t=e.column.meta.units;if([ue.Hi.FASTA,ue.Hi.SEPARATOR,ue.Hi.BILN].includes(t)){if(!e.column.getTag(ue.gp.alphabet)&&0===Object.keys(e.stats.freq).length)throw new Error("Alphabet is empty and not annotated.");let t=e.column.getTag(ue.gp.aligned);null==t&&(t=e.stats.sameLength||e.column.categories.slice(0,5).filter(e=>!!e).every(e=>e.length>100)?"SEQ.MSA":"SEQ",e.column.setTag(ue.gp.aligned,t));let n=e.column.getTag(ue.gp.alphabet);if(null==n&&(n=(0,Oe.pc)(e.stats.freq,ue.q7),e.column.setTag(ue.gp.alphabet,n)),n===ue.YI.UN){const t=Object.keys(e.stats.freq).length,n=Object.keys(e.stats.freq).some(e=>e.length>1);e.column.setTag(ue.gp.alphabetSize,t.toString()),e.column.setTag(ue.gp.alphabetIsMultichar,n?"true":"false")}}else if(t===ue.Hi.HELM){let t=e.column.getTag(ue.gp.alphabet);if(null==t){const n=ue.q7.map(e=>new no.aD(e.name,e.alphabet,.9));t=(0,Oe.p0)(e.stats.freq,n,e.defaultGapOriginal),e.column.setTag(ue.gp.alphabet,t)}}}get column(){return this._column}get length(){return this._column.length}get units(){return this._units}get notation(){return this._notation}get defaultGapOriginal(){return this._defaultGapOriginal}get separator(){const e=this.column.getTag(ue.gp.separator)??void 0;if(this.notation===ue.Hi.SEPARATOR&&null==e)throw new Error(`Separator is mandatory for column '${this.column.name}' of notation '${this.notation}'.`);return e}get aligned(){const e=this.column.getTag(ue.gp.aligned);if(!e&&(this.isFasta()||this.isSeparator()))throw new Error("Tag aligned not set");return e}get alphabet(){const e=this.column.getTag(ue.gp.alphabet);if(!e&&(this.isFasta()||this.isSeparator()))throw new Error("Tag alphabet not set");return e}get defaultBiotype(){return this.alphabet===ue.YI.RNA||this.alphabet===ue.YI.DNA?Fe.o.NUCLEOTIDE:Fe.o.AA}get helmCompatible(){return this.column.getTag(ue.gp.isHelmCompatible)}getAlphabetSize(){if(this.notation==ue.Hi.HELM||this.alphabet==ue.YI.UN){const e=this.column.getTag(ue.gp.alphabetSize);let t;if(e)t=parseInt(e);else{const e=this.stats;t=Object.keys(e.freq).length}return t}switch(this.alphabet){case ue.YI.PT:return 20;case ue.YI.DNA:case ue.YI.RNA:return 4;case"NT":return console.warn("Unexpected alphabet 'NT'."),4;default:throw new Error(`Unexpected alphabet '${this.alphabet}'.`)}}getAlphabetIsMultichar(){return this.notation===ue.Hi.HELM||this.alphabet===ue.YI.UN&&"true"===this.column.getTag(ue.gp.alphabetIsMultichar)}cached=!0;_splitted=null;columnVersion=null;getSplitted(e,t){if(this.cached&&void 0===t){this.column.version===this.columnVersion&&null!=this._splitted||(this.columnVersion=this.column.version,this._splitted=new Array(this.column.length));let t=this._splitted[e]?this._splitted[e].deref():void 0;if(!t){const n=this.column.get(e);t=this.splitter(n),this._splitted[e]=new WeakRef(t)}return t}{const n=this.column.get(e);return this.getSplitter(t)(n)}}getMonomerAtPosition(e,t,n){if(this.isCanonicalAlphabet&&this.isFasta()&&!this.getAlphabetIsMultichar()){const i=(this.column.get(e)??"")[t];return n?i===pe.b9[ue.Hi.FASTA]?pe._S:i??pe._S:i??""}const i=this.getSplitted(e);return t<0||t>=i.length?this.defaultGapOriginal:n?i.getCanonical(t):i.getOriginal(t)}getMonomersAtPosition(e,t){const n=this.column.length,i=new Array(n).fill(pe._S);if(this.isCanonicalAlphabet&&this.isFasta()&&!this.getAlphabetIsMultichar()){const o=this.column.categories,s=this.column.getRawData();for(let r=0;r<n;r++){const n=o[s[r]]??"";if(e<n.length){const o=n[e];i[r]=t?o===pe.b9[ue.Hi.FASTA]?pe._S:o??pe._S:o??""}}}else for(let o=0;o<n;o++){const n=this.getSplitted(o);e>=0&&e<n.length&&(i[o]=t?n.getCanonical(e):n.getOriginal(e))}return i}getValue(e,t){return this.column.get(e),new me.C(e,this)}getHelm(e){let t;const n=this.column.get(e);return t=this.notation===ue.Hi.HELM?n:this.notation===ue.Hi.CUSTOM||this.notation===ue.Hi.BILN?this.notationProvider.getHelm(n,{}):this.getConverter(ue.Hi.HELM)(n),t}_stats=null;get isCanonicalAlphabet(){const e=this.alphabet;return e===ue.YI.DNA||e===ue.YI.RNA||e===ue.YI.PT}get stats(){if(null==this._stats){const e={};let t=!0,n=null;const i=this.column.length;for(let o=0;o<i;++o){const i=this.getSplitted(o);null==n?n=i.length:i.length!==n&&(t=!1);for(let t=0;t<i.length;++t){const n=i.getCanonical(t);n in e||(e[n]=0),e[n]+=1}}this._stats={freq:e,sameLength:t}}return this._stats}_maxLength=null;get maxLength(){return null==this._maxLength&&(this._maxLength=0===this.column.length?0:ee().count(0).take(this.column.length).map(e=>this.getSplitted(e).length).reduce((e,t)=>e>t?e:t,0)),this._maxLength}_posList=null;get posList(){if(null==this._posList){const e=this.column.getTag(ue.gp.positionNames);this._posList=e?e.split(ue.z1).map(e=>e.trim()):ee().count(1).take(this.maxLength).map(e=>e.toString()).toArray()}return this._posList}isFasta(){return this.notation===ue.Hi.FASTA}isSeparator(){return this.notation===ue.Hi.SEPARATOR||!!this.separator}isFastaOrSeparator(){return this.isFasta()||this.isSeparator()}isHelm(){return this.notation===ue.Hi.HELM}isCustom(){return this.notation===ue.Hi.CUSTOM}isBiln(){return this.notation===ue.Hi.BILN}isRna(){return this.alphabet===ue.YI.RNA}isDna(){return this.alphabet===ue.YI.DNA}isPeptide(){return this.alphabet===ue.YI.PT}isMsa(){return!!this.aligned&&this.aligned.toUpperCase().includes("MSA")}isHelmCompatible(){return"true"===this.helmCompatible}isGap(e){return!e||e===this._defaultGapOriginal}getNotation(){if(this.units.toLowerCase().startsWith(ue.Hi.FASTA))return ue.Hi.FASTA;if(this.units.toLowerCase().startsWith(ue.Hi.SEPARATOR))return ue.Hi.SEPARATOR;if(this.units.toLowerCase().startsWith(ue.Hi.HELM))return ue.Hi.HELM;if(this.units.toLowerCase().startsWith(ue.Hi.CUSTOM))return ue.Hi.CUSTOM;if(this.units.toLowerCase().startsWith(ue.Hi.BILN))return ue.Hi.BILN;throw new Error(`Column '${this.column.name}' has unexpected notation '${this.units}'.`)}getHelmWrappers(){return[this.isDna()||this.isRna()||this.isHelmCompatible()?"RNA1{":"PEPTIDE1{",this.isDna()?"d(":this.isRna()?"r(":"",this.isDna()||this.isRna()?")p":"","}$$$$"]}getNewColumn(e,t,n,i){const o=this.column,s=e.toLowerCase()+"("+o.name+")",a=n??o.dataFrame?.columns.getUnusedName(s)??s,l=r.Column.fromList("string",a,i??new Array(this.column.length).fill(""));if(l.semType=r.SEMTYPE.MACROMOLECULE,l.meta.units=e,e===ue.Hi.SEPARATOR){if(!t)throw new Error(`Notation '${ue.Hi.SEPARATOR}' requires separator value.`);l.setTag(ue.gp.separator,t)}l.setTag(r.TAGS.CELL_RENDERER,e===ue.Hi.HELM?"helm":"sequence");const c=o.getTag(ue.gp.aligned);c&&l.setTag(ue.gp.aligned,c);let u=o.getTag(ue.gp.alphabet);u||this.notation!==ue.Hi.HELM||e===ue.Hi.HELM||(u=ue.YI.UN),null!=u&&l.setTag(ue.gp.alphabet,u);let h=o.getTag(ue.gp.alphabetSize);null!=u&&h&&l.setTag(ue.gp.alphabetSize,h);const d=o.getTag(ue.gp.alphabetIsMultichar);return null!=u&&void 0!==d&&l.setTag(ue.gp.alphabetIsMultichar,d),e==ue.Hi.HELM&&(h=this.getAlphabetSize().toString(),l.setTag(ue.gp.alphabetSize,h)),e===ue.Hi.BILN&&(l.setTag(ue.gp.separator,"-"),l.meta.units=ue.Hi.SEPARATOR),l}getNewColumnFromList(e,t){return this.getNewColumn(this.notation,this.separator,e,t)}static unitsStringIsValid(e){return e=e.toLowerCase(),[ue.Hi.FASTA,ue.Hi.SEPARATOR,ue.Hi.HELM].some(t=>e.startsWith(t.toLowerCase()))}static getNewColumnFromParams(e,t,n){if(!io.unitsStringIsValid(n))throw new Error("Invalid format of 'units' parameter");const i=r.Column.fromList("string",t,new Array(e).fill(""));return i.semType=r.SEMTYPE.MACROMOLECULE,i.meta.units=n,i}get splitter(){return null==this._splitter&&(this._splitter=this.getSplitter()),this._splitter}getSplitter(e){let t=null;if(t=this.notationProvider?this.notationProvider.splitter:null,t)return t;if(this.units.toLowerCase().startsWith(ue.Hi.FASTA))return null===this.column.getTag(ue.gp.alphabet)||this.getAlphabetIsMultichar()?ue.J9:Oe.tm;if(this.units.toLowerCase().startsWith(ue.Hi.SEPARATOR))return(0,ue.dh)(this.separator,e);if(this.units.toLowerCase().startsWith(ue.Hi.HELM))return ue.qp;throw new Error(`Unexpected units ${this.units} .`)}split(e){return this.splitter(e)}getDistanceFunctionName(){if(!this.isFasta())throw new Error("Only FASTA notation is supported");if(this.isMsa())return ce.Z.HAMMING;switch(this.alphabet){case ue.YI.DNA:case ue.YI.RNA:case ue.YI.PT:}return ce.Z.LEVENSHTEIN}getDistanceFunction(){return ce.V[this.getDistanceFunctionName()]()}async checkHelmCompatibility(){if(this.column.tags.has(ue.gp.isHelmCompatible))return"true"===this.column.getTag(ue.gp.isHelmCompatible);const e=(await(0,ye.pj)()).getMonomerLib().getMonomerSymbolsByType("PEPTIDE"),t=new Set(e),n=((0,ue.dh)(this.separator),new Set),i=this.column.length,o=this.column.getRawData();for(let e=0;e<i;++e){const i=o[e];if(!(i in n)){n.add(i);const o=this.getSplitted(e);for(let e=0;e<o.length;++e){const n=o.getCanonical(e);if(!t.has(n))return this.column.setTag(ue.gp.isHelmCompatible,"false"),!1}}}return this.column.setTag(ue.gp.isHelmCompatible,"true"),!0}toFasta(e){return e===ue.Hi.FASTA}toSeparator(e){return e===ue.Hi.SEPARATOR}toHelm(e){return e===ue.Hi.HELM}convertHelmToFastaSeparator(e,t,n,i){i||(i=this.toFasta(t)?pe.b9[ue.Hi.FASTA]:pe.b9[ue.Hi.SEPARATOR]),n||(n=this.toFasta(t)?"":this.separator);const o=e.startsWith("RNA"),s=(0,ue.qp)(e),r=[];for(let e=0;e<s.length;++e){let n=s.getOriginal(e);if(o&&(n=n.replace(de.EK,"$1")),n===pe.b9[ue.Hi.HELM])r.push(i);else if(this.toFasta(t)&&n.length>1){const e="["+n+"]";r.push(e)}else r.push(n)}return r.join(n)}convert(e,t){if(this.isCustom()&&e===ue.Hi.HELM){if(!this.notationProvider||!this.notationProvider.getHelm)throw new Error("Notation provider with getHelm function is required for custom notation conversion.");const n=this.getNewColumn(e,t);return n.init(e=>{const t=this.column.get(e);return this.notationProvider.getHelm(t,{})}),n}{const n=this.getJoiner({notation:e,separator:t}),i=this.getNewColumn(e,t);return i.init(e=>{const t=this.getSplitted(e);return n(t)}),i}}getRegion(e,t,n){const i=this.getNewColumn(this.notation,this.separator);i.name=n;const o=e??0,s=t??this.maxLength-1,r=this.getJoiner(),a=s-o+1,l=pe.b9[this.notation];i.init(e=>{const t=this.getSplitted(e),n=new Array(a);for(let e=0;e<a;++e){const i=o+e;n[e]=i<t.length?t.getOriginal(i):l}return r(new Oe.Mu(n,l))});const c=e=>{const t=e.split(",").map(e=>e.trim()),n=new Array(a);for(let e=0;e<a;++e){const i=o+e;n[e]=i<t.length?t[i]:"?"}return n.join(ue.z1)},u=this.column.getTag(ue.gp.positionNames);u&&i.setTag(ue.gp.positionNames,c(u));const h=this.column.getTag(ue.gp.positionLabels);return h&&i.setTag(ue.gp.positionLabels,c(h)),i}_joiner=void 0;get joiner(){return this._joiner||(this._joiner=this.getJoiner()),this._joiner}getJoiner(e){const t=e?e.notation:this.notation,n=e?e.separator:this.separator;let i;const o=this;switch(t){case ue.Hi.FASTA:i=function(e){return o.joinToFasta(e,o.isHelm())};break;case ue.Hi.SEPARATOR:if(!n)throw new Error(`Separator is mandatory for notation '${t}'.`);i=function(e){return oo(e,n,o.isHelm())};break;case ue.Hi.HELM:{const e=o.alphabet===ue.YI.DNA||o.alphabet===ue.YI.RNA,t=o.getHelmWrappers();i=function(n){return so(n,t,e)};break}case ue.Hi.BILN:i=function(e){return ro(e)};break;default:throw new Error(`Unexpected notation '${t}'.`)}return i}getConverter(e,t=void 0){if(e===ue.Hi.SEPARATOR&&!t)throw new Error(`Target separator is not specified for target units '${ue.Hi.SEPARATOR}'.`);const n=this;if(e===ue.Hi.FASTA)return function(e){return n.convertToFasta(e)};if(e===ue.Hi.HELM)return function(e){return n.convertToHelm(e)};if(e===ue.Hi.SEPARATOR)return function(e){return n.convertToSeparator(e,t)};if(e===ue.Hi.BILN)return function(e){return n.convertToBiln(e)};throw new Error("Unexpected target units '"+e+"'.")}static forColumn(e,t){let n=e.temp[me.j.seqHandler];return n&&n.columnVersion===e.version||(n=e.temp[me.j.seqHandler]=new io(e,t)),n}joinToFasta(e,t){const n=new Array(e.length);for(let i=0;i<e.length;++i){const o=e.getOriginal(i);let s=e.getOriginal(i);t&&(s=s.replace(de.EK,"$1")),o===pe._S?s=pe.b9[ue.Hi.FASTA]:!t||o!==de.q7&&o!==de.WS&&o!==de.rM?o===de.q7?s="":s.length>1&&(s="["+s+"]"):s="",n[i]=s}return n.join("")}convertToFasta(e){const t=this.splitter,n=this.isHelm()?this.splitterAsHelmNucl(e):t(e);return this.joinToFasta(n,this.isHelm())}convertToSeparator(e,t){return oo(this.isHelm()?this.splitterAsHelmNucl(e):this.splitter(e),t,this.isHelm())}convertToHelm(e){if(this.notation==ue.Hi.HELM)return e;if(this.isCustom()&&this.notationProvider?.getHelm)return this.notationProvider.getHelm(e,{});const t=this.getHelmWrappers(),n=this.isDna()||this.isRna();return so(this.splitter(e),t,n)}convertToBiln(e){return this.notation==ue.Hi.BILN?e:ro(this.splitter(e))}splitterAsHelmNucl(e){const t=this.splitter(e),n=new Array(t.length),i=e.startsWith("DNA"),o=e.startsWith("RNA");for(let e=0;e<t.length;++e){let s=t.getOriginal(e);(i||o)&&(s=s.replace(de.EK,"$1"),s!==de.q7&&s!==de.WS&&s!==de.rM||(s=null)),n[e]=s||null}return new Oe.Mu(n.filter(e=>!!e),pe.b9[ue.Hi.HELM])}getRendererBack(e,t){const n=this.column.temp;let i=n.rendererBack;return i||(i=n.rendererBack=this.notationProvider?.createCellRendererBack(e,t)),i}}function oo(e,t,n){const i=[];for(let t=0;t<e.length;++t){const o=e.getCanonical(t);let s=e.getOriginal(t);n&&(s=s.replace(de.EK,"$1")),o!==pe._S?(!n||o!==de.q7&&o!==de.WS&&o!==de.rM)&&o!==de.q7&&i.push(s):i.push(pe.b9[ue.Hi.SEPARATOR])}return i.join(t)}function so(e,t,n){if(e.graphInfo&&(e.graphInfo.connections?.length??0)>0){const i=n?"RNA":"PEPTIDE",o="$$$",s=e.graphInfo.disjointSeqStarts,r=t[1],a=t[2],l=[];for(let t=0;t<s.length;t++){const o=s[t],c=t+1<s.length?s[t+1]:e.length,u=new Array(c-o);for(let t=o;t<c;++t){const i=e.getCanonical(t);let s=i;i===pe._S?s=pe.b9[ue.Hi.HELM]:(n&&(s=s.replace(de.EK,"$1")),s=1===s.length?`${r}${s}${a}`:`${r}[${s}]${a}`),u[t-o]=s}l.push(`${i}${t+1}{${u.join(".")}}`)}return`${l.join("|")}$${e.graphInfo.connections.map(e=>`${i}${e.seqIndex1+1},${i}${e.seqIndex2+1},${e.monomerIndex1+1}:R${e.rGroup1}-${e.monomerIndex2+1}:R${e.rGroup2}`).join("|")}${o}V2.0`}{const[i,o,s,r]=t,a=new Array(e.length);for(let t=0;t<e.length;++t){const i=e.getCanonical(t);let r=i;i===pe._S?r=pe.b9[ue.Hi.HELM]:(n&&(r=r.replace(de.EK,"$1")),r=1===r.length?`${o}${r}${s}`:`${o}[${r}]${s}`),a[t]=r}return`${i}${a.join(".")}${r}`}}function ro(e){const t=e=>e&&(e.includes("-")||e.includes("*")||e.includes("[R"));if(e.graphInfo&&(e.graphInfo.connections?.length??0)>0){const n=e.graphInfo.disjointSeqStarts,i=new Array(e.length);for(let n=0;n<e.length;++n){const o=e.getCanonical(n);t(o)?i[n]=`[${o}]`:i[n]=o}for(let t=0;t<e.graphInfo.connections.length;t++){const o=e.graphInfo.connections[t],s=`${t+1}`,r=o.seqIndex1,a=o.seqIndex2,l=n[r]+o.monomerIndex1,c=n[a]+o.monomerIndex2,u=`${i[l]}(${s},${o.rGroup1})`,h=`${i[c]}(${s},${o.rGroup2})`;i[l]=u,i[c]=h}return n.map((t,o)=>{const s=o+1<n.length?n[o+1]:e.length;return i.slice(t,s).join("-")}).join(".")}{const n=new Array(e.length);for(let i=0;i<e.length;++i){const o=e.getCanonical(i);t(o)?n[i]=`[${o}]`:n[i]=o}return n.join("-")}}class ao{libHelper;rdKitModule;constructor(e,t){this.libHelper=e,this.rdKitModule=t}getSeqHandler(e){return io.forColumn(e,this)}getSeqMonomers(e){const t=this.getSeqHandler(e);return Object.keys(t.stats.freq)}async getHelmToMolfileConverter(e){const t=await(0,Dt.b2)();return new to(t,this.rdKitModule,e)}helmToAtomicLevelSingle(e,t,n,i=!0){if(!e)return Hi.vF.createEmpty();const o=t.convertToMolfileV3K([e])[0];if(!o||!o.molfile)return Hi.vF.createEmpty();let s=null;try{let e=o.molfile;if(i){if(s=this.rdKitModule.get_mol(e),!s)return Hi.vF.createEmpty();s.set_new_coords(),s.normalize_depiction(1),s.straighten_depiction(!0),e=s.get_v3Kmolblock()}return n&&(e=t.molV3KtoMolV3KOCL(e)),new Hi.vF(e,o.monomers)}catch(e){const[t,n]=(0,we.AP)(e);return Uo.logger.error(t,void 0,n),Hi.vF.createEmpty()}finally{s?.delete()}}async helmToAtomicLevel(e,t,n,i){const s=i??this.libHelper.getMonomerLib(),a=e.dataFrame,l=(0,Di.qj)(a,e.name),c=await this.getHelmToMolfileConverter(s),u=e.toList(),h=new Array(e.length),d=r.Func.find({package:"Chem",name:"beautifyMols"})[0],m=r.Func.find({package:"Chem",name:"convertToV3KViaOCL"})[0];for(let n=0;n<e.length;n++)h[n]=this.helmToAtomicLevelSingle(u[n],c,t&&!m,!d).molfile;if(d){const t=await d.apply({mols:h});if(t&&Array.isArray(t)&&t.length===e.length)for(let n=0;n<e.length;n++)t[n]&&(h[n]=t[n])}if(t&&m){const t=await m.apply({mols:h});if(t&&Array.isArray(t)&&t.length===e.length)for(let n=0;n<e.length;n++)t[n]&&(h[n]=t[n]);else o.shell.warning("OCL function returned an unexpected result")}const p=r.Column.fromStrings(l,h);return p.semType=r.SEMTYPE.MOLECULE,p.meta.units=r.UNITS.Molecule.MOLBLOCK,p.setTag(".sequence-src-col",e.name),{molCol:p,warnings:[]}}setUnitsToFastaColumn(e){if(e.column.semType!==r.SEMTYPE.MACROMOLECULE||e.column.meta.units!==ue.Hi.FASTA)throw new Error(`The column of notation '${ue.Hi.FASTA}' must be '${r.SEMTYPE.MACROMOLECULE}'.`);e.column.meta.units=ue.Hi.FASTA,io.setTags(e)}setUnitsToSeparatorColumn(e,t){if(e.column.semType!==r.SEMTYPE.MACROMOLECULE)throw new Error(`The column of notation '${ue.Hi.SEPARATOR}' must be '${r.SEMTYPE.MACROMOLECULE}'.`);if(!t)throw new Error(`The column of notation '${ue.Hi.SEPARATOR}' must have the separator tag.`);e.column.meta.units=ue.Hi.SEPARATOR,e.column.setTag(ue.gp.separator,t),io.setTags(e)}setUnitsToHelmColumn(e){if(e.column.semType!==r.SEMTYPE.MACROMOLECULE)throw new Error(`The column of notation '${ue.Hi.HELM}' must be '${r.SEMTYPE.MACROMOLECULE}'`);e.column.meta.units=ue.Hi.HELM,io.setTags(e)}}async function lo(e){let t="";try{if(!e||!e.value)return t="No sequence provided",{errorText:t,mol:""};if(!(e.cell&&e.cell.dart&&e.cell.dataFrame&&e.cell.column))return t="Atomic level conversion requeires a sequence column",{errorText:t,mol:""};const n=(await Wo.getSeqHelper()).getSeqHandler(e.cell.column);if(!n)return t="No sequence handler found",{errorText:t,mol:""};let i=50;if(n.isHelm()){const t=n.getSplitted(e.cell.rowIndex);t.graphInfo?.polymerTypes?.some(e=>"RNA"!==e)||(i=150)}if((n.getSplitted(e.cell.rowIndex)?.length??100)>i)return t="Maximum number of monomers is "+i,{errorText:t,mol:""};const o=r.Column.fromStrings("singleVal",[e.value]),s=r.DataFrame.fromColumns([o]);Object.entries(e.cell.column.tags).forEach(([e,t])=>{o.setTag(e,t)}),e.cell.column.temp[me.j.notationProvider]&&(o.temp[me.j.notationProvider]=e.cell.column.temp[me.j.notationProvider]);const a=n.getSplitted(e.cell.rowIndex),l=(a.graphInfo?.connections?.length??0)>0||n.units===ue.Hi.CUSTOM,c=n.isHelm()&&new Set(a.graphInfo?.polymerTypes??[]).size>1;if(await Wo.toAtomicLevel(s,o,l||c,!1),s.columns.length<2)return t="No structure generated",{errorText:t,mol:""};const u=s.columns.byIndex(1).get(0);return u?{errorText:"",mol:u}:(t="No structure generated",{errorText:t,mol:""})}catch(e){Uo.logger.error(e)}return t="No Structure generated",{errorText:t,mol:""}}const co="#333333",uo="rgba(60, 177, 115, 0.1)",ho="rgba(240, 240, 240, 0.5)",mo="rgba(100, 100, 100, 0.3)";class po{constructor(e=yo.DEFAULT_TRACK_HEIGHT,t=yo.MIN_TRACK_HEIGHT,n=""){this.ctx=null,this.visible=!0,this.title="",this.tooltipEnabled=!1,this.tooltipContent=null,this.height=e,this.defaultHeight=e,this.minHeight=t,this.title=n}init(e){this.ctx=e}getMonomerAt(e,t,n){return null}enableTooltip(e){this.tooltipEnabled=e}setTooltipContentGenerator(e){this.tooltipContent=e}getTooltipContent(e,t){if(!this.tooltipEnabled||!this.tooltipContent)return null;const n=this.getPositionData(e)??new Map;return this.tooltipContent(e,t,n)}getPositionData(e){return null}setVisible(e){this.visible=e}getHeight(){return this.visible?this.height:0}getDefaultHeight(){return this.defaultHeight}getMinHeight(){return this.minHeight}setHeight(e){this.height=Math.max(this.minHeight,e)}resetHeight(){this.height=this.defaultHeight}isVisible(){return this.visible}setTitle(e){this.title=e}getTitle(){return this.title}}class go extends po{constructor(e=new Map,t=yo.DEFAULT_TRACK_HEIGHT,n="",i="WebLogo"){super(t,yo.DEFAULT_TRACK_HEIGHT,i),this.data=new Map,this.monomerLib=null,this.biotype="HELM_AA",this.hoveredPosition=-1,this.hoveredMonomer=null,this.data=e,this.visible=e.size>0}setHovered(e,t){this.hoveredPosition=e,this.hoveredMonomer=t}getPositionData(e){return this.data.get(e)||null}setupDefaultTooltip(){this.enableTooltip(!0),this.setTooltipContentGenerator((e,t,n)=>this.createTooltipContent(e,t,n))}createFrequencyTable(e){let t;switch(this.biotype){case"HELM_BASE":case"HELM_SUGAR":case"HELM_NUCLETIDE":t=Fe.o.NUCLEOTIDE;break;default:t=Fe.o.AA}const n=Array.from(e.values()).reduce((e,t)=>e+t,0),i={};for(const[t,o]of e.entries())i[t]=Math.max(1,Math.round(o/n*100));const o=(0,Si.F)(i,t,this.monomerLib);return o.style.fontSize="11px",o.style.marginTop="4px",o}createTooltipContent(e,t,n){const i=[];if(i.push(s.divText(`Position: ${e+1}`,{style:{fontWeight:"bold",marginBottom:"6px",fontSize:"13px"}})),t&&(i.push(s.divText(`Monomer: ${t}`,{style:{marginBottom:"6px",fontSize:"13px"}})),n.has(t)&&i.push(s.divText(`${(100*n.get(t)).toFixed(2)}%`,{style:{marginBottom:"6px",fontSize:"13px"}}))),n&&n.size>0){const e=this.createFrequencyTable(n);i.push(e)}else i.push(s.divText("No data available",{style:{fontStyle:"italic",color:"#666"}}));const o=s.divV(i);return o.style.maxHeight="80vh",o}setMonomerLib(e){this.monomerLib=e}setBiotype(e){this.biotype=e}getMonomerAt(e,t,n){if(!this.ctx||!this.visible||0===this.data.size)return null;const i=this.data.get(n);if(!i||0===i.size)return null;const o=t,s=Array.from(i.entries()).sort((e,t)=>t[1]-e[1]),r=s.reduce((e,[t,n])=>e+n,0),a=this.height;let l=0;for(const[e,t]of s){const n=t*a/r;if(o>=l&&o<l+n)return e;l+=n}return null}updateData(e){this.data=e,this.visible=e.size>0}draw(e,t,n,i,o,s,r,a){if(!this.ctx||!this.visible||0===this.data.size)return;const l=Math.floor(n/s),c=i-4,u=t+2;for(let h=0;h<l;h++)this.drawWebLogoColumn(h,e,t,n,i,o,s,r,a,u,c)}drawWebLogoColumn(e,t,n,i,o,s,r,a,l,c,u){const h=s+e-1;if(h<0||h>=a)return;const d=this.data.get(h);if(!d||0===d.size)return;const m=t+e*r,p=r-2;s+e===l&&(this.ctx.fillStyle=uo,this.ctx.fillRect(m,n,r,o)),this.ctx.fillStyle=ho,this.ctx.fillRect(m+1,c,p,u),this.drawLettersInColumn(h,m,p,c,u,d),this.drawColumnBorder(m,c,p,u)}drawLettersInColumn(e,t,n,i,o,s){const r=Array.from(s.entries()).sort((e,t)=>t[1]-e[1]),a=r.reduce((e,[t,n])=>e+n,0),l=Math.min(1,o/(a*o));let c=i;const u=i+o;for(const[i,s]of r){const r=s*o*l,a=Math.max(4,Math.floor(r));if(a<4)continue;const h=e===this.hoveredPosition&&i===this.hoveredMonomer,d=Math.min(a,u-c);if(d<4)break;this.drawLetter(i,t+1,c,n,d,h),c+=d}}drawColumnBorder(e,t,n,i){this.ctx.strokeStyle=mo,this.ctx.lineWidth=1,this.ctx.strokeRect(e+1,t,n,i)}drawLetter(e,t,n,i,o,s=!1){if(!this.ctx)return;const r=this.getMonomerBackgroundColor(e),a=this.getMonomerTextColor(e);this.ctx.fillStyle=r,this.ctx.fillRect(t,n,i,o),s&&(this.ctx.shadowColor="rgba(255, 255, 255, 0.8)",this.ctx.shadowBlur=8,this.ctx.strokeStyle="white",this.ctx.lineWidth=2,this.ctx.strokeRect(t,n,i,o),this.ctx.shadowBlur=0),this.drawLetterSeparators(t,n,i,o),this.drawLetterText(e,t,n,i,o,a)}drawLetterSeparators(e,t,n,i){this.ctx.strokeStyle="rgba(255, 255, 255, 0.4)",this.ctx.lineWidth=1,t+i<t+this.ctx.canvas.height&&(this.ctx.beginPath(),this.ctx.moveTo(e,t+i),this.ctx.lineTo(e+n,t+i),this.ctx.stroke())}drawLetterText(e,t,n,i,o,s){const r=Math.min(.8*o,.8*i);r>=7&&(this.ctx.fillStyle=s,this.ctx.font=`bold ${r}px Roboto, Roboto Local`,this.ctx.textAlign="center",this.ctx.textBaseline="middle",this.ctx.fillText(e,t+i/2,n+o/2))}getMonomerBackgroundColor(e){if(this.monomerLib)try{const t=this.monomerLib.getMonomerColors(this.biotype,e);if(t&&t.backgroundcolor)return t.backgroundcolor}catch(e){console.warn("Error getting background color from monomerLib:",e)}return"#CCCCCC"}getMonomerTextColor(e){const t=this.getMonomerBackgroundColor(e);try{const e=r.Color.fromHtml(t),n=r.Color.getContrastColor(e);return r.Color.toHtml(n)}catch(e){return console.warn("Error calculating contrast color:",e),"#000000"}}}class fo extends po{constructor(e,t=yo.DEFAULT_TRACK_HEIGHT,n="default",i="Conservation"){super(t,yo.MIN_TRACK_HEIGHT,i),this.data=e,this.colorScheme=n,this.visible=e.length>0}updateData(e){this.data=e,this.visible=e.length>0}draw(e,t,n,i,o,s,r,a){if(!this.ctx||!this.visible||0===this.data.length)return;const l=Math.floor(n/s);for(let n=0;n<l;n++){const l=o+n;if(l>r)break;const c=e+n*s,u=s,h=c+u/2;l-1<this.data.length&&(this.drawConservationBar(l-1,c,u,h,t,i),l===a&&(this.ctx.fillStyle=uo,this.ctx.fillRect(c,t,u,i)))}}drawConservationBar(e,t,n,i,o,s){if(!this.ctx)return;const r=this.data[e];this.ctx.fillStyle=ho,this.ctx.fillRect(t+2,o,n-4,s);let a="#3CB173";if("default"===this.colorScheme)r<.5?a="#E74C3C":r<.75&&(a="#F39C12");else if("rainbow"===this.colorScheme)a=r<.2?"#E74C3C":r<.4?"#FF7F00":r<.6?"#FFFF00":r<.8?"#00FF00":"#0000FF";else if("heatmap"===this.colorScheme){const e=Math.round(255*r);a=`rgb(255, ${e}, ${e})`}const l=r*s;this.ctx.fillStyle=a,this.ctx.fillRect(t+2,o+s-l,n-4,l),this.ctx.strokeStyle=mo,this.ctx.lineWidth=1,this.ctx.strokeRect(t+2,o,n-4,s),n>20&&(this.ctx.fillStyle=co,this.ctx.font="9px monospace",this.ctx.textAlign="center",this.ctx.textBaseline="middle",this.ctx.fillText(`${Math.round(100*r)}%`,i,o+s/2))}}const yo={TITLE_HEIGHT:16,TRACK_GAP:4,DOTTED_CELL_HEIGHT:30,SLIDER_HEIGHT:8,TOP_PADDING:5,DEFAULT_TRACK_HEIGHT:45,MIN_TRACK_HEIGHT:35,ANNOTATION_TRACK_HEIGHT:20},bo={BASE:yo.DOTTED_CELL_HEIGHT+yo.SLIDER_HEIGHT,WITH_TITLE:function(){return this.BASE+yo.TITLE_HEIGHT+yo.TRACK_GAP},WITH_WEBLOGO:function(){return this.WITH_TITLE()+yo.DEFAULT_TRACK_HEIGHT+yo.TRACK_GAP},WITH_BOTH:function(){return this.WITH_WEBLOGO()+yo.DEFAULT_TRACK_HEIGHT+yo.TRACK_GAP}};class wo{constructor(e,t){this.gridColumn=t,this.canvas=null,this.ctx=null,this.tracks=new Map,this.currentHoverPosition=-1,this.currentHoverTrack=null,this.currentHoverMonomer=null,this.previousHoverPosition=-1,this.previousHoverTrack=null,this.previousHoverMonomer=null,this.dataFrame=null,this.seqHandler=null,this.seqColumn=null,this.onSelectionCallback=null,this.trackButtons=[],this.userSelectedTracks=null,this.config={x:e.x||0,y:e.y||0,width:e.width||0,height:e.height||0,windowStartPosition:e.windowStartPosition||1,positionWidth:e.positionWidth||15,totalPositions:e.totalPositions||5e3,headerHeight:e.headerHeight||bo.BASE,sliderHeight:e.sliderHeight||yo.SLIDER_HEIGHT,currentPosition:e.currentPosition||1,cellBackground:void 0===e.cellBackground||e.cellBackground,sliderColor:e.sliderColor||"rgba(220, 220, 220, 0.4)",onPositionChange:e.onPositionChange||((e,t)=>{}),onHeaderHeightChange:e.onHeaderHeightChange||(()=>{}),...e},this.eventElement=s.div(),this.eventElement.style.position="absolute",this.config.canvas.parentElement?.appendChild(this.eventElement),this.state={isDragging:!1,dragStartX:0,dragMode:"none",dragStartWindowPosition:1,dragOccurred:!1},this.setupEventListeners(),this.init()}determineVisibleTracks(){const e=this.config.headerHeight,t=this.getTrack("weblogo"),n=this.getTrack("conservation"),i=this.getTrack("annotations");if(this.tracks.forEach(e=>{e.setVisible(!1),e.setHeight(yo.DEFAULT_TRACK_HEIGHT)}),e<bo.WITH_TITLE())return;let o=0;i&&(i.setVisible(!0),i.setHeight(yo.ANNOTATION_TRACK_HEIGHT),o=yo.ANNOTATION_TRACK_HEIGHT+yo.TRACK_GAP);const s=bo.WITH_WEBLOGO()+o,r=bo.WITH_BOTH()+o;if(!(e<s))if(e<r){if(t){t.setVisible(!0);const n=e-s;t.setHeight(yo.DEFAULT_TRACK_HEIGHT+n)}}else{if(t&&t.setVisible(!0),n&&n.setVisible(!0),t&&e>r){const n=e-r;t.setHeight(yo.DEFAULT_TRACK_HEIGHT+n)}this.userSelectedTracks&&(this.tracks.forEach((e,t)=>{this.userSelectedTracks[t]||e.setVisible(!1)}),e<s&&t&&t.setVisible(!1),e<r&&n&&n.setVisible(!1))}}drawTrackButtons(){const e=70;if(!this.ctx||this.config.width<280)return;this.trackButtons=[];const t=this.getTrack("conservation"),n=this.getTrack("weblogo"),i=this.getTrack("annotations"),o=t?.isVisible()??!1,s=n?.isVisible()??!1,r=i?.isVisible()??!1;let a=this.config.width-16;const l=this.config.headerHeight>=bo.WITH_TITLE()?(yo.TITLE_HEIGHT-14)/2:2;o&&s||(!o&&t&&(a-=e,this.drawTrackButton("conservation","Conservation",a,l,e,14),a-=4),!s&&n&&(a-=e,this.drawTrackButton("weblogo","WebLogo",a,l,e,14),a-=4)),!r&&i&&(a-=e,this.drawTrackButton("annotations","Annotations",a,l,e,14))}drawTrackButton(e,t,n,i,o,s,r=!1){this.ctx&&(this.trackButtons.push({id:e,label:t,x:n,y:i,width:o,height:s}),this.ctx.fillStyle=r?"rgba(100, 150, 200, 0.8)":"rgba(240, 240, 240, 0.8)",this.ctx.fillRect(n,i,o,s),this.ctx.strokeStyle=r?"rgba(70, 120, 170, 0.8)":"rgba(180, 180, 180, 0.8)",this.ctx.lineWidth=1,this.ctx.strokeRect(n,i,o,s),this.ctx.fillStyle=r?"#ffffff":"#666666",this.ctx.font="9px Roboto, Roboto Local",this.ctx.textAlign="center",this.ctx.textBaseline="middle",this.ctx.fillText(t,n+o/2,i+s/2))}handleTrackButtonClick(e,t){for(const n of this.trackButtons)if(e>=n.x&&e<=n.x+n.width&&t>=n.y&&t<=n.y+n.height)return this.snapToTrackHeight(n.id),!0;return!1}isInsideColumnHeaderArea(e,t){return t<(this.config.headerHeight>=bo.WITH_TITLE()?yo.TITLE_HEIGHT:0)}snapToTrackHeight(e){const t=this.getTrack("annotations")?yo.ANNOTATION_TRACK_HEIGHT+yo.TRACK_GAP:0;let n;if("annotations"===e)n=bo.WITH_TITLE()+t;else if("weblogo"===e)n=bo.WITH_WEBLOGO()+t;else{if("conservation"!==e)return;n=bo.WITH_BOTH()+t}this.userSelectedTracks||(this.userSelectedTracks={},this.tracks.forEach((e,t)=>{this.userSelectedTracks[t]="annotations"===t})),"annotations"===e?this.userSelectedTracks.annotations=!0:"conservation"===e?(this.userSelectedTracks.weblogo=!0,this.userSelectedTracks.conservation=!0):"weblogo"===e&&(this.userSelectedTracks.weblogo=!0),this.config.onHeaderHeightChange&&this.config.onHeaderHeightChange(n),window.requestAnimationFrame(()=>this.redraw())}resetToAutoMode(){this.userSelectedTracks=null;const e=this.getTrack("annotations")?yo.ANNOTATION_TRACK_HEIGHT+yo.TRACK_GAP:0,t=this.tracks.size>0?bo.WITH_BOTH()+e:bo.BASE;this.config.onHeaderHeightChange&&this.config.onHeaderHeightChange(t),window.requestAnimationFrame(()=>this.redraw())}drawColumnTitle(e,t,n,i){this.ctx&&i&&this.config.headerHeight>=bo.WITH_TITLE()&&(this.ctx.fillStyle="rgba(255, 255, 255, 0.95)",this.ctx.fillRect(e,t,n,yo.TITLE_HEIGHT),this.ctx.fillStyle=co,this.ctx.font="bold 13px Roboto, Roboto Local",this.ctx.textAlign="center",this.ctx.textBaseline="middle",this.ctx.fillText(i,e+n/2,t+yo.TITLE_HEIGHT/2))}clearHoverStates(){(-1!==this.previousHoverPosition||null!==this.previousHoverTrack||null!==this.previousHoverMonomer)&&(this.previousHoverPosition=-1,this.previousHoverTrack=null,this.previousHoverMonomer=null,this.tracks.forEach(e=>{e instanceof go&&e.setHovered(-1,null)}),window.requestAnimationFrame(()=>this.redraw()))}redraw(){this.draw(this.config.x,this.config.y,this.config.width,this.config.height,this.config.currentPosition,this.config.windowStartPosition,{preventDefault:()=>{}},this.seqColumn?.name)}setSelectionData(e,t,n,i){this.dataFrame=e,this.seqColumn=t,this.seqHandler=n,this.onSelectionCallback=i||null}setupTooltipHandling(){this.eventElement.addEventListener("mousemove",this.handleTooltipMouseMove.bind(this)),this.eventElement.addEventListener("mouseleave",this.handleTooltipMouseLeave.bind(this))}handleTooltipMouseMove(e){if(!this.isValid)return;const{x:t,y:n}=this.getCoords(e),i=this.config.positionWidth,o=Math.floor(t/i),r=this.config.windowStartPosition+o-1;if(r<0||r>=this.config.totalPositions)return this.hideTooltip(),void this.clearHoverStates();const a=this.config.headerHeight>=bo.WITH_TITLE()?yo.TITLE_HEIGHT:0,l=this.config.headerHeight-yo.SLIDER_HEIGHT-yo.DOTTED_CELL_HEIGHT,c=l-yo.TRACK_GAP;if(n>=l||n<a)return this.hideTooltip(),void this.clearHoverStates();let u=null,h=0;const d=[];this.tracks.forEach((e,t)=>{e.isVisible()&&d.push({id:t,track:e})});let m=c;for(const{id:e,track:t}of d){const i=m-t.getHeight();if(n>=i&&n<m){u=e,h=n-i;break}m=i-yo.TRACK_GAP}let p=null;if(u){const e=this.tracks.get(u);e&&(p=e.getMonomerAt(t,h,r))}if((this.previousHoverPosition!==r||this.previousHoverTrack!==u||this.previousHoverMonomer!==p)&&(this.previousHoverPosition=r,this.previousHoverTrack=u,this.previousHoverMonomer=p,u)){const e=this.tracks.get(u);e instanceof go&&(e.setHovered(r,p),window.requestAnimationFrame(()=>this.redraw()))}if((r!==this.currentHoverPosition||u!==this.currentHoverTrack||p!==this.currentHoverMonomer)&&(this.currentHoverPosition=r,this.currentHoverTrack=u,this.currentHoverMonomer=p,u)){const t=this.tracks.get(u);if(t){const n=t.getTooltipContent(r,p);if(n)return void s.tooltip.show(n,e.clientX+16,e.clientY+16)}}u||(this.hideTooltip(),this.clearHoverStates())}handleTooltipMouseLeave(){this.hideTooltip(),this.clearHoverStates(),window.requestAnimationFrame(()=>this.draw(this.config.x,this.config.y,this.config.width,this.config.height,this.config.currentPosition,this.config.windowStartPosition,{preventDefault:()=>{}},this.seqColumn?.name))}hideTooltip(){this.currentHoverPosition=-1,this.currentHoverTrack=null,s.tooltip.hide()}draw(e,t,n,i,o,s,r,a){if(Object.assign(this.config,{x:e,y:t,width:n,height:i,currentPosition:o,windowStartPosition:s}),!this.isValid)return void(this.eventElement.style.display="none");this.ctx.save(),this.ctx.clearRect(e,t,n,i),this.ctx.translate(e,t),this.ctx.rect(0,0,n,i),this.ctx.clip(),this.determineVisibleTracks();const l=this.config.headerHeight>=bo.WITH_TITLE();l&&yo.TITLE_HEIGHT,a&&l&&this.drawColumnTitle(0,0,n,a);const c=i-yo.SLIDER_HEIGHT,u=c-yo.DOTTED_CELL_HEIGHT,h=u-yo.TRACK_GAP,d=[],m=[];this.tracks.forEach((e,t)=>{e.isVisible()&&m.push({id:t,track:e})});let p=h;for(const{track:e}of m){const t=e.getHeight(),i=p-t;e.draw(0,i,n,t,this.config.windowStartPosition,this.config.positionWidth,this.config.totalPositions,this.config.currentPosition),d.unshift({y:i,height:t}),p=i-yo.TRACK_GAP}if(this.drawDottedCells(0,u,n,yo.DOTTED_CELL_HEIGHT,c),d.push({y:u,height:yo.DOTTED_CELL_HEIGHT}),this.config.currentPosition>=1&&this.config.currentPosition<=this.config.totalPositions){const e=this.config.positionWidth,t=this.config.currentPosition-this.config.windowStartPosition;if(t>=0&&t<Math.floor(n/e)){const n=t*e+e/2;for(let e=0;e<d.length-1;e++){const t=d[e],i=d[e+1];this.ctx.strokeStyle="rgba(60, 177, 115, 0.4)",this.ctx.lineWidth=1,this.ctx.beginPath(),this.ctx.moveTo(n,t.y+t.height),this.ctx.lineTo(n,i.y),this.ctx.stroke()}}}this.drawTrackButtons(),this.ctx.restore(),r.preventDefault(),this.setupEventElement()}drawDottedCells(e,t,n,i,o){if(!this.ctx)return;const s=this.config.totalPositions,r=this.config.positionWidth,a=this.config.currentPosition,l=this.config.windowStartPosition,c=Math.floor(n/r),u=t+yo.TOP_PADDING;this.drawSlider(e,o,n);for(let n=0;n<c;n++){const c=l+n;if(c>s)break;const h=e+n*r,d=r,m=h+d/2;this.config.cellBackground&&(this.ctx.fillStyle=n%2==0?"rgba(248, 248, 248, 0.3)":"rgba(242, 242, 242, 0.2)",this.ctx.fillRect(h,t,d,i),this.ctx.strokeStyle="rgba(220, 220, 220, 0.7)",this.ctx.beginPath(),this.ctx.moveTo(h,t),this.ctx.lineTo(h,o),this.ctx.stroke()),this.ctx.fillStyle="#999999",this.ctx.beginPath(),this.ctx.arc(m,u+5,1,0,2*Math.PI),this.ctx.fill(),(c===a||(1===c||c%10==0)&&Math.abs(c-a)>1)&&(this.ctx.fillStyle=co,this.ctx.font="12px monospace",this.ctx.textAlign="center",this.ctx.textBaseline="middle",this.ctx.fillText(c.toString(),m,u+15)),c===a&&(this.ctx.fillStyle="rgba(60, 177, 115, 0.2)",this.ctx.fillRect(h,t,d,i))}}drawSlider(e,t,n){if(!this.ctx)return;this.ctx.fillStyle=this.config.sliderColor,this.ctx.fillRect(e,t,n,yo.SLIDER_HEIGHT);const i=Math.floor(n/this.config.positionWidth),o=this.config.windowStartPosition,s=this.config.totalPositions-i,r=this.sliderWidth,a=s<=0?0:(o-1)/s*(n-r),l=s<=0?n:r;if(this.ctx.fillStyle="rgba(150, 150, 150, 0.5)",this.ctx.fillRect(e+a,t,l,yo.SLIDER_HEIGHT),this.config.currentPosition>=1&&this.config.currentPosition<=this.config.totalPositions){const i=(this.config.currentPosition-1)/(this.config.totalPositions-1),o=Math.round(i*n);this.ctx.fillStyle="#3CB173",this.ctx.fillRect(e+o-1,t-2,3,yo.SLIDER_HEIGHT+4)}}setupEventElement(){this.eventElement.style.display="block",this.eventElement.style.left=`${this.config.x}px`,this.eventElement.style.top=`${this.config.y}px`,this.eventElement.style.width=`${this.config.width}px`,this.eventElement.style.height=`${this.config.height}px`}getCoords(e){const t=this.canvas.getBoundingClientRect();return{x:e.clientX-t.left-this.config.x,y:e.clientY-t.top-this.config.y}}isInHeaderArea(e){const{x:t,y:n}=this.getCoords(e);return t>=0&&t<=this.config.width&&n>=0&&n<=this.config.headerHeight}get positionWidth(){return this.config.positionWidth}set positionWidth(e){this.config.positionWidth=e}isInSliderArea(e){const{y:t}=this.getCoords(e),n=this.config.headerHeight-yo.SLIDER_HEIGHT;return t>n&&t<n+yo.SLIDER_HEIGHT}get sliderWidth(){const e=this.config.width/this.config.totalPositions*(this.config.width/this.config.positionWidth);return Math.max(e,20)}isInSliderDraggableArea(e){const{x:t,y:n}=this.getCoords(e),i=this.config.headerHeight-yo.SLIDER_HEIGHT,o=Math.floor(this.config.width/this.config.positionWidth),s=this.config.windowStartPosition,r=this.config.totalPositions-o,a=r<=0?0:(s-1)/r*(this.config.width-this.sliderWidth);return n>i&&n<i+yo.SLIDER_HEIGHT&&t>=a&&t<a+this.sliderWidth}setupEventListeners(){this.eventElement.addEventListener("mousemove",e=>{this.isValid&&(this.state.isDragging&&"header"===this.state.dragMode?this.eventElement.style.cursor="grabbing":this.isInSliderDraggableArea(e)?this.eventElement.style.cursor="grab":this.isInSliderArea(e)?this.eventElement.style.cursor="pointer":this.isInHeaderArea(e)?this.eventElement.style.cursor="grab":this.eventElement.style.cursor="default")}),this.eventElement.addEventListener("mousedown",this.handleMouseDown.bind(this)),this.eventElement.addEventListener("mousemove",this.handleMouseMove.bind(this)),this.eventElement.addEventListener("mouseup",this.handleMouseUp.bind(this)),this.eventElement.addEventListener("mouseleave",this.handleMouseUp.bind(this)),this.eventElement.addEventListener("click",this.handleSelectionClick.bind(this)),this.eventElement.addEventListener("click",this.handleClick.bind(this)),this.eventElement.addEventListener("wheel",this.handleMouseWheel.bind(this)),window.addEventListener("keydown",this.handleKeyDown.bind(this))}handleSelectionClick(e){if(this.state.dragOccurred)return;if(!(this.isValid&&this.dataFrame&&this.seqColumn&&this.seqHandler))return;const{x:t,y:n}=this.getCoords(e);if(this.handleTrackButtonClick(t,n))return;if(this.isInsideColumnHeaderArea(t,n))return;const i=this.config.positionWidth,o=Math.floor(t/i),s=this.config.windowStartPosition+o-1;if(s<0||s>=this.config.totalPositions)return;const r=this.config.headerHeight>=bo.WITH_TITLE()?yo.TITLE_HEIGHT:0,a=this.config.headerHeight-yo.SLIDER_HEIGHT-yo.DOTTED_CELL_HEIGHT,l=a-yo.TRACK_GAP;if(n>=a||n<r)return;let c=null,u=0;const h=[],d=this.getTrack("weblogo");d&&d.isVisible()&&h.push({id:"weblogo",track:d});const m=this.getTrack("conservation");m&&m.isVisible()&&h.push({id:"conservation",track:m});let p=l;for(const{id:e,track:t}of h){const i=p-t.getHeight();if(n>=i&&n<p){c=e,u=n-i;break}p=i-yo.TRACK_GAP}if(c){const n=this.tracks.get(c);if(n){const i=n.getMonomerAt(t,u,s);if(i){if(this.onSelectionCallback)return void this.onSelectionCallback(s,i);this.selectRowsWithMonomerAtPosition(s,i),e.stopPropagation(),e.stopImmediatePropagation()}}}}selectRowsWithMonomerAtPosition(e,t){if(this.dataFrame&&this.seqHandler)try{const n=this.dataFrame.selection,i=this.seqHandler.getMonomersAtPosition(e,!0);n.init(e=>i[e]===t)}catch(e){console.error("Error selecting rows:",e)}}init(){if(this.canvas=this.config.canvas,!this.canvas)return void console.error("Canvas not found");const e=this.canvas.getContext("2d");e?(this.ctx=e,this.tracks.forEach(t=>t.init(e))):console.error("Failed to get 2D context from canvas")}addTrack(e,t){this.ctx&&t.init(this.ctx),this.tracks.set(e,t)}removeTrack(e){this.tracks.delete(e)}getTrack(e){return this.tracks.get(e)}updateTrack(e,t){const n=this.getTrack(e);n&&t(n)}get isValid(){const e=this.gridColumn,t=e?.grid,n=t?.horzScroll?.min||0,i=t?.horzScroll?.max||1e7;return!!this.canvas&&!!this.ctx&&this.config.height>=bo.WITH_TITLE()&&t&&(vo(e.left??0,n,i)||vo(e.right??1/0,n,i))}handleMouseDown(e){if(!this.isValid)return;const{x:t,y:n}=this.getCoords(e);this.isInSliderDraggableArea(e)?(this.state.isDragging=!0,this.state.dragMode="slider",this.state.dragStartX=t,this.handleSliderDrag(t),e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()):this.isInHeaderArea(e)&&!this.isInSliderArea(e)&&(this.state.isDragging=!0,this.state.dragMode="header",this.state.dragStartX=t,this.state.dragStartWindowPosition=this.config.windowStartPosition,e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation())}handleMouseWheel(e){if(this.isValid&&this.isInHeaderArea(e)){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();const t=e.shiftKey?Math.sign(e.deltaY):Math.sign(e.deltaX||e.deltaY),n=e.shiftKey?3:1,i=this.config.windowStartPosition+t*n,o=Math.floor(this.config.width/this.config.positionWidth),s=this.config.totalPositions-o+1;this.config.windowStartPosition=Math.max(1,Math.min(s,i)),"function"==typeof this.config.onPositionChange&&this.config.onPositionChange(this.config.currentPosition,this.getWindowRange())}}handleMouseMove(e){if(!this.state.isDragging||!this.isValid)return;const t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-this.config.x;if(this.state.dragOccurred=!0,"slider"===this.state.dragMode)this.handleSliderDrag(n);else if("header"===this.state.dragMode){const e=n-this.state.dragStartX,t=Math.round(e/this.config.positionWidth),i=Math.floor(this.config.width/this.config.positionWidth),o=this.config.totalPositions-i+1;this.config.windowStartPosition=Math.max(1,Math.min(o,this.state.dragStartWindowPosition-t)),"function"==typeof this.config.onPositionChange&&this.config.onPositionChange(this.config.currentPosition,this.getWindowRange())}e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()}detach(){this.eventElement.remove(),window.removeEventListener("keydown",this.handleKeyDown.bind(this))}handleKeyDown(e){if(this.isValid&&!(this.config.currentPosition<1)&&document.activeElement?.contains(this.eventElement)&&"block"===this.eventElement.style.display){if("ArrowLeft"===e.key||"ArrowRight"===e.key){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();const t="ArrowLeft"===e.key?-1:1,n=Math.min(Math.max(this.config.currentPosition+t,1),this.config.totalPositions);if(n===this.config.currentPosition)return;this.config.currentPosition=n;const i=Math.floor(this.config.width/this.config.positionWidth),o=this.config.windowStartPosition;(n<o||n>o+i-1)&&(this.config.windowStartPosition=t<0?n:Math.max(1,n-i+1))}else{if("Escape"!==e.key)return;this.config.currentPosition=-2,e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()}"function"==typeof this.config.onPositionChange&&this.config.onPositionChange(this.config.currentPosition,this.getWindowRange())}}handleMouseUp(){this.state.isDragging=!1,this.state.dragMode="none",this.state.dragOccurred&&setTimeout(()=>{this.state.dragOccurred=!1},0)}handleSliderDrag(e){if(!this.isValid)return;const t=this.sliderWidth,n=this.config.width-t,i=Math.max(0,Math.min(this.config.width,e)),o=Math.floor(this.config.width/this.config.positionWidth),s=Math.floor(this.config.width/this.config.positionWidth),r=this.config.totalPositions-s,a=Math.max(0,i-t/2)/n*r;this.config.windowStartPosition=Math.max(1,Math.min(a,this.config.totalPositions-o+1)),"function"==typeof this.config.onPositionChange&&this.config.onPositionChange(this.config.currentPosition,this.getWindowRange())}get headerHeight(){return this.config.headerHeight}set headerHeight(e){this.config.headerHeight=e}handleClick(e){if(this.state.dragOccurred)return;if(!this.isValid)return;e.clientX,this.canvas.getBoundingClientRect().left,e.clientY,this.canvas.getBoundingClientRect().top;const{x:t,y:n}=this.getCoords(e);if(this.handleTrackButtonClick(t,n))return e.preventDefault(),void e.stopPropagation();if(this.isInsideColumnHeaderArea(t,n))this.seqColumn&&(o.shell.o=this.seqColumn);else if(n<this.config.headerHeight-yo.SLIDER_HEIGHT&&n>=0){const e=this.config.positionWidth,n=Math.round(t/e-.5),i=this.config.windowStartPosition+n;i>=1&&i<=this.config.totalPositions&&(this.config.currentPosition=i,"function"==typeof this.config.onPositionChange&&this.config.onPositionChange(this.config.currentPosition,this.getWindowRange()))}}getWindowRange(){return{start:this.config.windowStartPosition,end:Math.min(this.config.totalPositions,this.config.windowStartPosition+Math.floor(this.config.width/this.config.positionWidth))}}updateConfig(e){Object.assign(this.config,e),this.config.currentPosition=Math.min(this.config.currentPosition,this.config.totalPositions),"function"==typeof this.config.onPositionChange&&this.config.onPositionChange(this.config.currentPosition,this.getWindowRange())}getCurrentPosition(){return this.config.currentPosition}setCurrentPosition(e){this.config.currentPosition=Math.max(1,Math.min(this.config.totalPositions,e)),"function"==typeof this.config.onPositionChange&&this.config.onPositionChange(this.config.currentPosition,this.getWindowRange())}getHeightThresholds(){return{BASE:bo.BASE,WITH_TITLE:bo.WITH_TITLE(),WITH_WEBLOGO:bo.WITH_WEBLOGO(),WITH_BOTH:bo.WITH_BOTH()}}}function vo(e,t,n){return e>=t&&e<=n}class Co extends po{constructor(e,t="Annotations"){super(20,14,t),this.tableCol=e,this.regions=[],this.posList=[],this._cacheVersion=-1,this._rebuildRegions()}hasRegions(){return this._ensureUpToDate(),this.regions.length>0}getRegionAtPosition(e){this._ensureUpToDate();for(const t of this.regions)if(e>=t.startIdx&&e<=t.endIdx)return t;return null}getTooltipContent(e,t){this._ensureUpToDate();const n=this.getRegionAtPosition(e);if(!n)return null;const i=n.sourceScheme??"",o=e<this.posList.length?this.posList[e]:"",r=[],a=document.createElement("b");return a.textContent=n.name,r.push(s.div([a],{style:{fontSize:"13px",marginBottom:"4px"}})),i&&r.push(s.divText(`Scheme: ${i}`,{style:{fontSize:"12px",color:"#555"}})),r.push(s.divText(`Range: ${n.startPos} – ${n.endPos}`,{style:{fontSize:"12px",color:"#555"}})),o&&r.push(s.divText(`Position: ${o}`,{style:{fontSize:"12px",color:"#555"}})),n.description&&r.push(s.divText(n.description,{style:{fontSize:"11px",color:"#888",marginTop:"2px"}})),s.divV(r,{style:{padding:"4px"}})}draw(e,t,n,i,o,s,r,a){if(!this.ctx||!this.visible)return;if(this._ensureUpToDate(),0===this.regions.length)return;const l=this.ctx;l.save(),l.beginPath(),l.rect(e,t,n,i),l.clip();const c=o-1,u=c+Math.ceil(n/s)+2;for(const n of this.regions){if(n.endIdx<c||n.startIdx>u)continue;const o=Math.max(n.startIdx,c),r=e+(o-c)*s,a=(Math.min(n.endIdx,u)-o+1)*s;l.fillStyle=n.color,l.globalAlpha=.35,l.fillRect(r,t,a,i),l.globalAlpha=1,l.strokeStyle=n.color,l.globalAlpha=.6,l.lineWidth=1,l.strokeRect(r+.5,t+.5,a-1,i-1),l.globalAlpha=1,l.font="bold 9px Roboto, Roboto Local, sans-serif",a>l.measureText(n.name).width+4&&(l.fillStyle="#333",l.textAlign="center",l.textBaseline="middle",l.fillText(n.name,r+a/2,t+i/2))}l.restore()}_ensureUpToDate(){this._cacheVersion!==this.tableCol.version&&(this._rebuildRegions(),this._cacheVersion=this.tableCol.version)}_rebuildRegions(){this.regions=[];const e=this.tableCol.getTag(pe.gp.annotations);if(!e)return;let t;try{t=JSON.parse(e)}catch{return}if(this.posList=this._getPosList(),0!==this.posList.length)for(const e of t){if(e.category!==St.eI.Structure)continue;if(null==e.start||null==e.end)continue;const t=this.posList.indexOf(e.start),n=this.posList.indexOf(e.end);t<0||n<0||this.regions.push({name:e.name,color:e.color??this._defaultColor(e),startIdx:t,endIdx:n,startPos:e.start,endPos:e.end,sourceScheme:e.sourceScheme,description:e.description})}}_getPosList(){const e=this.tableCol.getTag(pe.gp.positionNames);return e?e.split(", "):[]}_defaultColor(e){if(e.name.startsWith("CDR")){const t=parseInt(e.name.replace("CDR",""))-1;return St.D5.structure.CDR[t%St.D5.structure.CDR.length]}if(e.name.startsWith("FR")){const t=parseInt(e.name.replace("FR",""))-1;return St.D5.structure.FR[t%St.D5.structure.FR.length]}return"#90CAF9"}}class Ao{static conservationCache=new r.LruCache(100);static webLogoCache=new r.LruCache(100);static lastInvalidationTime=0;static CHUNK_SIZE=50;static clearAllCaches(){Ao.conservationCache=new r.LruCache(100),Ao.webLogoCache=new r.LruCache(100),Ao.lastInvalidationTime=Date.now()}static getLastInvalidationTime(){return Ao.lastInvalidationTime}static getChunkCacheKey(e,t,n){const i=e.dataFrame;return`${i.id}_${e.name}_f${i.filter.version}_${t}_${n}`}static getConservationChunk(e,t,n,i){return Ao.conservationCache.getOrCreate(i,()=>{const o=Ao.getWebLogoChunk(e,t,n,i),s=new Array(n-t).fill(0);for(let i=t;i<n;i++){const n=o.get(i);if(!n||0===n.size)continue;let r=0,a=0;const l=e.defaultGapOriginal;for(const[e,t]of n.entries())e&&e!==l&&(r+=t,t>a&&(a=t));s[i-t]=r>0?a/r:0}return s})}static getWebLogoChunk(e,t,n,i){return Ao.webLogoCache.getOrCreate(i,()=>{const i=e.column.dataFrame,o=new Map,s=i.filter.trueCount;if(s<=1)return o;for(let e=t;e<n;e++)o.set(e,new Map);const r=i.filter,a=1/s;for(let i=-1;-1!==(i=r.findNext(i,!0));){const s=e.getSplitted(i).getOriginalRegion(t,n);if(0!==s.length)for(let e=0;e<s.length;e++){const n=s[e],i=o.get(t+e);i.set(n,(i.get(n)||0)+a)}}return o})}static getConservationForViewport(e,t,n,i){const o=new Array(i).fill(0),s=Math.floor(t/Ao.CHUNK_SIZE)*Ao.CHUNK_SIZE,r=Math.ceil(n/Ao.CHUNK_SIZE)*Ao.CHUNK_SIZE;for(let t=s;t<r;t+=Ao.CHUNK_SIZE){const n=Math.min(t+Ao.CHUNK_SIZE,i),s=Ao.getChunkCacheKey(e.column,t,n),r=Ao.getConservationChunk(e,t,n,s);for(let e=0;e<r.length&&t+e<i;e++)o[t+e]=r[e]}return o}static getWebLogoForViewport(e,t,n,i){const o=new Map,s=Math.floor(t/Ao.CHUNK_SIZE)*Ao.CHUNK_SIZE,r=Math.ceil(n/Ao.CHUNK_SIZE)*Ao.CHUNK_SIZE;for(let t=s;t<r;t+=Ao.CHUNK_SIZE){const n=Math.min(t+Ao.CHUNK_SIZE,i),s=Ao.getChunkCacheKey(e.column,t,n),r=Ao.getWebLogoChunk(e,t,n,s);for(const[e,t]of r.entries())e<i&&o.set(e,t)}return o}}class To extends go{seqHandler;maxLength;lastViewportStart=-1;lastViewportEnd=-1;lastInvalidationTime=0;forceNextUpdate=!1;constructor(e,t,n=45,i="WebLogo"){super(new Map,n,"",i),this.seqHandler=e,this.maxLength=t,this.visible=e.column.dataFrame.filter.trueCount>1}forceUpdate(){this.forceNextUpdate=!0}resetViewportTracking(){this.lastViewportStart=-1,this.lastViewportEnd=-1}updateForViewport(e,t){const n=Ao.getLastInvalidationTime(),i=n>this.lastInvalidationTime;if(!(Math.abs(this.lastViewportStart-e)>=10||Math.abs(this.lastViewportEnd-t)>=10||i||this.forceNextUpdate))return;this.forceNextUpdate=!1,this.lastViewportStart=e,this.lastViewportEnd=t,this.lastInvalidationTime=n;const o=Math.max(0,e-20),s=Math.min(this.maxLength,t+20),r=Ao.getWebLogoForViewport(this.seqHandler,o,s,this.maxLength);this.updateData(r)}draw(e,t,n,i,o,s,r,a){const l=Math.ceil(n/s)+2,c=Math.min(o+l,r);this.updateForViewport(o-1,c-1),super.draw(e,t,n,i,o,s,r,a)}}class Eo extends fo{seqHandler;maxLength;lastViewportStart=-1;lastViewportEnd=-1;lastInvalidationTime=0;forceNextUpdate=!1;constructor(e,t,n=45,i="default",o="Conservation"){super([],n,i,o),this.seqHandler=e,this.maxLength=t,this.visible=e.column.dataFrame.filter.trueCount>1}forceUpdate(){this.forceNextUpdate=!0}resetViewportTracking(){this.lastViewportStart=-1,this.lastViewportEnd=-1}updateForViewport(e,t){const n=Ao.getLastInvalidationTime(),i=n>this.lastInvalidationTime;if(!(Math.abs(this.lastViewportStart-e)>=10||Math.abs(this.lastViewportEnd-t)>=10||i||this.forceNextUpdate))return;this.forceNextUpdate=!1,this.lastViewportStart=e,this.lastViewportEnd=t,this.lastInvalidationTime=n;const o=Math.max(0,e-20),s=Math.min(this.maxLength,t+20),r=Ao.getConservationForViewport(this.seqHandler,o,s,this.maxLength);this.updateData(r)}draw(e,t,n,i,o,s,r,a){const l=Math.ceil(n/s)+2,c=Math.min(o+l,r);this.updateForViewport(o-1,c-1),super.draw(e,t,n,i,o,s,r,a)}}const So="__msa-scroller-initialized",Mo="__msa-scroller-subscription";class xo extends no.$G{separator;seqHelper;seqCol;splitter;get defaultGapOriginal(){return""}static get notationName(){return pe.Hi.BILN}static get implementsFromHelm(){return!1}static convertFromHelm(e,t){throw new Error("Canonical way of converting from helm to biln must be used")}constructor(e,t,n){super(),this.separator=e,this.seqHelper=t,this.seqCol=n,this.splitter=Oe.bR.bind(this)}setUnits(){}getHelm(e,t){const n=this.splitter(e);return this.seqHelper.getSeqHandler(this.seqCol).getJoiner({notation:pe.Hi.HELM})(n)}createCellRendererBack(e,t){const n=Uo.properties.maxMonomerLength||4,i=new Po(e,t,n,this.seqHelper);return i.init().then(()=>{}),i}}class Po extends $e.Jy{constructor(e,t,n,i){super(e,t,Uo.logger,n,()=>{const e=i.getSeqHandler(t),{font:n,fontWidth:o}=$e.Jy.getFontSettings(t);return{seqHandler:e,font:n,fontCharWidth:o,separatorWidth:0,monomerToShort:Oe.zS}})}}var Lo=n(6520),Io={};Io.styleTagTransform=C(),Io.setAttributes=y(),Io.insert=g().bind(null,"head"),Io.domAPI=m(),Io.insertStyleElement=w(),h()(Lo.A,Io),Lo.A&&Lo.A.locals&&Lo.A.locals;class _o{view=null;libHelper=null;monomerLib=null;collectionNames=[];filteredNames=[];displayedCount=0;cardsContainer=null;loadMoreContainer=null;searchInput=null;currentUser="";collectionsCache=new Map;selectedCollections=new Set;cardElements=new Map;handler=new jn;static VIEW_NAME="Monomer Collections";async init(){this.libHelper=await bn.getInstance(),await this.libHelper.awaitLoaded(),this.monomerLib=this.libHelper.getMonomerLib(),this.currentUser=r.User.current().login,this.view=r.View.create(),this.view.name=_o.VIEW_NAME,this.view._mcView=this;const e=s.icons.add(()=>this.showAddCollectionDialog(),"Create new monomer collection"),t=s.iconFA("sync",()=>this.refresh(),"Refresh collections");return this.view.setRibbonPanels([[e,t]]),this.view.root.addEventListener("contextmenu",e=>{const t=e.target;if(t.closest(".monomer-collection-card")||t.closest(".monomer-collection-add-card"))return;e.preventDefault();const n=r.Menu.popup();n.item("New Collection...",()=>this.showAddCollectionDialog()),n.item("Refresh",()=>this.refresh()),n.show()}),this.view.root.addEventListener("click",e=>{const t=e.target;t.closest(".monomer-collection-card")||t.closest(".monomer-collection-add-card")||this.clearSelection()}),this.view.root.tabIndex=0,this.view.root.addEventListener("keydown",e=>{"Escape"===e.key&&this.clearSelection()}),await this.buildContent(),this.view}async buildContent(){if(!this.view)return;this.view.root.innerHTML="";const e=s.div([],{classes:"monomer-collections-view"});this.searchInput=s.input.string("Monomer Collections",{value:"",placeholder:"Search by name or tag..."}),this.searchInput.root.classList.add("monomer-collections-search");const t=this.searchInput.input;t.style.width="100%",t.style.marginBottom="12px";let n=null;t.addEventListener("input",()=>{n&&clearTimeout(n),n=setTimeout(()=>this.applyFilter(),250)}),this.cardsContainer=s.div([],{classes:"monomer-collections-grid"}),this.loadMoreContainer=s.div([],{classes:"monomer-collections-load-more"}),e.appendChild(this.searchInput.root),e.appendChild(this.cardsContainer),e.appendChild(this.loadMoreContainer),this.view.root.appendChild(e),await this.loadCollections()}async loadCollections(){try{this.collectionNames=await this.libHelper.listMonomerCollections()}catch(e){Uo.logger.error(`Error listing monomer collections: ${e instanceof Error?e.message:e.toString()}`),o.shell.error("Error loading monomer collections"),this.collectionNames=[]}this.collectionsCache.clear();for(const e of this.collectionNames)this.libHelper.readMonomerCollection(e).then(t=>{this.collectionsCache.set(e,t)}).catch(()=>{});this.applyFilter()}applyFilter(){const e=(this.searchInput?.value??"").trim().toLowerCase();this.filteredNames=e?this.collectionNames.filter(t=>{if(t.replace(/\.json$/i,"").toLowerCase().includes(e))return!0;const n=this.collectionsCache.get(t);return!!n?.tags?.some(t=>t.toLowerCase().includes(e))}):[...this.collectionNames],this.displayedCount=0,this.cardsContainer.innerHTML="",this.cardElements.clear(),this.showNextPage()}showNextPage(){const e=Math.min(this.displayedCount+19,this.filteredNames.length);for(let t=this.displayedCount;t<e;t++){const e=this.createCollectionCard(this.filteredNames[t]);this.cardsContainer.appendChild(e),this.cardElements.set(this.filteredNames[t],e)}this.displayedCount=e;const t=this.cardsContainer.querySelector(".monomer-collection-add-card");t&&t.remove(),this.cardsContainer.appendChild(this.createAddCard());const n=this.cardsContainer.querySelector(".monomer-collection-empty-state");if(n&&n.remove(),0===this.filteredNames.length){const e=0===this.collectionNames.length?'No monomer collections found. Click "+" to create one.':"No collections match your search.",t=s.div([s.divText(e)],{classes:"monomer-collection-empty-state"});this.cardsContainer.prepend(t)}if(this.loadMoreContainer.innerHTML="",this.displayedCount<this.filteredNames.length){const e=this.filteredNames.length-this.displayedCount,t=s.button(`Load more (${e} remaining)`,()=>this.showNextPage());this.loadMoreContainer.appendChild(t)}}createCollectionCard(e){const t=e.replace(/\.json$/i,""),n=s.div([t],{classes:"monomer-collection-card-title"});s.tooltip.bind(n,t);const i=s.div([n],{classes:"monomer-collection-card-header"}),a=s.div([],{classes:"monomer-collection-card-body"}),l=s.div([],{classes:"monomer-collection-card-actions"}),c=s.div([i,a,l],{classes:"monomer-collection-card"});c.dataset.collectionName=e,this.selectedCollections.has(e)&&c.classList.add("monomer-collection-card-selected"),c.addEventListener("click",t=>{const n=t.target;n.closest(".monomer-collection-card-actions")||n.closest(".monomer-collection-tag")||(t.stopPropagation(),this.handleCardClick(e,t.ctrlKey||t.metaKey))}),c.addEventListener("contextmenu",t=>{t.preventDefault(),t.stopPropagation(),this.selectedCollections.has(e)||this.handleCardClick(e,!1),this.showCardContextMenu(t)});const u=async()=>{const t=await this.libHelper.readMonomerCollection(e);if(this.collectionsCache.set(e,t),t.description){const e=s.div([t.description],{classes:"monomer-collection-card-description"});s.tooltip.bind(e,t.description),i.appendChild(e)}if(t.tags&&t.tags.length>0){const e=s.div([],{classes:"monomer-collection-card-tags"});for(const n of t.tags){const t=s.div([n],{classes:"monomer-collection-card-tag"});e.appendChild(t)}i.appendChild(e)}const n=[];if(t.updatedBy&&n.push(`by ${t.updatedBy}`),t.updatedOn)try{n.push(new Date(t.updatedOn).toLocaleDateString())}catch{}n.length>0&&i.appendChild(s.div([n.join(" | ")],{classes:"monomer-collection-card-meta"}));const a=s.div([],{classes:"monomer-collection-tags"}),c=t.monomerSymbols??[];for(const e of c){const t=s.div([e],{classes:"monomer-collection-tag"});t.addEventListener("mouseenter",()=>{if(this.monomerLib){const n=this.getMonomerTooltipSafe(e);if(n){const e=t.getBoundingClientRect();s.tooltip.show(n,e.left,e.bottom+4)}}}),t.addEventListener("mouseleave",()=>s.tooltip.hide()),t.addEventListener("click",t=>{t.stopPropagation(),o.shell.o=r.SemanticValue.fromValueType(e,Ve.uF.MONOMER)}),a.appendChild(t)}const u=s.divText(`${c.length} monomer(s)`,{style:{fontSize:"11px",color:"var(--grey-4)",marginBottom:"6px"}}),h=s.divV([u,a]),d=t.updatedBy===this.currentUser,m=s.button("Edit",()=>{d&&this.showEditCollectionDialog(e,t)}),p=s.button("Delete",()=>{d&&this.confirmDeleteCollection(e)});if(!d){for(const e of[m,p])e.style.opacity="0.4",e.style.cursor="default";s.tooltip.bind(m,"Only the author can edit"),s.tooltip.bind(p,"Only the author can delete")}return l.appendChild(m),l.appendChild(p),h};return a.appendChild(s.wait(()=>u())),c}handleCardClick(e,t){t?this.selectedCollections.has(e)?this.selectedCollections.delete(e):this.selectedCollections.add(e):(this.selectedCollections.clear(),this.selectedCollections.add(e)),this.updateCardSelectionStyles(),this.setCurrentObject()}clearSelection(){this.selectedCollections.clear(),this.updateCardSelectionStyles()}updateCardSelectionStyles(){for(const[e,t]of this.cardElements)this.selectedCollections.has(e)?t.classList.add("monomer-collection-card-selected"):t.classList.remove("monomer-collection-card-selected")}async setCurrentObject(){const e=[...this.selectedCollections];if(0===e.length)return;const t=[];for(const n of e){let e=this.collectionsCache.get(n);if(!e)try{e=await this.libHelper.readMonomerCollection(n)}catch{continue}t.push({name:n,displayName:n.replace(/\.json$/i,""),data:e})}1===t.length?o.shell.o=t[0]:t.length>1&&(o.shell.o=t)}showCardContextMenu(e){const t=r.Menu.popup(),n=[...this.selectedCollections];if(n.length<=1&&n.length>0){const e=n[0],i=this.collectionsCache.get(e);if(i){const n={name:e,displayName:e.replace(/\.json$/i,""),data:i};jn.buildContextMenu(t,n,this.handler)}}else if(n.length>1){const e=n.map(e=>{const t=this.collectionsCache.get(e);return t?{name:e,displayName:e.replace(/\.json$/i,""),data:t}:null}).filter(e=>null!==e);e.length>0&&jn.buildMultiContextMenu(t,e,this.handler)}t.show()}getMonomerTooltipSafe(e){if(!this.monomerLib)return null;const t=[Fe.o.AA,Fe.o.NUCLEOTIDE,Fe.o.CHEM,Fe.o.BLOB];for(const n of t)try{if(this.monomerLib.getWebEditorMonomer(n,e))return this.monomerLib.getTooltip(n,e)}catch(e){}return null}createAddCard(){const e=s.iconFA("plus",()=>{},"");e.style.fontSize="32px",e.style.marginBottom="8px";const t=s.span(["New Collection"]),n=s.div([e,t],{classes:"monomer-collection-add-card-content"}),i=s.div([n],{classes:"monomer-collection-add-card"});return i.addEventListener("click",()=>this.showAddCollectionDialog()),i}showAddCollectionDialog(){const e=s.input.string("Name",{nullable:!1,placeholder:"Enter collection name"}),t=s.input.string("Description",{nullable:!0,placeholder:"Optional description"}),n=s.input.string("Tags",{nullable:!0,placeholder:"Comma-separated tags"}),i=s.input.choice("Polymer Type",{items:["PEPTIDE","RNA","CHEM"],value:"PEPTIDE",nullable:!1}),r=new Yn(this.monomerLib,i.value,[],this.libHelper);i.onChanged.subscribe(()=>{r.setPolymerType(i.value)}),s.dialog({title:"New Monomer Collection"}).add(s.divV([e,t,n,i,s.element("hr"),r.root])).onOK(async()=>{const i=e.value?.trim();if(!i)return void o.shell.warning("Collection name is required");const s=r.getSelectedMonomers();if(0===s.length)return void o.shell.warning("Please select at least one monomer");const a=No(n.value);try{await this.libHelper.addOrUpdateMonomerCollection(i,s,t.value??void 0,a.length>0?a:void 0),o.shell.info(`Collection "${i}" created successfully`),await this.refresh()}catch(e){o.shell.error("Error creating collection"),Uo.logger.error(`Error creating collection: ${e instanceof Error?e.message:e.toString()}`)}}).show({resizable:!0}).root.style.width="550px",r.focus()}editCollectionPublic(e,t){this.showEditCollectionDialog(e,t)}showEditCollectionDialog(e,t){const n=e.replace(/\.json$/i,""),i=s.input.string("Name",{value:n,nullable:!1}),r=s.input.string("Description",{value:t.description??"",nullable:!0}),a=s.input.string("Tags",{value:(t.tags??[]).join(", "),nullable:!0,placeholder:"Comma-separated tags"}),l=s.input.choice("Polymer Type",{items:["PEPTIDE","RNA","CHEM"],value:"PEPTIDE",nullable:!1}),c=new Yn(this.monomerLib,l.value,[...t.monomerSymbols??[]],this.libHelper);l.onChanged.subscribe(()=>{c.setPolymerType(l.value)}),s.dialog({title:`Edit Collection: ${n}`}).add(s.divV([i,r,a,l,s.element("hr"),c.root])).onOK(async()=>{const t=i.value?.trim();if(!t)return void o.shell.warning("Collection name is required");const s=c.getSelectedMonomers();if(0===s.length)return void o.shell.warning("Please select at least one monomer");const l=No(a.value);try{t!==n&&await this.libHelper.deleteMonomerCollection(e),await this.libHelper.addOrUpdateMonomerCollection(t,s,r.value??void 0,l.length>0?l:void 0),o.shell.info(`Collection "${t}" saved successfully`),await this.refresh()}catch(e){o.shell.error("Error saving collection"),Uo.logger.error(`Error saving collection: ${e instanceof Error?e.message:e.toString()}`)}}).show({resizable:!0}).root.style.width="550px",c.focus()}confirmDeleteCollection(e){const t=e.replace(/\.json$/i,"");s.dialog({title:"Delete Collection"}).add(s.divText(`Are you sure you want to delete the collection "${t}"?`)).onOK(async()=>{try{await this.libHelper.deleteMonomerCollection(e),o.shell.info(`Collection "${t}" deleted`),await this.refresh()}catch(e){o.shell.error("Error deleting collection"),Uo.logger.error(`Error deleting collection: ${e instanceof Error?e.message:e.toString()}`)}}).show()}async refresh(){this.selectedCollections.clear(),await this.loadCollections()}}function No(e){return e?e.split(",").map(e=>e.trim()).filter(e=>e.length>0):[]}class Ro{colInput;constructor(e,t){const n=t.filter;this.colInput=s.input.column(e,{...t,filter:e=>e.semType===r.SEMTYPE.MACROMOLECULE&&(!n||n(e))});const i=s.iconFA("cut",()=>this.onRegionIconClick(),"Extract a region from the sequence");this.colInput.addOptions(i)}static create(e,t){return new Ro(e,t)}get root(){return this.colInput.root}get value(){return this.colInput.value}set value(e){this.colInput.value=e}get inputBase(){return this.colInput}onRegionIconClick(){const e=this.colInput.value;e?function(e,t){const n=Uo.seqHelper.getSeqHandler(e),i=s.input.string("Name",{value:""}),a=s.input.choice("Start Position",{value:n.posList[0],items:n.posList,onValueChanged:()=>h()}),l=s.input.choice("End Position",{value:n.posList[n.posList.length-1],items:n.posList,onValueChanged:()=>h()});let c=null;const u=()=>c?`${e.name}(${c}): ${a.value}-${l.value}`:`${e.name}:${a.value}-${l.value}`,h=()=>{i.value||i.input.setAttribute("placeholder",u())};h();const d=function(e,t,n,i){let o=null;const r=e.getTag(ue.gp.annotations);if(r)try{const e=JSON.parse(r).filter(e=>e.category===St.eI.Structure&&e.start&&e.end);e.length>0&&(o=e.map(e=>({name:e.name,start:e.start,end:e.end})))}catch{}if(!o){const t=e.getTag(ue.gp.regions);if(t)try{o=JSON.parse(t)}catch{}}if(!o||0===o.length)return null;const a=["",...o.map(e=>`${e.name}: ${e.start}-${e.end}`)];return s.input.choice("Region",{value:"",items:a,onValueChanged:e=>{if(!e)return void i?.(null);const s=o.find(t=>`${t.name}: ${t.start}-${t.end}`===e);s&&(t.value=s.start,n.value=s.end,i?.(s.name))}})}(e,a,l,e=>{c=e,h()}),m=[];d&&m.push(d),m.push(i,a,l);const p=s.dialog({title:"Get Region"}).add(s.inputs(m)).onOK(()=>{const n=r.TaskBarProgressIndicator.create("Getting region...");try{const n=i.value||u(),o=Ii(e,a.value,l.value,n);e.dataFrame.columns.add(o),o.setTag(r.TAGS.CELL_RENDERER,"sequence"),t?.(o)}catch(e){o.shell.error(e.toString())}finally{n.close()}});p.show()}(e,e=>{this.colInput.value=e}):o.shell.warning("Select a macromolecule column first.")}}var $o,Oo,Ho=n(6839),Do=n(9422),Fo=n(9287),ko=n(9036);!function(e){e.embed=async function(e){return await o.functions.call("Bio:Embed",{molecule:e})},e.molToHelmConverterPy=async function(e,t,n){return await o.functions.call("Bio:MolToHelmConverterPy",{moleculesDataframe:e,moleculesColumn:t,libraryFile:n})},e.sequenceGenerator=async function(e,t,n,i,s,r,a,l,c,u,h,d,m,p,g,f,y){return await o.functions.call("Bio:SequenceGenerator",{clusters:e,num_sequences:t,alphabet_key:n,motif_length:i,max_variants_position:s,random_length:r,dispersion:a,activity_range:l,cliff_probability:c,cliff_strength:u,cliff_strength_dispersion:h,assay_noise_levels:d,assay_scales:m,disable_negatives:p,fasta_separator:g,helm_library_file:f,helm_connection_mode:y})}}($o||($o={})),function(e){e.test1=async function(){return await o.functions.call("Bio:Test1",{})},e.getMonomerLibHelper=async function(){return await o.functions.call("Bio:GetMonomerLibHelper",{})},e.initBio=async function(){return await o.functions.call("Bio:InitBio",{})},e.sequenceTooltip=async function(e){return await o.functions.call("Bio:SequenceTooltip",{col:e})},e.standardiseMonomerLibrary=async function(e){return await o.functions.call("Bio:StandardiseMonomerLibrary",{library:e})},e.matchWithMonomerLibrary=async function(e,t,n){return await o.functions.call("Bio:MatchWithMonomerLibrary",{table:e,molecules:t,polymerType:n})},e.getBioLib=async function(){return await o.functions.call("Bio:GetBioLib",{})},e.getSeqHandler=async function(e){return await o.functions.call("Bio:GetSeqHandler",{sequence:e})},e.getRegionPanel=async function(e){return await o.functions.call("Bio:GetRegionPanel",{seqCol:e})},e.libraryPanel=async function(e){return await o.functions.call("Bio:LibraryPanel",{seqColumn:e})},e.getRegionEditor=async function(e){return await o.functions.call("Bio:GetRegionEditor",{call:e})},e.splitToMonomersEditor=async function(e){return await o.functions.call("Bio:SplitToMonomersEditor",{call:e})},e.sequenceSpaceEditor=async function(e){return await o.functions.call("Bio:SequenceSpaceEditor",{call:e})},e.seqActivityCliffsEditor=async function(e){return await o.functions.call("Bio:SeqActivityCliffsEditor",{call:e})},e.customSequenceCellRenderer=async function(){return await o.functions.call("Bio:CustomSequenceCellRenderer",{})},e.fastaSequenceCellRenderer=async function(){return await o.functions.call("Bio:FastaSequenceCellRenderer",{})},e.separatorSequenceCellRenderer=async function(){return await o.functions.call("Bio:SeparatorSequenceCellRenderer",{})},e.bilnSequenceCellRenderer=async function(){return await o.functions.call("Bio:BilnSequenceCellRenderer",{})},e.refineNotationProviderForBiln=async function(e,t,n){return await o.functions.call("Bio:RefineNotationProviderForBiln",{col:e,stats:t,separator:n})},e.macroMolColumnPropertyPanel=async function(e){return await o.functions.call("Bio:MacroMolColumnPropertyPanel",{molColumn:e})},e.compositionAnalysisWidget=async function(e){return await o.functions.call("Bio:CompositionAnalysisWidget",{sequence:e})},e.monomerInfoPanel=async function(e){return await o.functions.call("Bio:MonomerInfoPanel",{monomerSv:e})},e.macromoleculeDifferenceCellRenderer=async function(){return await o.functions.call("Bio:MacromoleculeDifferenceCellRenderer",{})},e.sequenceAlignment=async function(e,t,n,i,s){return await o.functions.call("Bio:SequenceAlignment",{alignType:e,alignTable:t,gap:n,seq1:i,seq2:s})},e.webLogoViewer=async function(){return await o.functions.call("Bio:WebLogoViewer",{})},e.vdRegionsViewer=async function(){return await o.functions.call("Bio:VdRegionsViewer",{})},e.getRegion=async function(e,t,n,i){return await o.functions.call("Bio:GetRegion",{sequence:e,start:t,end:n,name:i})},e.getRegionTopMenu=async function(e,t,n,i,s){return await o.functions.call("Bio:GetRegionTopMenu",{table:e,sequence:t,start:n,end:i,name:s})},e.applyNumberingScheme=async function(){return await o.functions.call("Bio:ApplyNumberingScheme",{})},e.scanLiabilities=async function(){return await o.functions.call("Bio:ScanLiabilities",{})},e.manageAnnotations=async function(){return await o.functions.call("Bio:ManageAnnotations",{})},e.sequenceColumnInput=async function(e,t){return await o.functions.call("Bio:SequenceColumnInput",{name:e,options:t})},e.activityCliffs=async function(e,t,n,i,s,r,a,l,c){return await o.functions.call("Bio:ActivityCliffs",{table:e,molecules:t,activities:n,similarity:i,methodName:s,similarityMetric:r,preprocessingFunction:a,options:l,demo:c})},e.seqActivityCliffsInitFunction=async function(e){return await o.functions.call("Bio:SeqActivityCliffsInitFunction",{sp:e})},e.seqActivityCliffsTransform=async function(e,t,n,i,s,r,a,l,c){return await o.functions.call("Bio:SeqActivityCliffsTransform",{table:e,molecules:t,activities:n,similarity:i,methodName:s,similarityMetric:r,options:a,isDemo:l,axesNames:c})},e.macromoleculePreprocessingFunction=async function(e,t,n,i,s){return await o.functions.call("Bio:MacromoleculePreprocessingFunction",{col:e,metric:t,gapOpen:n,gapExtend:i,fingerprintType:s})},e.helmPreprocessingFunction=async function(e,t){return await o.functions.call("Bio:HelmPreprocessingFunction",{col:e,_metric:t})},e.sequenceSpaceTopMenu=async function(e,t,n,i,s,r,a,l,c){return await o.functions.call("Bio:SequenceSpaceTopMenu",{table:e,molecules:t,methodName:n,similarityMetric:i,plotEmbeddings:s,preprocessingFunction:r,options:a,clusterEmbeddings:l,isDemo:c})},e.sequenceSpaceTransform=async function(e,t,n,i,s,r,a,l,c){return await o.functions.call("Bio:SequenceSpaceTransform",{table:e,molecules:t,methodName:n,similarityMetric:i,plotEmbeddings:s,options:r,clusterEmbeddings:a,embedColsNames:l,clusterColName:c})},e.moleculesToHelmTopMenu=async function(e,t){return await o.functions.call("Bio:MoleculesToHelmTopMenu",{table:e,molecules:t})},e.moleculeToHelmSingle=async function(e){return await o.functions.call("Bio:MoleculeToHelmSingle",{molecule:e})},e.toAtomicLevel=async function(e,t,n,i){return await o.functions.call("Bio:ToAtomicLevel",{table:e,seqCol:t,nonlinear:n,highlight:i})},e.toAtomicLevelAction=async function(e){return await o.functions.call("Bio:ToAtomicLevelAction",{seqCol:e})},e.toAtomicLevelPanel=async function(e){return await o.functions.call("Bio:ToAtomicLevelPanel",{sequence:e})},e.toAtomicLevelSingleSeq=async function(e){return await o.functions.call("Bio:ToAtomicLevelSingleSeq",{sequence:e})},e.sequence3dStructureWidget=async function(e){return await o.functions.call("Bio:Sequence3dStructureWidget",{sequence:e})},e.multipleSequenceAlignmentDialog=async function(){return await o.functions.call("Bio:MultipleSequenceAlignmentDialog",{})},e.alignSequences=async function(e,t,n){return await o.functions.call("Bio:AlignSequences",{sequenceCol:e,clustersCol:t,options:n})},e.pepseaMsa=async function(e,t,n,i){return await o.functions.call("Bio:PepseaMsa",{sequenceCol:e,method:t,gapOpen:n,gapExtend:i})},e.immunumAntibodyNumbering=async function(e,t,n){return await o.functions.call("Bio:ImmunumAntibodyNumbering",{df:e,seqCol:t,scheme:n})},e.compareSequences=async function(){return await o.functions.call("Bio:CompareSequences",{})},e.compositionAnalysis=async function(){return await o.functions.call("Bio:CompositionAnalysis",{})},e.importFasta=async function(e){return await o.functions.call("Bio:ImportFasta",{fileContent:e})},e.importBam=async function(e){return await o.functions.call("Bio:ImportBam",{fileContent:e})},e.convertDialog=async function(){return await o.functions.call("Bio:ConvertDialog",{})},e.convertColumnAction=async function(e){return await o.functions.call("Bio:ConvertColumnAction",{col:e})},e.monomerCellRenderer=async function(){return await o.functions.call("Bio:MonomerCellRenderer",{})},e.testDetectMacromolecule=async function(e){return await o.functions.call("Bio:TestDetectMacromolecule",{path:e})},e.splitToMonomersTopMenu=async function(e,t){return await o.functions.call("Bio:SplitToMonomersTopMenu",{table:e,sequence:t})},e.getHelmMonomers=async function(e){return await o.functions.call("Bio:GetHelmMonomers",{sequence:e})},e.similaritySearchViewer=async function(){return await o.functions.call("Bio:SimilaritySearchViewer",{})},e.similaritySearchTopMenu=async function(){return await o.functions.call("Bio:SimilaritySearchTopMenu",{})},e.diversitySearchViewer=async function(){return await o.functions.call("Bio:DiversitySearchViewer",{})},e.diversitySearchTopMenu=async function(){return await o.functions.call("Bio:DiversitySearchTopMenu",{})},e.searchSubsequenceEditor=async function(e){return await o.functions.call("Bio:SearchSubsequenceEditor",{call:e})},e.subsequenceSearchTopMenu=async function(e){return await o.functions.call("Bio:SubsequenceSearchTopMenu",{macromolecules:e})},e.sequenceIdentityScoring=async function(e,t,n){return await o.functions.call("Bio:SequenceIdentityScoring",{table:e,macromolecule:t,reference:n})},e.sequenceSimilarityScoring=async function(e,t,n){return await o.functions.call("Bio:SequenceSimilarityScoring",{table:e,macromolecule:t,reference:n})},e.manageMonomerLibraries=async function(){return await o.functions.call("Bio:ManageMonomerLibraries",{})},e.manageLibrariesView=async function(){return await o.functions.call("Bio:ManageLibrariesView",{})},e.manageMonomersView=async function(){return await o.functions.call("Bio:ManageMonomersView",{})},e.manageMonomerLibrariesView=async function(e){return await o.functions.call("Bio:ManageMonomerLibrariesView",{path:e})},e.manageMonomerLibrariesViewTreeBrowser=async function(e){return await o.functions.call("Bio:ManageMonomerLibrariesViewTreeBrowser",{treeNode:e})},e.monomerCollectionsApp=async function(){return await o.functions.call("Bio:MonomerCollectionsApp",{})},e.saveAsFasta=async function(){return await o.functions.call("Bio:SaveAsFasta",{})},e.bioSubstructureFilter=async function(){return await o.functions.call("Bio:BioSubstructureFilter",{})},e.bioSubstructureFilterTest=async function(){return await o.functions.call("Bio:BioSubstructureFilterTest",{})},e.webLogoLargeApp=async function(){return await o.functions.call("Bio:WebLogoLargeApp",{})},e.webLogoAggApp=async function(){return await o.functions.call("Bio:WebLogoAggApp",{})},e.getRegionApp=async function(){return await o.functions.call("Bio:GetRegionApp",{})},e.getRegionHelmApp=async function(){return await o.functions.call("Bio:GetRegionHelmApp",{})},e.longSeqTableSeparator=async function(){return await o.functions.call("Bio:LongSeqTableSeparator",{})},e.longSeqTableFasta=async function(){return await o.functions.call("Bio:LongSeqTableFasta",{})},e.longSeqTableHelm=async function(){return await o.functions.call("Bio:LongSeqTableHelm",{})},e.addCopyMenu=async function(e,t){return await o.functions.call("Bio:AddCopyMenu",{cell:e,menu:t})},e.demoBioSimilarityDiversity=async function(){return await o.functions.call("Bio:DemoBioSimilarityDiversity",{})},e.demoBioSequenceSpace=async function(){return await o.functions.call("Bio:DemoBioSequenceSpace",{})},e.demoBioActivityCliffs=async function(){return await o.functions.call("Bio:DemoBioActivityCliffs",{})},e.demoBioAtomicLevel=async function(){return await o.functions.call("Bio:DemoBioAtomicLevel",{})},e.demoBioSiRNA=async function(){return await o.functions.call("Bio:DemoBioSiRNA",{})},e.sdfToJsonLib=async function(e){return await o.functions.call("Bio:SdfToJsonLib",{table:e})},e.demoAntibodies=async function(){return await o.functions.call("Bio:DemoAntibodies",{})},e.seq2atomic=async function(e,t){return await o.functions.call("Bio:Seq2atomic",{seq:e,nonlinear:t})},e.seqIdentity=async function(e,t){return await o.functions.call("Bio:SeqIdentity",{seq:e,ref:t})},e.detectMacromoleculeProbe=async function(e,t,n){return await o.functions.call("Bio:DetectMacromoleculeProbe",{file:e,colName:t,probeCount:n})},e.getSeqHelper=async function(){return await o.functions.call("Bio:GetSeqHelper",{})},e.getMolFromHelm=async function(e,t,n){return await o.functions.call("Bio:GetMolFromHelm",{df:e,helmCol:t,chiralityEngine:n})}}(Oo||(Oo={}));var Go=function(e,t,n,i){var o,s=arguments.length,r=s<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(r=(s<3?o(r):s>3?o(t,n,r):o(t,n))||r);return s>3&&r&&Object.defineProperty(t,n,r),r},Bo=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},Vo=function(e,t){return function(n,i){t(n,i,e)}};const Uo=new Ei;let qo=null;o.decorators||(o.decorators={}),["func","init","param","panel","editor","demo","app","appTreeBrowser","fileHandler","fileExporter","model","viewer","filter","cellRenderer","autostart","dashboard","folderViewer","semTypeDetector","packageSettingsEditor","functionAnalysis","converter","fileViewer","model","treeBrowser","polyfill"].forEach(e=>{o.decorators[e]||(o.decorators[e]=function(e){return function(e,t,n){}})});class Wo{static async getMonomerLibHelper(){return await bn.getInstance()}static async initBio(){null==qo&&(qo=async function(){const e="Bio: _package.initBio()";Uo.logger.debug(`${e}, start`);const t=window.performance.now(),n=await(0,Ie.j)(),i=await Uo.getProperties(),s=new Ti(i);Uo.properties=s;const a=await bn.getInstance(),l=await(0,Le.u)();l.explicit&&(l.explicit=[],await(0,Le.E)(l)),await a.awaitLoaded(1/0),a.initialLoadCompleted||await a.loadMonomerLib(),a.loadMonomerSets();const u=a.getMonomerLib(),h=a.getMonomerSets(),d=window.performance.now();Uo.logger.debug(`${e}, loading ET: ${d-t} ms`);const m=new ao(a,n);Uo.completeInit(m,u,h,n),r.ObjectHandler.register(new jn),Uo.logger.debug(`${e}, end`),function(){const e=t=>{setTimeout(()=>{if(t.isDetached)return;const n=t.dataFrame;if(!n)return;t.temp[Mo]||(t.temp[Mo]=[]);let i=t.temp[Mo];i.forEach(e=>e.unsubscribe()),t.temp[Mo]=i=[];const s=e=>{i.push(e)},a=n.columns.bySemTypeAll(r.SEMTYPE.MACROMOLECULE);s(r.debounce(c.merge(n.onColumnsAdded,n.onColumnsRemoved,n.onSemanticTypeDetected,t.onEvent("d4-data-frame-changed")),200).subscribe(()=>e(t)));for(const e of a){const i=t.col(e.name);if(!i)continue;const a=!0===i.temp[So];i.temp[So]=!0;let l=null;try{l=Uo.seqHelper.getSeqHandler(e)}catch(t){console.warn(`Failed to get SeqHandler for column ${e.name}`);continue}if(!l)continue;if(l.isHelm()||l.alphabet===ue.YI.UN)continue;let u=!!t.tableView&&Array.from(t.tableView.viewers).some(e=>"Sequence Position Statistics"===e.type);const h=(e,t)=>Number.isNaN(e)||null==e?t:e,d=()=>h(Math.max(Number.parseInt(e.getTag(ue.gp.positionShift)??"0"),0),0)+1,m=()=>h(Number.parseInt(e.getTag(ue.gp.selectedPosition)??"-2"),-2),p=()=>$e.Jy.getFontSettings(e).fontWidth;let g=0,f=0;const y=e.categories;for(let e=0;e<y.length;e++){const t=y[e];t&&t.length>f&&(f=t.length,g=e)}const b=y[g],w=l.splitter(b),v=w?w.length:30,C=e.getTag(ue.gp.annotations)?24:0,A={WITH_TITLE:58,WITH_WEBLOGO:107+C,WITH_BOTH:156+C};let T;T=e.length>1e5||v<50?A.WITH_TITLE+C:e.length>5e4?A.WITH_WEBLOGO:A.WITH_BOTH;let E=null,S=null;const M=r.debounce(c.merge(n.onFilterChanged,n.onDataChanged.pipe((0,R.filter)(t=>t?.args?.column===e))),100).subscribe(()=>{Ao.clearAllCaches(),E&&(E.resetViewportTracking(),E.forceUpdate()),S&&(S.resetViewportTracking(),S.forceUpdate()),setTimeout(()=>{t.isDetached||t.invalidate()},50)});s(M);const x=o=>{const c=[],h=new Co(e,"Annotations");h.hasRegions()&&c.push({id:"annotations",track:h,priority:0});const g=new To(l,v,45,"WebLogo");E=g,o&&(g.setMonomerLib(o),g.setBiotype(l.defaultBiotype||"HELM_AA")),g.setupDefaultTooltip(),c.push({id:"weblogo",track:g,priority:1});const f=new Eo(l,v,45,"default","Conservation");S=f,c.push({id:"conservation",track:f,priority:2});const y=new wo({canvas:t.overlay,headerHeight:T,totalPositions:v+1,onPositionChange:(n,i)=>{setTimeout(()=>{const o=d(),s=m();if(o!==i.start&&e.setTag(ue.gp.positionShift,(i.start-1).toString()),s!==n&&(e.setTag(ue.gp.selectedPosition,n.toString()),n>=0&&!u&&t.tableView&&ee()(t.dataFrame?.columns.numerical).find(e=>!0))){u=!0;const n=t.tableView.addViewer("Sequence Position Statistics",{sequenceColumnName:e.name});t.tableView.dockManager.dock(n,r.DOCK_TYPE.DOWN,null,"Sequence Position Statistics",.4)}})},onHeaderHeightChange:e=>{t.isDetached||e<A.WITH_TITLE||setTimeout(()=>t.props.colHeaderHeight=e)}},i);y.setupTooltipHandling(),c.sort((e,t)=>e.priority-t.priority),c.forEach(({id:e,track:t})=>{y.addTrack(e,t)}),y.setSelectionData(n,e,l),v>50&&!a&&(t.props.colHeaderHeight=T,setTimeout(()=>{t.isDetached||(i.width=400)},300)),s({unsubscribe:()=>y.detach()});const b=i.column;s(t.onCellRender.subscribe(t=>{const n=t.cell;if(!n||!n.isColHeader||n?.tableColumn?.dart!==b?.dart)return;const i=t.bounds;if(!i)return;y.headerHeight=i.height;const o=p();y.positionWidth=o+8;const s=d();y.draw(i.x,i.y,i.width,i.height,m(),s,t,e.name)}))};(0,ye.pj)().then(e=>{const t=e.getMonomerLib();x(t)}).catch(e=>{o.shell.warning("Failed to initialize monomer library"),console.error("Failed to initialize monomer library:",e)})}},1e3)},t=(o.events.onViewerAdded.subscribe(t=>{if(!(t.args&&t.args.viewer instanceof r.Grid))return;const n=t.args.viewer;e(n)}),o.shell.tableViews);for(const n of t){const t=n?.grid;t&&e(t)}}()}()),await qo}static sequenceTooltip(e){const t=new Pi(e,Uo.seqHelper);return t.init().then(()=>{}).catch(e=>{const t=e instanceof Error?e.message:e.toString();o.shell.error(t)}),t}static async standardiseMonomerLibrary(e){return await async function(e){const t=JSON.parse(e);if(!t||!Array.isArray(t)||0===t.length)throw new Error("Invalid library format, expected an array of monomers");const n=(await xn(t)).map(e=>({...e,lib:void 0,wem:void 0}));return JSON.stringify(n,null,2)}(e)}static async matchWithMonomerLibrary(e,t,n="PEPTIDE"){const i=await async function(e,t,n,i="PEPTIDE"){const s=n.duplicateMonomers?.[i]??{},a=r.Func.find({package:"Chem",name:"convertMoleculeNotation"})[0];if(!a)throw new Error("Function convertMoleculeNotation not found, please install Chem package");const l=n.getMonomerSymbolsByType(i).map(e=>n.getMonomer(i,e)).filter(e=>e&&(e.smiles||e.molfile)),c=await xn(l);c.forEach((e,t)=>{e.lib=l[t].lib});const{cappedMap:u,uncappedMap:h}=await async function(e,t,n){const i={};for(const t of e){if(!t.smiles)continue;const e={symbol:t.symbol,smiles:t.smiles,original:t.smiles,source:t.lib?.source??""};i[t.smiles]||(i[t.smiles]=[]),i[t.smiles].push(e)}const o=e.map((e,n)=>({symbol:e.symbol,smiles:Fn(e.smiles??"",e.rgroups??[]),original:e.smiles,source:t[n]?.lib?.source??""})).filter(e=>!!e.smiles&&!e.smiles.includes("[*:")),s=r.Column.fromList(r.COLUMN_TYPE.STRING,"CappedSmiles",o.map(e=>e.smiles));s.semType=r.SEMTYPE.MOLECULE;const a=await n.apply({molecule:s,targetNotation:r.chem.Notation.Smiles});if(!a||a.length!==s.length)throw new Error("Error canonicalizing capped monomer SMILES");const l={},c=a.toList();for(let e=0;e<c.length;e++){const t=c[e];if(!t)continue;o[e].smiles=t;const n=o[e];l[t]||(l[t]=[]),l[t].push(n)}return{cappedMap:l,uncappedMap:i}}(c,l,a),d=await async function(e,t,n){const i=e.col(t).toList().map(e=>{if(!e)return e;try{const t=e.includes("\n");return Hn([],t?void 0:e,t?e:void 0)}catch(t){return e}}),o=r.Column.fromList(r.COLUMN_TYPE.STRING,"MoleculesCorrected",i);o.semType=r.SEMTYPE.MOLECULE,r.DataFrame.fromColumns([o]);const s=await n.apply({molecule:o,targetNotation:r.chem.Notation.Smiles});if(!s||s.length!==o.length)throw new Error("Error canonicalizing molecules");return s.toList()}(e,t,a),m=new Array(d.length).fill(null).map(()=>[]),p=[];for(let e=0;e<d.length;e++){const t=d[e];if(!t)continue;const n=An(t,u,h);n.length>0?m[e]=n:p.push(e)}if(p.length>0)try{const{fpMap:e}=await async function(e){const t=Object.keys(e);if(0===t.length)return{fpMap:{},cappedSmilesList:[]};const n=r.Column.fromList(r.COLUMN_TYPE.STRING,"MonomerSmiles",t);n.semType=r.SEMTYPE.MOLECULE;const i=await o.functions.call("Chem:getMorganFingerprints",{molColumn:n}),s={};for(let n=0;n<i.length;n++){const o=i.get(n);if(!o)continue;const r=o.toBinaryString(),a=e[t[n]]??[];s[r]||(s[r]=[]),s[r].push(...a)}return{fpMap:s,cappedSmilesList:t}}(u),t=await async function(e,t,n){const i=new Map;if(0===e.length||0===Object.keys(n).length)return i;const s=e.map(e=>t[e]??""),a=s.map(e=>{if(!e)return"";const t=Fn(e,Cn);return t!==e?o.chem.convert(t,r.chem.Notation.Unknown,r.chem.Notation.Smiles):e}),l=r.Column.fromList(r.COLUMN_TYPE.STRING,"UnmatchedMols",s);l.semType=r.SEMTYPE.MOLECULE;const c=r.Column.fromList(r.COLUMN_TYPE.STRING,"UnmatchedMolsCapped",a);c.semType=r.SEMTYPE.MOLECULE;const[u,h]=await Promise.all([o.functions.call("Chem:getMorganFingerprints",{molColumn:l}),o.functions.call("Chem:getMorganFingerprints",{molColumn:c})]);for(let t=0;t<e.length;t++){const o=e[t],s=u.get(t);if(s){const e=n[s.toBinaryString()];if(e&&e.length>0){i.set(o,e);continue}}const r=h.get(t);if(r){const e=n[r.toBinaryString()];e&&e.length>0&&i.set(o,e)}}return i}(p,d,e);for(const[e,n]of t)m[e]=n}catch(e){console.warn("Fingerprint fallback matching failed, continuing with SMILES matches only:",e)}const g=e.clone(),f=g.columns.addNewString(g.columns.getUnusedName("Matched monomer symbol")),y=g.columns.addNewString(g.columns.getUnusedName("Matched monomer smiles"));y.semType=r.SEMTYPE.MOLECULE;const b=g.columns.addNewString(g.columns.getUnusedName("Matched monomer source")),w=g.columns.addNewInt(g.columns.getUnusedName("Match count")),v=g.columns.addNewString(g.columns.getUnusedName("Match method"));g.columns.setOrder([t,f.name,y.name,b.name,w.name,v.name]);for(let e=0;e<m.length;e++){const t=m[e];if(0===t.length)continue;const n=Tn(t),i=En(n,s);f.set(e,n.map(e=>e.symbol).join(" | "),!1),y.set(e,n[0].original??n[0].smiles,!1),b.set(e,i,!1),w.set(e,n.length,!1);const o=p.includes(e)?"fingerprint":"exact";v.set(e,o,!1)}return g}(e,t.name,Uo.monomerLib,n);o.shell.addTableView(i)}static getBioLib(){return Uo.monomerLib}static getSeqHandler(e){return Uo.seqHelper.getSeqHandler(e)}static getRegionPanel(e){const t="getRegionTopMenu",n=r.Func.find({package:Uo.name,name:t});if(1!==n.length)throw new Error(`Package '${Uo.name}' func '${t}' not found`);const i=n[0].prepare({table:e.dataFrame,sequence:e});return new Ri(i,Uo.seqHelper).widget()}static async libraryPanel(e){return async function(){const e=s.label("Manage monomer libraries");return zn()(e).addClass("d4-link-action"),e.onclick=async()=>await ti(),new r.Widget(e)}()}static GetRegionEditor(e){try{new Ri(e,Uo.seqHelper).dialog()}catch(e){const t=e instanceof Error?e.message:e.toString(),n=e instanceof Error?e.stack:void 0;o.shell.error(`Get region editor error: ${t}`),Uo.logger.error(t,void 0,n)}}static SplitToMonomersEditor(e){const t=new yi;s.dialog({title:"Split to Monomers"}).add(t.paramsUI).onOK(async()=>e.func.prepare(t.funcParams).call(!0)).show()}static SequenceSpaceEditor(e){const t=new N({semtype:r.SEMTYPE.MACROMOLECULE}),n=s.dialog({title:"Sequence Space"}).add(t.getEditor()).onOK(async()=>{const n=t.getParams();return e.func.prepare({molecules:n.col,table:n.table,methodName:n.methodName,similarityMetric:n.similarityMetric,plotEmbeddings:n.plotEmbeddings,options:n.options,preprocessingFunction:n.preprocessingFunction,clusterEmbeddings:n.clusterEmbeddings}).call()});n.history(()=>({editorSettings:t.getStringInput()}),e=>t.applyStringInput(e.editorSettings)),n.show()}static SeqActivityCliffsEditor(e){const t=new Ce({semtype:r.SEMTYPE.MACROMOLECULE}),n=s.dialog({title:"Activity Cliffs"}).add(t.getEditor()).onOK(async()=>{const n=t.getParams();return e.func.prepare({table:n.table,molecules:n.col,activities:n.activities,similarity:n.similarityThreshold,methodName:n.methodName,similarityMetric:n.similarityMetric,preprocessingFunction:n.preprocessingFunction,options:n.options}).call()});n.history(()=>({editorSettings:t.getStringInput()}),e=>t.applyStringInput(e.editorSettings)),n.show()}static customSequenceCellRenderer(){return new We}static fastaSequenceCellRenderer(){return new We}static separatorSequenceCellRenderer(){return new We}static bilnSequenceCellRenderer(){return new We}static refineNotationProviderForBiln(e,t,n){if("-"!==n)return!1;if(!Object.keys(t.freq).some(e=>e.match(/^.+\(\d{1,2},\d{1,2}\)$/))){const e=Object.keys(t.freq).filter(e=>e.startsWith("[")),n=Object.keys(t.freq).filter(e=>e.endsWith("]"));if(Object.keys(t.freq).filter(e=>(e.includes("[")||e.includes("]"))&&!e.startsWith("[")&&!e.endsWith("]")).length>0||0==e.length||0==n.length)return!1;if(Object.keys(t.freq).some(e=>e.startsWith("*")||e.startsWith("$")||e.startsWith("@")||e.startsWith("%")))return!1}return e.setTag("aligned","SEQ"),e.setTag("alphabet","UN"),e.setTag(".alphabetIsMultichar","true"),e.meta.units=ue.Hi.BILN,e.temp[me.j.notationProvider]=new xo(n,Uo.seqHelper,e),!0}static macroMolColumnPropertyPanel(e){return function(e){const t=Array.from(e.dataFrame.columns).filter(e=>e.semType===r.SEMTYPE.MOLECULE).map(e=>e.name);new Set(t).delete(e.name);let i=Uo.properties?Uo.properties.maxMonomerLength:4;if(Re.gp.maxMonomerLength in e.tags){const t=parseInt(e.getTag(Re.gp.maxMonomerLength));i=isNaN(t)?i:t}if(".mm.cellRenderer.maxMonomerLength"in e.temp){const t=parseInt(e.temp[".mm.cellRenderer.maxMonomerLength"]);i=isNaN(t)?i:t}const o=s.input.int("Max Monomer Length",{value:i,nullable:!0,min:1,max:50,step:1,onValueChanged:t=>{if(0==t)setTimeout(()=>{o.value=null},0);else{const n=t??"",i=null==n?"":n.toString();e.temp[".mm.cellRenderer.maxMonomerLength"]=i,e.temp[".mm.cellRenderer.settingsChanged"]=ke.s.true,e.dataFrame.fireValuesChanged()}},tooltipText:"The max length of monomer symbol displayed without shortening, empty to no limit"});let a=Uo.properties?Uo.properties.fontSize:12;".mm.cellRenderer.fontSize"in e.temp&&e.temp[".mm.cellRenderer.fontSize"]&&!isNaN(e.temp[".mm.cellRenderer.fontSize"])&&(a=e.temp[".mm.cellRenderer.fontSize"]);const l=s.input.int("Font Size",{value:a,nullable:!0,min:1,max:50,step:1,onValueChanged:t=>{if(t&&t>0){const n=t??12;e.temp[".mm.cellRenderer.fontSize"]=n,e.temp[".mm.cellRenderer.settingsChanged"]=ke.s.true,e.dataFrame.fireValuesChanged()}},tooltipText:"The font size of monomer symbol in sequence renderer"}),c=s.input.int("Monomer Margin",{value:e.temp[".mm.cellRenderer.gapLength"]??0,onValueChanged:t=>{e.temp[".mm.cellRenderer.gapLength"]=t,e.temp[".mm.cellRenderer.settingsChanged"]=ke.s.true,e.dataFrame.fireValuesChanged()},tooltipText:"The size of margin between monomers (in pixels)"}),u=s.input.bool("Color Code",{value:null==e?.temp["color-code"]||e.temp["color-code"],onValueChanged:t=>{e.temp["color-code"]=t,e.dataFrame.fireValuesChanged()},tooltipText:"Color code"}),h=s.input.string("Reference Sequence",{value:null!=e?.temp["reference-sequence"]?e?.temp["reference-sequence"]:"",nullable:!0,onValueChanged:t=>{e.temp["reference-sequence"]=t,e.dataFrame.fireValuesChanged()},tooltipText:"Reference sequence is not empty, then the sequence will be render \nas a difference from the reference sequence"}),d=s.input.bool("Compare with current",{value:null==e?.temp["compare-with-current"]||e.temp["compare-with-current"],onValueChanged:t=>{e.temp["compare-with-current"]=t,e.dataFrame.fireValuesChanged()},tooltipText:'When on, all sequences get rendered in the "diff" mode'});let m=null;e.meta.units!==ue.Hi.HELM&&(m=s.input.bool("Multiline Rendering",{value:"true"===e.getTag("renderMultiline"),onValueChanged:t=>{e.tags.renderMultiline=t?"true":"false",e.dataFrame.fireValuesChanged()},tooltipText:"Render sequences across multiple lines when they exceed cell width"}));const p=[l,o,c,h,u,d];m&&p.push(m);const g=s.inputs(p),f=(0,Et.Ln)(e),y=s.divV([]);if(f.length>0){const t=e.getTag(ue.gp.numberingScheme),i=f.filter(e=>e.category===St.eI.Structure),o=f.filter(e=>e.category===St.eI.Liability);if(t&&y.append(s.divText(`Numbering: ${t}`,{style:{fontSize:"12px",marginBottom:"4px"}})),i.length>0){const e=i.map(e=>e.name).join(", ");y.append(s.divText(`Regions: ${e}`,{style:{fontSize:"12px",marginBottom:"4px"}}))}if(o.length>0){const e=o.reduce((e,t)=>{const n=t.description?.match(/\((\d+) hits\)/);return e+(n?parseInt(n[1]):0)},0);y.append(s.divText(`Liabilities: ${o.length} rules (${e} hits)`,{style:{fontSize:"12px",marginBottom:"4px"}}))}const r=s.button("Manage",()=>{Promise.resolve().then(n.bind(n,9287)).then(e=>e.showAnnotationManagerDialog())}),a=s.button("Clear All",()=>{(0,Et.OW)(e.dataFrame,e),e.dataFrame.fireValuesChanged()});y.append(s.divH([r,a],{style:{gap:"4px",marginTop:"4px"}}))}else{y.append(s.divText("No annotations",{style:{fontSize:"12px",color:"#888"}}));const e=s.button("Scan Liabilities",()=>{Promise.resolve().then(n.bind(n,9422)).then(e=>e.showLiabilityScannerDialog())}),t=s.button("Apply Numbering",()=>{Promise.resolve().then(n.bind(n,6839)).then(e=>e.showNumberingSchemeDialog())});y.append(s.divH([e,t],{style:{gap:"4px",marginTop:"4px"}}))}const b=s.accordion();return b.addPane("Renderer Settings",()=>g),b.addPane("Annotations",()=>y),new r.Widget(b.root)}(e)}static compositionAnalysisWidget(e){return function(e,t,n){const i=s.div();i.classList.add("macromolecule-cell-comp-analysis-host");const o=e.cell.column.tags[ue.gp.alphabet],a=o===ue.YI.DNA||o===ue.YI.RNA?Fe.o.NUCLEOTIDE:Fe.o.AA,l={},c=n.getSeqHandler(e.cell.column),u=e.cell.rowIndex,h=c.getSplitted(u),d={};ee().count(0).take(h.length).filter(e=>!h.isGap(e)).forEach(e=>{let t=h.getCanonical(e);a===Fe.o.NUCLEOTIDE&&c.isHelm()&&"("===t[1]&&")"===t[t.length-2]&&(t=t.substring(2,t.length-2));const n=l[t]||0;if(l[t]=n+1,!d[t]&&h.graphInfo?.polymerTypes){const n=h.graphInfo.polymerTypes[e];d[t]=(0,Oe.MD)(n)}});const m=(0,Si.F)(l,a,t,Object.keys(d).length?d:void 0);return Array.from(m.rows).forEach(e=>{const t=e.getElementsByClassName("macromolecule-cell-comp-analysis-bar")[0].style.backgroundColor;e.cells[0].style.color=t}),i.appendChild(m),new r.Widget(i)}(e,Uo.monomerLib,Uo.seqHelper)}static monomerInfoPanel(e){return function(e,t){const n=e.value;if(!n)return new r.Widget(s.divText("No monomer value."));const i=function(e){try{const t=e.cell?.column;if(t)return t.temp[pe.sc]??null}catch{}return null}(e),o=(i?i.canonicalize(n):n).split(pe.ot).map(e=>e.trim()).filter(e=>e.length>0).map(e=>({symbol:e,monomer:t.getMonomer(null,e)})).filter(e=>null!==e.monomer);if(0===o.length)return new r.Widget(s.divText(`Monomer '${n}' not found in the library.`));const a=s.accordion("Monomer");if(1===o.length){const e=o[0].monomer;a.addPane("Details",()=>Bn(e),!0),a.addPane("Molecule",()=>Vn(e),!0)}else for(const{symbol:e,monomer:t}of o)a.addPane(e,()=>s.divV([Bn(t),s.element("hr"),Vn(t)]),!0);return new r.Widget(a.root)}(e,Uo.monomerLib)}static macromoleculeDifferenceCellRenderer(){return new je}static sequenceAlignment(e,t,n,i,o){const s=new ct(i,o,n,t);return"Local alignment"==e?s.smithWaterman():s.needlemanWunsch()}static webLogoViewer(){return new tt.oP}static vdRegionsViewer(){return new rt}static getRegion(e,t,n,i){return Ii(e,t??null,n??null,i??null)}static async getRegionTopMenu(e,t,n,i,s){const r=Ii(t,n??null,i??null,s??null);t.dataFrame.columns.add(r),await o.data.detectSemanticTypes(t.dataFrame)}static applyNumberingScheme(){(0,Ho.showNumberingSchemeDialog)()}static scanLiabilities(){(0,Do.showLiabilityScannerDialog)()}static manageAnnotations(){(0,Fo.showAnnotationManagerDialog)()}static sequenceColumnInput(e,t){return Ro.create(e,t)}static async activityCliffs(e,t,n,i,c,u,h,d,m){if(_e(e),!(0,di.V)(t,"Activity Cliffs"))return;const p=c===l.c.UMAP?2e5:2e4,g=c===l.c.UMAP?5e3:2e3;if(e.rowCount>p)return void o.shell.warning(`Too many rows, maximum for sequence activity cliffs is ${p}`);const f=Se(e),y=async()=>{await r.Func.find({name:"seqActivityCliffsTransform"})[0].prepare({table:e,molecules:t,activities:n,similarity:i,methodName:c,similarityMetric:u,options:JSON.stringify(d),isDemo:m,axesNames:f}).call(void 0,void 0,{processed:!1}),_e(e);const s=o.shell.tv,a=`Molecules: ${t.name}, activities: ${n.name}, method: ${c}, ${d?`options: ${JSON.stringify(d)},`:""} similarity: ${u}, similarity cutoff: ${i}`;s.addViewer(r.VIEWER.SCATTER_PLOT,{xColumnName:f[0],yColumnName:f[1],color:n.name,showXSelector:!1,showYSelector:!1,showSizeSelector:!1,showColorSelector:!1,markerMinSize:5,markerMaxSize:25,title:"Activity cliffs",initializationFunction:"seqActivityCliffsInitFunction",description:a,descriptionVisibilityMode:"Never"})},b=r.TaskBarProgressIndicator.create("Running sequence activity cliffs ...");try{e.rowCount>g&&!d?.[a.vb]?await new Promise((e,t)=>{s.dialog().add(s.divText("Activity cliffs analysis might take several minutes.\n Do you want to continue?")).onOK(async()=>{y().then(()=>e()).catch(e=>t(e))}).onCancel(()=>{e()}).show()}):await y()}catch(e){const[t,n]=(0,we.AP)(e);throw Uo.logger.error(t,void 0,n),e}finally{b.close()}}static async seqActivityCliffsInitFunction(e){const t=e.dataFrame.getTag("seqActivityCliffsParams");if(!t)return void o.shell.error("Sequence activity cliffs parameters not found in table tags");const n=JSON.parse(t),i=e.dataFrame.col(n.seqColName),s=e.dataFrame.col(n.activityColName),a=r.Func.find({name:"macromoleculePreprocessingFunction",package:"Bio"})[0],l=await a.apply({col:i,metric:n.similarityMetric}),c=[e.getOptions().look.xColumnName,e.getOptions().look.yColumnName],u={units:i.meta.units,aligned:i.getTag(ue.gp.aligned),separator:i.getTag(ue.gp.separator),alphabet:i.getTag(ue.gp.alphabet)};await le(e,e.dataFrame,i,l,s,c,n.similarity,n.similarityMetric,n.options??{},r.SEMTYPE.MACROMOLECULE,u,dt,mt,yt,void 0,n.isDemo)}static async seqActivityCliffsTransform(e,t,i,o,s,a,l,c,u){await e.meta.detectSemanticTypes();const h=r.Func.find({name:"macromoleculePreprocessingFunction",package:"Bio"})[0];u||(u=Se(e)),await async function(e,t,i,o,s,r,a,l){const c=l.inputs,u=await l.apply({[c[0].name]:t,[c[1].name]:s,...a.preprocessingFuncArgs??{}});let h=[];if(r===I){const t=await function(e,t,i,o,s,r,a=10,l=!1,c=2){const u=new Worker(new URL(n.p+n.u(980),n.b));let h;return u.postMessage({data:e,threshold:t,weights:i,aggregationMethod:o,distanceFns:s,distanceFnArgs:r,maxIterations:a,useWebGPU:l,inflate:c}),{promise:new Promise((e,t)=>{h=e,u.onmessage=t=>{setTimeout(()=>u.terminate(),100),e(t.data.res)},u.onerror=e=>{setTimeout(()=>u.terminate(),100),t(e)}}),terminate:()=>{try{h(null),u.terminate()}catch(e){console.error(e)}}}}([u.entries],o,[1],"MANHATTAN",[s],[u.options??{}],a?.maxIterations??5,a.useWebGPU??!1).promise;e.columns.addNewInt(e.columns.getUnusedName("MCL Cluster")).init(e=>t.clusters[e]),h=[t.embedX,t.embedY]}else h=await W([u.entries],r,[s],[1],"MANHATTAN",{...a,distanceFnArgs:[u.options??{}]});if(h.length!==i.length)throw new Error("Number of axes names should be equal to number of embedding dimensions");for(let t=0;t<h.length;++t)e.columns.addNewFloat(i[t]).init(e=>h[t][e])}(e,t,u,o,a,s,JSON.parse(l??"{}"),h);const d={seqColName:t.name,activityColName:i.name,similarityMetric:a,similarity:o,options:l??{},isDemo:c};e.setTag("seqActivityCliffsParams",JSON.stringify(d))}static async macromoleculePreprocessingFunction(e,t,n=1,i=.6,o="Morgan"){if(e.semType!==r.SEMTYPE.MACROMOLECULE)return{entries:e.toList(),options:{}};const{seqList:s,options:a}=await ut(e,t,o,n,i);return{entries:s,options:a}}static async helmPreprocessingFunction(e,t){e.version!==e.temp["last-invalidated-version"]&&await(0,ht.BQ)(e,Uo.seqHelper,!1);const n=e.temp["monomeric-mols"],i=await o.functions.call("Chem:getMorganFingerprints",{molColumn:n}),s=new Array(i.length).fill(null);for(let e=0;e<i.length;e++){if(i.isNone(e)||!i.get(e))continue;const t=i.get(e);s[e]=G.A.fromUint32Array(t.length,new Uint32Array(t.getBuffer().buffer))}return{entries:s,options:{}}}static async sequenceSpaceTopMenu(e,t,n,i,s,a,l,c,u){if(_e(e),!(0,di.V)(t,"Sequence Space"))return;const h=e.columns.getUnusedName("Cluster (DBSCAN)"),d=Se(e);let m;if(await r.Func.find({name:"sequenceSpaceTransform"})[0].prepare({table:e,molecules:t,methodName:n,similarityMetric:i,plotEmbeddings:!1,options:JSON.stringify(l),clusterEmbeddings:c,embedColsNames:d,clusterColName:h}).call(void 0,void 0,{processed:!1}),s){_e(e),m=o.shell.tv.scatterPlot({x:d[0],y:d[1],title:"Sequence space"});const s=`Molecules column: ${t.name}, method: ${n}, ${l?`options: ${JSON.stringify(l)},`:""} similarity: ${i}`;m.setOptions({description:s,descriptionVisibilityMode:"Never"}),c&&(m.props.colorColumnName=h)}return m}static async sequenceSpaceTransform(e,t,n,i,s,l,c,u,h){await e.meta.detectSemanticTypes();const d=r.Func.find({name:"macromoleculePreprocessingFunction",package:"Bio"})[0],m=JSON.parse(l??"{}"),p=o.shell.tv?.dataFrame==e?o.shell.tv:void 0;return await xe(e,[t],n,[i],[1],[d],"MANHATTAN",s,c??!1,{...m,preprocessingFuncArgs:[m.preprocessingFuncArgs??{}]},{fastRowCount:1e4,scatterPlotName:"Sequence space",bypassLargeDataWarning:m?.[a.vb],tableView:p,embedColsNames:u,clusterColName:h})}static async moleculesToHelmTopMenu(e,t){const n=Uo.monomerLib,i=JSON.stringify(n.toJSON()),o=r.FileInfo.fromString("monomerLib.json",i);await $o.molToHelmConverterPy(e,t,o);const s=e.columns.toList().find(e=>e.name.toLowerCase().includes("regenerated sequence")&&e.semType!==r.SEMTYPE.MACROMOLECULE);s&&(s.meta.units=ue.Hi.HELM,s.semType=r.SEMTYPE.MACROMOLECULE,s.setTag("cell.renderer","helm"))}static async moleculeToHelmSingle(e){const t=r.Column.fromStrings("molecule",[e]);t.semType=r.SEMTYPE.MOLECULE;const n=r.DataFrame.fromColumns([t]);await Wo.moleculesToHelmTopMenu(n,t);const i=n.columns.toList().find(e=>e.name.toLowerCase().includes("regenerated sequence"))?.get(0);return i??""}static async toAtomicLevel(e,t,n=!0,i=!1){const o=r.TaskBarProgressIndicator.create("Converting to atomic level ...");try{await qo;const o=t.temp[".mm.cellRenderer.overriddenLibrary"]??Uo.monomerLib,s=Uo.seqHelper,r=Uo.rdKitModule;await(0,$i.V)(e,t,n,i,o,s,r)}finally{o.close()}}static async toAtomicLevelAction(e){if(!e?.dataFrame)throw new Error("Sequence column is not found or its data frame is not empty");const t=r.Func.find({name:"toAtomicLevel",package:"Bio"})[0];if(!t)throw new Error("To Atomic level Function not found");t.prepare({table:e.dataFrame,seqCol:e}).edit()}static async toAtomicLevelPanel(e){return async function(e){const t=await lo(e);if(t.errorText||!t.mol)return r.Widget.fromRoot(s.divText(t.errorText??"No structure generated"));try{const e=r.SemanticValue.fromValueType(t.mol,r.SEMTYPE.MOLECULE),n=s.panels.infoPanel(e);let i=null;if(n){const e=s.accordion("Sequence Molfile details");e.addPane("Explore",()=>n.root),i=r.Widget.fromRoot(e.root)}const a=o.chem.drawMolecule(t.mol,300,300,!1);return a.style.cursor="pointer",s.tooltip.bind(a,"Click to expand"),a.onclick=()=>{const e=window.innerWidth-200,n=window.innerHeight-200,i=o.chem.drawMolecule(t.mol,e,n,!1);s.dialog({title:"Molecule"}).add(i).showModal(!0)},i&&i.root.prepend(a),i??r.Widget.fromRoot(a)}catch(e){Uo.logger.error(e)}return r.Widget.fromRoot(s.divText("No structure generated"))}(e)}static async toAtomicLevelSingleSeq(e){const t=e.includes("$$"),n=e.split("").filter(e=>"/"==e).length>2,i=e.split("").filter(e=>"-"==e).length>2,o=r.Column.fromStrings("sequence",[e]);o.semType=r.SEMTYPE.MACROMOLECULE,o.meta.units=t?ue.Hi.HELM:n?ue.Hi.SEPARATOR:i?ue.Hi.BILN:ue.Hi.FASTA,o.setTag(ue.gp.aligned,"SEQ"),n&&o.setTag(ue.gp.separator,"/"),i&&o.setTag(ue.gp.separator,"-");const s=e.split("").every(e=>"AGCT".includes(e)||"/"===e||"-"===e),a=!s&&e.split("").every(e=>"AGCU".includes(e)||"/"===e||"-"===e);o.setTag(ue.gp.alphabet,s?ue.YI.DNA:a?ue.YI.RNA:"UN"),o.setTag(ue.gp.alphabetIsMultichar,"true");const l=r.DataFrame.fromColumns([o]).cell(0,"sequence"),c=r.SemanticValue.fromTableCell(l),u=await lo(c);if(u.errorText||!u.mol)throw new Error(u.errorText);return u.mol}static async sequence3dStructureWidget(e){return async function(e){const t=r.TaskBarProgressIndicator.create("Creating 3D view");let n,i="";try{await(r.Func.find({name:"getPdbHelper"})[0]?.apply({}));try{const a=await lo(e);if(a.errorText||!a.mol)return n=s.divText(a.errorText??"No structure generated"),t.close(),new r.Widget(n);const l=a.mol;i=await o.functions.call("Bio:Embed",{molecule:l});const c=Fi.Molecule.fromMolfile(i);c?i=c.toMolfile():console.warn("Failed to convert molv3 to molv2")}catch(e){console.warn(e)}try{i=i.replaceAll("\\n","\n");const e=new Blob([i],{type:"text/plain"}),t=s.div([],{classes:"d4-ngl-viewer",id:"ngl-3d-host"});t.style.setProperty("height","100%","important");const o=new NGL.Stage(t,{backgroundColor:"white"});o.loadFile(e,{ext:"sdf"}).then(function(e){o.setSize(300,300),e.addRepresentation("ball+stick"),e.autoView()}),n=s.div([t],{style:{aspectRatio:"1"}})}catch(e){n=s.divText("Couldn't get 3D structure")}}catch(e){n=s.divText("Couldn't get 3D structure")}return t.close(),new r.Widget(n)}(e)}static multipleSequenceAlignmentDialog(){(0,pi.D)({},Uo.seqHelper).catch(e=>{const[t,n]=(0,we.AP)(e);if(e instanceof mi.Ap)return o.shell.warning(e.element),void Uo.logger.warning(t);o.shell.error(t),Uo.logger.error(t,void 0,n)})}static async alignSequences(e=null,t=null,n){return(0,pi.D)({col:e,clustersCol:t,...n},Uo.seqHelper)}static async pepseaMsa(e,t="mafft --auto",n=1.53,i=0){return(0,gi.Gf)(e,t,n,i)}static async immunumAntibodyNumbering(e,t,n){return(0,ko.C)(t,n)}static compareSequences(){!function(){const e=o.shell.tv;if(!e||!e.dataFrame)return void o.shell.error("No active table");const t=e.dataFrame,n=(0,Ne.me)();if(n.length<2)return void o.shell.error("Current table needs at least two Macromolecule columns");const i=n.map(e=>e.name),a=s.input.choice("Sequence column 1",{value:i[0],items:i}),l=s.input.choice("Sequence column 2",{value:i[1],items:i}),c=s.input.string("Result column name",{value:""});c.setTooltip("Leave empty to auto-generate from the chosen columns"),s.dialog({title:"Compare Sequences"}).add(a).add(l).add(c).onOK(()=>{const e=t.col(a.value??""),n=t.col(l.value??"");if(!e||!n)return void o.shell.error("Could not resolve chosen columns");const i=function(e,t){return e===t?"Please choose two distinct columns":e.semType!==r.SEMTYPE.MACROMOLECULE||t.semType!==r.SEMTYPE.MACROMOLECULE?"Both columns must be Macromolecule semantic type":e.getTag(r.TAGS.UNITS)!==t.getTag(r.TAGS.UNITS)?"Columns must use the same notation (units)":(e.getTag(ue.gp.separator)??"")!==(t.getTag(ue.gp.separator)??"")?"Columns must use the same separator":(e.getTag(ue.gp.alphabet)??"")!==(t.getTag(ue.gp.alphabet)??"")?"Columns must use the same alphabet":null}(e,n);if(null!=i)return void o.shell.error(i);const s=(c.value??"").trim()||`${e.name} vs ${n.name}`,u=function(e,t,n){const i=Math.min(e.length,t.length),o=new Array(i);for(let n=0;n<i;n++){const i=e.get(n)??"",s=t.get(n)??"";o[n]=`${i}#${s}`}const s=n??`${e.name} vs ${t.name}`,a=r.Column.fromStrings(s,o);a.semType=Ve.uF.MACROMOLECULE_DIFFERENCE;const l=e.getTag(ue.gp.separator);null!=l&&(a.tags[ue.gp.separator]=l);const c=e.getTag(r.TAGS.UNITS);null!=c&&(a.tags[r.TAGS.UNITS]=c);const u=e.getTag(ue.gp.aligned);null!=u&&(a.tags[ue.gp.aligned]=u);const h=e.getTag(ue.gp.alphabet);return null!=h&&(a.tags[ue.gp.alphabet]=h),a.tags[r.TAGS.CELL_RENDERER]=Ve.uF.MACROMOLECULE_DIFFERENCE,a.temp[me.j.notationProvider]=e.temp[me.j.notationProvider],a}(e,n,t.columns.getUnusedName(s));t.columns.add(u)}).show()}()}static async compositionAnalysis(){const e=o.shell.tv,t=e.dataFrame.columns.toList().filter(e=>e.semType==r.SEMTYPE.MACROMOLECULE&&(Uo.seqHelper.getSeqHandler(e),!0)),n=async t=>{if(!(0,di.V)(t,"Composition"))return;const n=e.addViewer("WebLogo",{sequenceColumnName:t.name});o.shell.tv.dockManager.dock(n,r.DOCK_TYPE.DOWN,null,"Composition analysis",.25)};let i=null;if(0!=t.length){if(t.length>1){const e=t.map(e=>e.name),i=t.find(e=>Uo.seqHelper.getSeqHandler(e).isMsa()),o=s.input.choice("Column",{value:i?i.name:e[0],items:e});s.dialog({title:"Composition Analysis",helpUrl:"https://datagrok.ai/help/datagrok/solutions/domains/bio/#sequence-composition"}).add(s.div([o])).onOK(async()=>{const e=t.find(e=>e.name==o.value)??null;e&&await n(e)}).show()}else i=t[0];i&&await n(i)}else o.shell.error("Current table does not contain sequences")}static importFasta(e){return new he.m(e).importFasta()}static importBam(e){return console.log(e),[]}static convertDialog(){const e=(0,Ne.me)()[0];(0,Tt.C)(e,Uo.seqHelper)}static convertColumnAction(e){(0,Tt.C)(e,Uo.seqHelper)}static monomerCellRenderer(){return new Ci}static async testDetectMacromolecule(e){const t=r.TaskBarProgressIndicator.create("Test detectMacromolecule..."),n=(await o.dapi.files.list(e,!0,"")).filter(e=>e.fileName.endsWith(".csv"));let i=0;const s=[];for(const a of n)try{const t=await o.dapi.files.readAsText(e+a.fullPath),n=r.DataFrame.fromCsv(t);for(const e of n.columns)await o.functions.call("Bio:detectMacromolecule",{col:e})===r.SEMTYPE.MACROMOLECULE&&s.push({file:a.path,result:"detected",column:e.name,message:`units: ${e.meta.units}`})}catch(e){s.push({file:a.path,result:"error",column:null,message:e instanceof Error?e.message:e.toString()})}finally{i+=1,t.update(100*i/n.length,`Test ${a.fileName}`)}o.shell.info("Test Demo:Files for detectMacromolecule finished."),t.close();const a=r.DataFrame.fromObjects(s);return a.name=`datasets_detectMacromolecule_${e}`,a}static async splitToMonomersTopMenu(e,t){return await async function(e,t){if(await r.delay(10),!(0,di.V)(t,"Sequence space"))return e;const n=ge(t,Uo.seqHelper);n.name="splitToMonomers";const i=t.dataFrame;for(const e of n.columns)e.semType=Ve.uF.MONOMER,e.setTag(pe.gp.alphabet,t.getTag(pe.gp.alphabet));const s=/(\d+)(?: \((\d+)\))?/,a=e=>{s.lastIndex=0;const t=e.match(s);return t?`${t[1]} (${parseInt(t[2]??"0")+1})`:e};for(let e=0;e<n.columns.length;e++){const o=n.columns.byIndex(e);o.semType=Ve.uF.MONOMER,o.setTag(pe.gp.alphabet,t.getTag(pe.gp.alphabet));const s=100;let r=0;for(;i.columns.byName(o.name)&&r<s;)o.name=a(o.name),r++;i.columns.add(o)}await o.data.detectSemanticTypes(i);for(let e=0;e<n.columns.length;e++){const t=n.columns.byIndex(e);t.setTag(r.TAGS.CELL_RENDERER,"Monomer"),t.setTag(".use-as-filter","false")}return i}(e,t)}static getHelmMonomers(e){return Uo.seqHelper.getSeqMonomers(e)}static similaritySearchViewer(){return new Ct(Uo.seqHelper)}static similaritySearchTopMenu(){const e=o.shell.v,t=e.addViewer("Sequence Similarity Search");e.dockManager.dock(t,"down")}static diversitySearchViewer(){return new At(Uo.seqHelper)}static diversitySearchTopMenu(){const e=o.shell.v,t=e.addViewer("Sequence Diversity Search");e.dockManager.dock(t,"down")}static searchSubsequenceEditor(e){const t=(0,Ne.me)();1===t.length?e.func.prepare({macromolecules:t[0]}).call(!0):new ht.a7(t,Uo.seqHelper)}static SubsequenceSearchTopMenu(e){o.shell.tv.getFiltersGroup({createDefaultFilters:!1}).updateOrAdd({type:"Bio:bioSubstructureFilter",column:e.name,columnName:e.name}),o.shell.tv.grid.scrollToCell(e,0)}static async sequenceIdentityScoring(e,t,n){const i=Uo.seqHelper;return Oi(e,t,n,fe.IDENTITY,i)}static async sequenceSimilarityScoring(e,t,n){const i=Uo.seqHelper;return Oi(e,t,n,fe.SIMILARITY,i)}static async manageMonomerLibraries(){ti()}static async manageLibrariesView(){await ni()}static async manageMonomersView(){const e=await Ln.getInstance();await e.getViewRoot()}static async manageMonomerLibrariesView(e){const t=await ni(!1);return t.parentCall=o.functions.getCurrentCall(),t}static async manageMonomerLibrariesViewTreeBrowser(e){(await(await bn.getInstance()).getAvaliableLibraryNames()).forEach(t=>{const n=t.endsWith(".json")?t.substring(0,t.length-5):t;e.item(n).onSelected.subscribe(async()=>{const e=await Ln.getInstance();(await e.getViewRoot(t,!0)).parentCall=o.functions.getCurrentCall(),e.resetCurrentRowFollowing()})})}static async monomerCollectionsApp(){return await async function(e=!0){if(e){const e=Array.from(o.shell.views).find(e=>e.name===_o.VIEW_NAME);if(e)return o.shell.v=e,e}const t=new _o,n=await t.init();return e&&o.shell.addView(n),n}(!1)}static saveAsFasta(){(0,Un.TE)()}static bioSubstructureFilter(){return new qn._i(Uo.seqHelper,Uo.logger)}static bioSubstructureFilterTest(){return new qn._i(Uo.seqHelper,Uo.logger)}static async webLogoLargeApp(){const e=r.TaskBarProgressIndicator.create("WebLogo");try{const e=new URLSearchParams(window.location.search),t=new fi(e,"webLogoLargeApp"),n=await Uo.files.readCsv("data/sample_PT_100000x5.csv");await o.data.detectSemanticTypes(n),await t.init(n)}finally{e.close()}}static async webLogoAggApp(){const e=r.TaskBarProgressIndicator.create("WebLogo ...");try{const e=new URLSearchParams(window.location.search),t=new fi(e,"webLogoAggApp"),n=await Uo.files.readCsv("samples/FASTA_PT_activity.csv");await o.data.detectSemanticTypes(n),await t.init(n)}finally{e.close()}}static async getRegionApp(){const e=r.TaskBarProgressIndicator.create("getRegion ...");try{const e=new URLSearchParams(window.location.search),t=new Ni(e,"getRegionApp");await t.init()}finally{e.close()}}static async getRegionHelmApp(){const e=r.TaskBarProgressIndicator.create("getRegion ...");try{const e=new URLSearchParams(window.location.search),t=await Uo.files.readCsv("samples/HELM_empty_vals.csv"),n=new Ni(e,"getRegionHelmApp");await n.init({df:t,colName:"HELM"})}finally{e.close()}}static longSeqTableSeparator(){const e=r.DataFrame.fromColumns((0,Pe.dW)());o.shell.addTableView(e)}static longSeqTableFasta(){const e=r.DataFrame.fromColumns([(0,Pe.Hx)(Uo.seqHelper,ue.Hi.FASTA)]);o.shell.addTableView(e)}static longSeqTableHelm(){const e=r.DataFrame.fromColumns([(0,Pe.Hx)(Uo.seqHelper,ue.Hi.HELM)]);o.shell.addTableView(e)}static addCopyMenu(e,t){!function(e,t,i){const s=Object.values(ue.Hi).filter(e=>e!==ue.Hi.CUSTOM);t.group("Copy").items(s,t=>{const n=e.column,s=e.rowIndex,r=i.getSeqHandler(n),a=t===ue.Hi.SEPARATOR?Uo.properties.defaultSeparator??"-":void 0,l=r.getJoiner({notation:t,separator:a})(r.getSplitted(s));navigator.clipboard?(navigator.clipboard.writeText(l),o.shell.info(`Value of notation '${t}' copied to clipboard`)):o.shell.warning("The clipboard functionality requires a secure origin — either HTTPS or localhost")});const r=e.column,a=(0,Et.Ln)(r);if(a.length>0&&new Li.$(r).hasAnnotations()){const e=a.filter(e=>e.category===St.eI.Structure);if(e.length>0){const s=t.group("Annotations");for(const t of e)t.start&&t.end&&s.item(`Extract ${t.name} as Column`,()=>{n.e(288).then(n.bind(n,9288)).then(e=>{try{e.extractAnnotatedRegion(r.dataFrame,r,t.name,i)}catch(e){o.shell.error(`Failed to extract region: ${e.message??e}`)}})});a.filter(e=>e.category===St.eI.Liability).length>0&&s.item("Filter: Rows with Liability Hits",()=>{n.e(288).then(n.bind(n,9288)).then(e=>{e.filterByLiabilityHits(r.dataFrame,r)})})}}}(e,t,Uo.seqHelper)}static async demoBioSimilarityDiversity(){await async function(){const e=await Uo.files.readCsv("samples/peptides-non-natural.csv"),t=o.shell.addTableView(e);Uo.files.readAsText("demo-files/bio_similarity_diversity.layout").then(async e=>{const n=r.ViewLayout.fromJson(e);await r.delay(100),t.loadLayout(n)})}()}static async demoBioSequenceSpace(){await async function(){const e=await o.functions.eval("Bio:SeqSpaceDemo"),t=await o.dapi.projects.find(e.id);await t.open()}()}static async demoBioActivityCliffs(){await async function(){o.shell.windows.showContextPanel=!0;const e=await o.functions.eval("Bio:BioDemoActivityCliffs"),t=await o.dapi.projects.find(e.id);await t.open();let n,i=null;for(const e of o.shell.tv.viewers)e.type==r.VIEWER.SCATTER_PLOT&&(i=e);try{await(0,hi.bk)(()=>{const e=i?.root.getElementsByClassName("scatter_plot_link");return!!e?.length&&(n=e[0],!0)},"",1e4),n.click()}catch(e){}}()}static async demoBioAtomicLevel(){await async function(){const e=await Uo.files.readCsv("demo-files/Atomic_Level.csv");await e.meta.detectSemanticTypes();const t=o.shell.addTableView(e);await r.delay(100),await(0,He.Qc)(e.col("helm"),e.col("molfile(helm)"),Uo.monomerLib,Uo.seqHelper,Uo.rdKitModule,!0),(0,Ne.Kd)(t.grid,"molfile(HELM)",500,300,!0),(0,Ne.Kd)(t.grid,"HELM",500,void 0,!0),e.col("molfile(helm)").setTag(".sequence-src-highlight-monomers","false"),e.col("molfile(helm)").setTag(".sequence-src-col","HELM"),o.shell.info("Hover over monomers in HELM column to highlight them in molecular structure.",{timeout:10})}()}static async demoBioSiRNA(){await async function(){const e=await Uo.files.readCsv("demo-files/SIRNA.csv"),t=await Uo.files.readAsText("demo-files/SIRNA.layout"),n=r.ViewLayout.fromJson(t);e.col("sense_seq").setTag("aligned","SEQ.MSA"),e.col("antisense_seq").setTag("aligned","SEQ.MSA");const i=o.shell.addTableView(e);await r.delay(100),i.loadLayout(n,!0),await e.meta.detectSemanticTypes(),o.shell.info("Hover over the oligo structrues to see modifications to different sugars, linkers and residues.",{timeout:10}),setTimeout(()=>{e.currentCell=e.cell(0,"oligo_helm")},300)}()}static async sdfToJsonLib(e){const t=function(e){const t=[];for(let n=0;n<e.rowCount;n++){const i={};Object.keys(de.Ec).forEach(t=>{if("symbol"===t){const o=e.get(de.Ec[t],n);i[t]="."===o?e.get(de.yw,n):o}else if("rgroups"===t){const o=e.get(de.Ec[t],n).split("\n"),s=[];o.forEach(e=>{const t={},n=e.substring(e.lastIndexOf("]")+1),i=e.match(/\[R(\d+)\]/)[1];t.capGroupSmiles="H"===n?`[*:${i}][H]`:`O[*:${i}]`,t.alternateId="H"===n?`R${i}-H`:`R${i}-OH`,t.capGroupName="H"===n?"H":"OH",t.label=`R${i}`,s.push(t)}),i[t]=s}else de.Ec[t]&&(i[t]=e.get(de.Ec[t],n))}),i.author??(i.author=""),i.id??(i.id=0),i.smiles??(i.smiles=""),i.monomerType??(i.monomerType="Backbone"),i.createDate??(i.createDate=null),t.push(i)}return t}(e),n=JSON.stringify(t);r.Utils.download(`${e.name}.json`,n)}static async demoAntibodies(){await async function(){const e=await Uo.files.readCsv("demo-files/Antibody_HC.csv"),t=e.col("AntibodyHC");[["units","fasta"],["aligned","SEQ.MSA"],["alphabet","PT"],["cell.renderer","sequence"],["quality","Macromolecule"],[".semantic-detection-duration","8"],[".annotations",'[{"id":"deamid-ng","name":"Deamidation (NG)","description":"deamidation liability pattern (111 hits)","start":null,"end":null,"visualType":"motif","category":"liability","color":"#E53935","severity":"high","motifPattern":"NG","autoGenerated":true},{"id":"deamid-ns","name":"Deamidation (NS)","description":"deamidation liability pattern (859 hits)","start":null,"end":null,"visualType":"motif","category":"liability","color":"#E53935","severity":"medium","motifPattern":"NS","autoGenerated":true},{"id":"deamid-na","name":"Deamidation (NA)","description":"deamidation liability pattern (69 hits)","start":null,"end":null,"visualType":"motif","category":"liability","color":"#E53935","severity":"low","motifPattern":"NA","autoGenerated":true},{"id":"deamid-nd","name":"Deamidation (ND)","description":"deamidation liability pattern (18 hits)","start":null,"end":null,"visualType":"motif","category":"liability","color":"#E53935","severity":"low","motifPattern":"ND","autoGenerated":true},{"id":"deamid-nt","name":"Deamidation (NT)","description":"deamidation liability pattern (546 hits)","start":null,"end":null,"visualType":"motif","category":"liability","color":"#E53935","severity":"low","motifPattern":"NT","autoGenerated":true},{"id":"isom-dg","name":"Isomerization (DG)","description":"isomerization liability pattern (118 hits)","start":null,"end":null,"visualType":"motif","category":"liability","color":"#FF9800","severity":"high","motifPattern":"DG","autoGenerated":true},{"id":"isom-ds","name":"Isomerization (DS)","description":"isomerization liability pattern (306 hits)","start":null,"end":null,"visualType":"motif","category":"liability","color":"#FF9800","severity":"medium","motifPattern":"DS","autoGenerated":true},{"id":"oxid-m","name":"Oxidation (Met)","description":"oxidation liability pattern (1220 hits)","start":null,"end":null,"visualType":"point","category":"liability","color":"#9C27B0","severity":"medium","motifPattern":"M","autoGenerated":true},{"id":"oxid-w","name":"Oxidation (Trp)","description":"oxidation liability pattern (2593 hits)","start":null,"end":null,"visualType":"point","category":"liability","color":"#9C27B0","severity":"low","motifPattern":"W","autoGenerated":true},{"id":"glyco-nxst","name":"N-glycosylation","description":"glycosylation liability pattern (38 hits)","start":null,"end":null,"visualType":"motif","category":"liability","color":"#4CAF50","severity":"high","motifPattern":"N[^P][ST]","autoGenerated":true},{"id":"free-cys","name":"Free Cysteine","description":"freeCysteine liability pattern (2327 hits)","start":null,"end":null,"visualType":"point","category":"liability","color":"#607D8B","severity":"info","motifPattern":"C","autoGenerated":true},{"id":"kabat-heavy-fr1","name":"FR1","description":"FR1 (KABAT 1-30)","start":"1","end":"30","visualType":"region","category":"structure","sourceScheme":"KABAT","autoGenerated":true},{"id":"kabat-heavy-cdr1","name":"CDR1","description":"CDR1 (KABAT 31-35)","start":"31","end":"35","visualType":"region","category":"structure","sourceScheme":"KABAT","autoGenerated":true},{"id":"kabat-heavy-fr2","name":"FR2","description":"FR2 (KABAT 36-49)","start":"36","end":"49","visualType":"region","category":"structure","sourceScheme":"KABAT","autoGenerated":true},{"id":"kabat-heavy-cdr2","name":"CDR2","description":"CDR2 (KABAT 50-65)","start":"50","end":"65","visualType":"region","category":"structure","sourceScheme":"KABAT","autoGenerated":true},{"id":"kabat-heavy-fr3","name":"FR3","description":"FR3 (KABAT 66-94)","start":"66","end":"94","visualType":"region","category":"structure","sourceScheme":"KABAT","autoGenerated":true},{"id":"kabat-heavy-cdr3","name":"CDR3","description":"CDR3 (KABAT 95-102)","start":"95","end":"102","visualType":"region","category":"structure","sourceScheme":"KABAT","autoGenerated":true},{"id":"kabat-heavy-fr4","name":"FR4","description":"FR4 (KABAT 103-113)","start":"103","end":"113","visualType":"region","category":"structure","sourceScheme":"KABAT","autoGenerated":true}]'],[".annotationColumnName","~AntibodyHC_annotations"],[".id","750dcca0-48b0-11f1-e663-211b32f9e20c"],[".numberingScheme","kabat"],[".regions",'[{"name":"FR1","description":"FR1 (KABAT 1-30)","start":"1","end":"30"},{"name":"CDR1","description":"CDR1 (KABAT 31-35)","start":"31","end":"35"},{"name":"FR2","description":"FR2 (KABAT 36-49)","start":"36","end":"49"},{"name":"CDR2","description":"CDR2 (KABAT 50-65)","start":"50","end":"65"},{"name":"FR3","description":"FR3 (KABAT 66-94)","start":"66","end":"94"},{"name":"CDR3","description":"CDR3 (KABAT 95-102)","start":"95","end":"102"},{"name":"FR4","description":"FR4 (KABAT 103-113)","start":"103","end":"113"}]'],[".positionShift","42.10943057774151"]].forEach(([e,n])=>t.setTag(e,n));const n=e.col("cluster (dbscan)"),i=n.convertTo(r.TYPE.STRING);e.columns.remove(n.name),e.columns.add(i);const s=await Uo.files.readAsText("demo-files/Antibody_HC.layout"),a=r.ViewLayout.fromJson(s);a.columns.forEach(t=>{const n=e.col(t.name);n&&Object.entries(t.tags).forEach(([e,t])=>n.setTag(e,t))});const l=o.shell.addTableView(e);await r.delay(100),l.loadLayout(a,!0)}()}static async seq2atomic(e,t){return e.trim()?Wo.toAtomicLevelSingleSeq(e):""}static async seqIdentity(e,t){if(!e.trim())return null;try{const n=r.Column.fromList(r.COLUMN_TYPE.STRING,"seq",[e]),i=r.DataFrame.fromColumns([n]);if(!await o.functions.call("Bio:detectMacromolecule",{col:n}))throw new Error("Macromolecule required");return(await Oi(i,n,t,fe.IDENTITY,Uo.seqHelper)).get(0)}catch(e){const[t,n]=(0,we.AP)(e);throw Uo.logger.error(t,void 0,n),e}}static async detectMacromoleculeProbe(e,t="",n=100){const i=await e.readAsString();await async function(e,t,n){const i=r.TaskBarProgressIndicator.create("detectMacromolecule probe ...");try{let s=0;const a=await o.functions.call("Bio:detectMacromoleculeEnableStore");let l=0;for(let c=0;c<n;++c){const u=r.DataFrame.fromCsv(e),h=t?u.getCol(t):u.columns.byIndex(0);await o.functions.call("Bio:detectMacromolecule",{col:h})!==r.SEMTYPE.MACROMOLECULE&&(++l,console.warn(`Reject reason: ${a.last.rejectReason}`));const d=c/n;d-s>=.1&&(s=d,i.update(100*d,`detectMacromolecule probe ${l}/${c}/${n} ...`),await r.delay(0))}l>0?o.shell.warning(`detectMacromolecule failed ${l} / ${n}`):o.shell.info(`detectMacromolecule success ${n}`)}finally{i.close()}}(i,t,n)}static async getSeqHelper(){return await Wo.initBio(),Uo.seqHelper}static async getMolFromHelm(e,t,n=!0){return async function(e,t,n=!0,i){const o=Uo.seqHelper,s=(await o.getHelmToMolfileConverter(i)).convertToRdKitBeautifiedMolfileColumn(t,n,Uo.rdKitModule,i);return s.semType=r.SEMTYPE.MOLECULE,s}(0,t,n,Uo.monomerLib)}}Go([o.decorators.func({description:"Returns an instance of the monomer library helper",outputs:[{type:"object",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"getMonomerLibHelper",null),Go([o.decorators.init({tags:["init"]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"initBio",null),Go([o.decorators.func({meta:{role:"tooltip"},tags:["tooltip"]}),Vo(0,o.decorators.param({options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column]),Bo("design:returntype",r.Widget)],Wo,"sequenceTooltip",null),Go([o.decorators.func({}),Bo("design:type",Function),Bo("design:paramtypes",[String]),Bo("design:returntype",Promise)],Wo,"standardiseMonomerLibrary",null),Go([o.decorators.func({"top-menu":"Bio | Manage | Match with Monomer Library...",description:"Matches molecules in a column with monomers from the selected library(s)"}),Vo(1,o.decorators.param({type:"column",options:{semType:"Molecule"}})),Vo(2,o.decorators.param({type:"string",options:{choices:["PEPTIDE","RNA","CHEM"],initialValue:"PEPTIDE",caption:"Polymer Type"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,String]),Bo("design:returntype",Promise)],Wo,"matchWithMonomerLibrary",null),Go([o.decorators.func({outputs:[{type:"object",name:"monomerLib"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Object)],Wo,"getBioLib",null),Go([o.decorators.func({outputs:[{type:"object",name:"result"}]}),Vo(0,o.decorators.param({type:"column",options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column]),Bo("design:returntype",Object)],Wo,"getSeqHandler",null),Go([o.decorators.panel({name:"Bioinformatics | Get Region",description:"Creates a new column with sequences of the region between start and end",tags:["panel"]}),Vo(0,o.decorators.param({type:"column",options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column]),Bo("design:returntype",r.Widget)],Wo,"getRegionPanel",null),Go([o.decorators.panel({name:"Bioinformatics | Manage Monomer Libraries",meta:{"exclude-actions-panel":"true"},tags:["exclude-actions-panel"]}),Vo(0,o.decorators.param({name:"seqColumn",options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column]),Bo("design:returntype",Promise)],Wo,"libraryPanel",null),Go([o.decorators.editor({tags:["editor"]}),Bo("design:type",Function),Bo("design:paramtypes",[r.FuncCall]),Bo("design:returntype",void 0)],Wo,"GetRegionEditor",null),Go([o.decorators.editor({tags:["editor"]}),Bo("design:type",Function),Bo("design:paramtypes",[r.FuncCall]),Bo("design:returntype",void 0)],Wo,"SplitToMonomersEditor",null),Go([o.decorators.editor({tags:["editor"]}),Bo("design:type",Function),Bo("design:paramtypes",[r.FuncCall]),Bo("design:returntype",void 0)],Wo,"SequenceSpaceEditor",null),Go([o.decorators.editor({tags:["editor"]}),Bo("design:type",Function),Bo("design:paramtypes",[r.FuncCall]),Bo("design:returntype",void 0)],Wo,"SeqActivityCliffsEditor",null),Go([o.decorators.func({name:"customSequenceCellRenderer",tags:["cellRenderer"],meta:{cellType:"sequence",columnTags:"quality=Macromolecule, units=custom",role:"cellRenderer"},outputs:[{type:"grid_cell_renderer",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",r.GridCellRenderer)],Wo,"customSequenceCellRenderer",null),Go([o.decorators.func({name:"fastaSequenceCellRenderer",tags:["cellRenderer"],meta:{cellType:"sequence",columnTags:"quality=Macromolecule, units=fasta",role:"cellRenderer"},outputs:[{type:"grid_cell_renderer",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",We)],Wo,"fastaSequenceCellRenderer",null),Go([o.decorators.func({name:"separatorSequenceCellRenderer",tags:["cellRenderer"],meta:{cellType:"sequence",columnTags:"quality=Macromolecule, units=separator",role:"cellRenderer"},outputs:[{type:"grid_cell_renderer",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",We)],Wo,"separatorSequenceCellRenderer",null),Go([o.decorators.func({name:"bilnSequenceCellRenderer",tags:["cellRenderer"],meta:{cellType:"sequence",columnTags:"quality=Macromolecule, units=biln",role:"cellRenderer"},outputs:[{type:"grid_cell_renderer",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",We)],Wo,"bilnSequenceCellRenderer",null),Go([o.decorators.func({name:"refineNotationProviderForBiln",outputs:[{type:"bool",name:"result"}],tags:["notationRefiner"],meta:{role:"notationRefiner"}}),Vo(0,o.decorators.param({type:"column"})),Vo(1,o.decorators.param({type:"object"})),Vo(2,o.decorators.param({type:"string",options:{nullable:!0,optional:!0}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column,Object,Object]),Bo("design:returntype",Boolean)],Wo,"refineNotationProviderForBiln",null),Go([o.decorators.panel({name:"Bioinformatics | Sequence Renderer",tags:["panel"]}),Vo(0,o.decorators.param({options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column]),Bo("design:returntype",r.Widget)],Wo,"macroMolColumnPropertyPanel",null),Go([o.decorators.panel({name:"Composition analysis",tags:["bio","widgets","panel"],meta:{role:"widgets",domain:"bio"}}),Vo(0,o.decorators.param({options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.SemanticValue]),Bo("design:returntype",r.Widget)],Wo,"compositionAnalysisWidget",null),Go([o.decorators.panel({name:"Monomer",tags:["bio","panel"],meta:{domain:"bio"}}),Vo(0,o.decorators.param({options:{semType:"Monomer"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.SemanticValue]),Bo("design:returntype",r.Widget)],Wo,"monomerInfoPanel",null),Go([o.decorators.func({name:"MacromoleculeDifferenceCellRenderer",tags:["cellRenderer"],meta:{cellType:"MacromoleculeDifference",columnTags:"quality=MacromoleculeDifference",role:"cellRenderer"},outputs:[{type:"grid_cell_renderer",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",je)],Wo,"macromoleculeDifferenceCellRenderer",null),Go([o.decorators.func({outputs:[{type:"object",name:"result"}]}),Vo(0,o.decorators.param({options:{choices:["Local alignment","Global alignment"]}})),Vo(1,o.decorators.param({options:{choices:["AUTO","NUCLEOTIDES","BLOSUM45","BLOSUM50","BLOSUM62","BLOSUM80","BLOSUM90","PAM30","PAM70","PAM250","SCHNEIDER","TRANS"]}})),Bo("design:type",Function),Bo("design:paramtypes",[String,String,Number,String,String]),Bo("design:returntype",void 0)],Wo,"sequenceAlignment",null),Go([o.decorators.panel({name:"WebLogo",description:"WebLogo",tags:["viewer","panel"],meta:{icon:"files/icons/weblogo-viewer.svg",role:"viewer"},outputs:[{type:"viewer",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"webLogoViewer",null),Go([o.decorators.panel({name:"VdRegions",description:"V-Domain regions viewer",tags:["viewer"],meta:{icon:"files/icons/vdregions-viewer.svg",role:"viewer"},outputs:[{type:"viewer",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"vdRegionsViewer",null),Go([o.decorators.func({name:"getRegion",description:"Gets a new column with sequences of the region between start and end"}),Vo(0,o.decorators.param({type:"column"})),Vo(1,o.decorators.param({type:"string",options:{optional:!0}})),Vo(2,o.decorators.param({type:"string",options:{optional:!0}})),Vo(3,o.decorators.param({type:"string",options:{optional:!0,description:"Name of the column to be created"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column,Object,Object,Object]),Bo("design:returntype",r.Column)],Wo,"getRegion",null),Go([o.decorators.func({name:"Get Region Top Menu",description:"Get sequences for a region specified from a Macromolecule","top-menu":"Bio | Calculate | Extract Region...",editor:"Bio:GetRegionEditor"}),Vo(0,o.decorators.param({options:{description:"Input data table"}})),Vo(1,o.decorators.param({options:{semType:"Macromolecule",description:"Sequence column"}})),Vo(2,o.decorators.param({type:"string",options:{optional:!0,description:"Region start position name"}})),Vo(3,o.decorators.param({type:"string",options:{optional:!0,description:"Region end position name"}})),Vo(4,o.decorators.param({type:"string",options:{optional:!0,description:"Region column name"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,Object,Object,Object]),Bo("design:returntype",Promise)],Wo,"getRegionTopMenu",null),Go([o.decorators.func({name:"Apply Numbering Scheme",description:"Assigns antibody numbering (IMGT/Kabat/Chothia/AHo)","top-menu":"Bio | Annotate | Apply Numbering Scheme..."}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"applyNumberingScheme",null),Go([o.decorators.func({name:"Scan Liabilities",description:"Scans macromolecule sequences for deamidation, oxidation, and other liabilities","top-menu":"Bio | Annotate | Scan Liabilities..."}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"scanLiabilities",null),Go([o.decorators.func({name:"Manage Annotations",description:"View and manage sequence annotations on macromolecule columns","top-menu":"Bio | Annotate | Manage Annotations..."}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"manageAnnotations",null),Go([o.decorators.func({name:"Sequence Column Input",description:"Creates a new input for sequence columns with ability to extract a region"}),Bo("design:type",Function),Bo("design:paramtypes",[String,Object]),Bo("design:returntype",Object)],Wo,"sequenceColumnInput",null),Go([o.decorators.func({name:"Sequence Activity Cliffs",description:"Detects pairs of molecules with similar structure and significant difference in any given property","top-menu":"Bio | Analyze | Activity Cliffs...",editor:"Bio:SeqActivityCliffsEditor",outputs:[]}),Vo(0,o.decorators.param({options:{description:"Input data table"}})),Vo(1,o.decorators.param({type:"string",options:{semType:"Macromolecule",description:"Input data table"}})),Vo(3,o.decorators.param({options:{initialValue:"80",description:"Similarity cutoff"}})),Vo(4,o.decorators.param({type:"string",options:{choices:["UMAP","t-SNE"]}})),Vo(5,o.decorators.param({type:"string",options:{choices:["Hamming","Levenshtein","Monomer chemical distance"]}})),Vo(6,o.decorators.param({type:"func"})),Vo(7,o.decorators.param({type:"object",options:{optional:!0}})),Vo(8,o.decorators.param({options:{optional:!0}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,r.Column,Number,String,String,r.Func,Object,Boolean]),Bo("design:returntype",Promise)],Wo,"activityCliffs",null),Go([o.decorators.func({name:"seqActivityCliffsInitFunction"}),Vo(0,o.decorators.param({type:"viewer"})),Bo("design:type",Function),Bo("design:paramtypes",[r.ScatterPlotViewer]),Bo("design:returntype",Promise)],Wo,"seqActivityCliffsInitFunction",null),Go([o.decorators.func({meta:{role:"transform"}}),Vo(0,o.decorators.param({options:{description:"Input data table"}})),Vo(1,o.decorators.param({type:"column",options:{semType:"Macromolecule"}})),Vo(2,o.decorators.param({type:"column",options:{type:"numerical"}})),Vo(3,o.decorators.param({options:{description:"Similarity cutoff",initialValue:"80"}})),Vo(4,o.decorators.param({type:"string"})),Vo(5,o.decorators.param({type:"string"})),Vo(6,o.decorators.param({options:{optional:!0}})),Vo(7,o.decorators.param({options:{optional:!0}})),Vo(8,o.decorators.param({options:{optional:!0}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,r.Column,Number,String,String,String,Boolean,Array]),Bo("design:returntype",Promise)],Wo,"seqActivityCliffsTransform",null),Go([o.decorators.func({name:"Encode Sequences",tags:["dim-red-preprocessing-function"],meta:{supportedSemTypes:"Macromolecule",supportedTypes:"string",supportedDistanceFunctions:"Hamming,Levenshtein,Monomer chemical distance,Needlemann-Wunsch",role:"dim-red-preprocessing-function"},outputs:[{type:"object",name:"result"}]}),Vo(0,o.decorators.param({options:{semType:"Macromolecule"}})),Vo(1,o.decorators.param({type:"string"})),Vo(2,o.decorators.param({options:{initialValue:"1",caption:"Gap open penalty",optional:!0}})),Vo(3,o.decorators.param({options:{initialValue:"0.6",caption:"Gap extension penalty",optional:!0}})),Vo(4,o.decorators.param({options:{caption:"Fingerprint type",initialValue:"Morgan",choices:["Morgan","RDKit","Pattern","AtomPair","MACCS","TopologicalTorsion"],optional:!0}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column,String,Number,Number,String]),Bo("design:returntype",Promise)],Wo,"macromoleculePreprocessingFunction",null),Go([o.decorators.func({name:"Helm Fingerprints",meta:{supportedSemTypes:"Macromolecule",supportedTypes:"string",supportedUnits:"helm",supportedDistanceFunctions:"Tanimoto,Asymmetric,Cosine,Sokal"},outputs:[{type:"object",name:"result"}]}),Vo(0,o.decorators.param({type:"column",options:{semType:"Macromolecule"}})),Vo(1,o.decorators.param({type:"string"})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column,String]),Bo("design:returntype",Promise)],Wo,"helmPreprocessingFunction",null),Go([o.decorators.func({name:"Sequence Space",description:"Creates 2D sequence space with projected sequences by pairwise distance","top-menu":"Bio | Analyze | Sequence Space...",editor:"Bio:SequenceSpaceEditor",outputs:[{type:"viewer",name:"result"}]}),Vo(1,o.decorators.param({options:{semType:"Macromolecule"}})),Vo(2,o.decorators.param({type:"string",options:{choices:["UMAP","t-SNE"]}})),Vo(3,o.decorators.param({type:"string",options:{choices:["Hamming","Levenshtein","Monomer chemical distance"]}})),Vo(4,o.decorators.param({options:{initialValue:"true"}})),Vo(5,o.decorators.param({type:"func",options:{optional:!0}})),Vo(6,o.decorators.param({type:"object",options:{optional:!0}})),Vo(7,o.decorators.param({options:{optional:!0,initialValue:"true"}})),Vo(8,o.decorators.param({options:{optional:!0}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,String,String,Boolean,r.Func,Object,Boolean,Boolean]),Bo("design:returntype",Promise)],Wo,"sequenceSpaceTopMenu",null),Go([o.decorators.func({outputs:[{type:"viewer",name:"result"}],meta:{role:"transform"}}),Vo(1,o.decorators.param({options:{semType:"Macromolecule"}})),Vo(2,o.decorators.param({type:"string"})),Vo(3,o.decorators.param({type:"string"})),Vo(4,o.decorators.param({options:{initialValue:"true"}})),Vo(5,o.decorators.param({options:{optional:!0}})),Vo(6,o.decorators.param({options:{optional:!0}})),Vo(7,o.decorators.param({options:{optional:!0}})),Vo(8,o.decorators.param({options:{optional:!0}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,String,String,Boolean,String,Boolean,Array,String]),Bo("design:returntype",Promise)],Wo,"sequenceSpaceTransform",null),Go([o.decorators.func({name:"Molecules to HELM","top-menu":"Bio | Transform | Molecules to HELM...",description:"Converts Peptide molecules to HELM notation by matching with monomer library"}),Vo(0,o.decorators.param({name:"table",options:{description:"Input data table"}})),Vo(1,o.decorators.param({name:"molecules",options:{semType:"Molecule",description:"Molecule column"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column]),Bo("design:returntype",Promise)],Wo,"moleculesToHelmTopMenu",null),Go([o.decorators.func({name:"Molecule to HELM Single",description:"Converts a single molecule to HELM notation without requiring a table or column",outputs:[{name:"result",type:"string",options:{semType:"Macromolecule",units:"helm"}}]}),Vo(0,o.decorators.param({name:"molecule",options:{semType:"Molecule",description:"Input molecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[String]),Bo("design:returntype",Promise)],Wo,"moleculeToHelmSingle",null),Go([o.decorators.func({name:"To Atomic Level",description:"Converts sequences to molblocks","top-menu":"Bio | Transform | To Atomic Level..."}),Vo(0,o.decorators.param({options:{description:"Input data table"}})),Vo(1,o.decorators.param({options:{semType:"Macromolecule",caption:"Sequence"}})),Vo(2,o.decorators.param({options:{initialValue:"true",caption:"Non-linear",description:"Slower mode for cycling/branching HELM structures"}})),Vo(3,o.decorators.param({options:{initialValue:"false",caption:"Highlight monomers",description:"Highlight monomers' substructures of the molecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,Boolean,Boolean]),Bo("design:returntype",Promise)],Wo,"toAtomicLevel",null),Go([o.decorators.func({name:"To Atomic Level...",meta:{action:"to atomic level"}}),Vo(0,o.decorators.param({options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column]),Bo("design:returntype",Promise)],Wo,"toAtomicLevelAction",null),Go([o.decorators.panel({name:"Molecular Structure",tags:["bio","widgets","panel"],meta:{role:"widgets",domain:"bio"}}),Vo(0,o.decorators.param({name:"sequence",type:"semantic_value",options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.SemanticValue]),Bo("design:returntype",Promise)],Wo,"toAtomicLevelPanel",null),Go([o.decorators.func({name:"To Atomic Level Single sequence",description:"Converts a single sequence to molblock",outputs:[{name:"molfile",type:"string",options:{semType:"Molecule"}}]}),Vo(0,o.decorators.param({name:"sequence",type:"string",options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[String]),Bo("design:returntype",Promise)],Wo,"toAtomicLevelSingleSeq",null),Go([o.decorators.panel({name:"Molecular 3D Structure",tags:["bio","widgets","panel"],meta:{role:"widgets",domain:"bio"}}),Vo(0,o.decorators.param({type:"semantic_value",options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.SemanticValue]),Bo("design:returntype",Promise)],Wo,"sequence3dStructureWidget",null),Go([o.decorators.panel({name:"MSA",description:"Performs multiple sequence alignment",tags:["bio","panel"],meta:{domain:"bio"},"top-menu":"Bio | Analyze | MSA..."}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"multipleSequenceAlignmentDialog",null),Go([o.decorators.func({name:"Multiple Sequence Alignment",description:"Multiple sequence alignment",meta:{domain:"bio"}}),Vo(0,o.decorators.param({type:"column",options:{semType:"Macromolecule"}})),Vo(1,o.decorators.param({type:"column"})),Vo(2,o.decorators.param({type:"object",options:{optional:!0}})),Bo("design:type",Function),Bo("design:paramtypes",[Object,Object,Object]),Bo("design:returntype",Promise)],Wo,"alignSequences",null),Go([o.decorators.func({name:"PepSeA",description:"Aligns non-canonical peptide sequences using PepSeA Docker container (MAFFT)",meta:{role:"sequenceMSA"},outputs:[{name:"result",type:"column"}]}),Vo(0,o.decorators.param({type:"column",options:{semType:"Macromolecule"}})),Vo(1,o.decorators.param({type:"string",options:{choices:["mafft --auto","mafft","linsi","ginsi","einsi","fftns","fftnsi","nwns","nwnsi"],initialValue:"mafft --auto"}})),Vo(2,o.decorators.param({type:"double",options:{initialValue:"1.53"}})),Vo(3,o.decorators.param({type:"double",options:{initialValue:"0"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column,String,Number,Number]),Bo("design:returntype",Promise)],Wo,"pepseaMsa",null),Go([o.decorators.func({name:"Immunum",description:"Assigns antibody numbering (IMGT/Kabat) using the immunum WASM library",meta:{role:"antibodyNumbering"}}),Vo(0,o.decorators.param({type:"dataframe"})),Vo(1,o.decorators.param({type:"column",options:{semType:"Macromolecule"}})),Vo(2,o.decorators.param({type:"string",options:{choices:["imgt","kabat"],initialValue:"imgt"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,String]),Bo("design:returntype",Promise)],Wo,"immunumAntibodyNumbering",null),Go([o.decorators.func({name:"Compare Sequences",description:"Builds a MacromoleculeDifference column from two sequence columns (seq1#seq2)","top-menu":"Bio | Analyze | Compare sequences..."}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"compareSequences",null),Go([o.decorators.func({name:"Composition Analysis",description:"Visualizes sequence composition on a WebLogo plot","top-menu":"Bio | Analyze | Composition",meta:{icon:"files/icons/composition-analysis.svg"},outputs:[{name:"result",type:"viewer"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"compositionAnalysis",null),Go([o.decorators.fileHandler({name:"importFasta",tags:["fileHandler"],description:"Opens FASTA file",ext:"fasta, fna, ffn, faa, frn, fa, fst"}),Bo("design:type",Function),Bo("design:paramtypes",[String]),Bo("design:returntype",Array)],Wo,"importFasta",null),Go([o.decorators.fileHandler({name:"importBam",tags:["fileHandler"],description:"Opens Bam file",ext:"bam, bai"}),Bo("design:type",Function),Bo("design:paramtypes",[String]),Bo("design:returntype",Array)],Wo,"importBam",null),Go([o.decorators.func({name:"convertDialog","top-menu":"Bio | Transform | Convert Sequence Notation..."}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"convertDialog",null),Go([o.decorators.func({name:"Convert Notation...",meta:{action:"Convert Notation..."}}),Vo(0,o.decorators.param({options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column]),Bo("design:returntype",void 0)],Wo,"convertColumnAction",null),Go([o.decorators.func({name:"monomerCellRenderer",tags:["cellRenderer"],meta:{cellType:"Monomer",columnTags:"quality=Monomer",role:"cellRenderer"},outputs:[{type:"grid_cell_renderer",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Ci)],Wo,"monomerCellRenderer",null),Go([o.decorators.func({name:"testDetectMacromolecule"}),Vo(0,o.decorators.param({options:{choices:["Demo:Files/","System:AppData/"]}})),Bo("design:type",Function),Bo("design:paramtypes",[String]),Bo("design:returntype",Promise)],Wo,"testDetectMacromolecule",null),Go([o.decorators.func({name:"Split to Monomers","top-menu":"Bio | Transform | Split to Monomers...",editor:"Bio:SplitToMonomersEditor"}),Vo(1,o.decorators.param({options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column]),Bo("design:returntype",Promise)],Wo,"splitToMonomersTopMenu",null),Go([o.decorators.func({name:"Bio: getHelmMonomers",outputs:[{name:"result",type:"object"}]}),Vo(0,o.decorators.param({type:"column",options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.Column]),Bo("design:returntype",Array)],Wo,"getHelmMonomers",null),Go([o.decorators.func({name:"Sequence Similarity Search",meta:{icon:"files/icons/sequence-similarity-viewer.svg",role:"viewer"},tags:["viewer"],outputs:[{name:"result",type:"viewer"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Ct)],Wo,"similaritySearchViewer",null),Go([o.decorators.func({name:"similaritySearch",description:"Finds similar sequences","top-menu":"Bio | Search | Similarity Search",outputs:[{name:"result",type:"viewer"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"similaritySearchTopMenu",null),Go([o.decorators.func({name:"Sequence Diversity Search",tags:["viewer"],meta:{icon:"files/icons/sequence-diversity-viewer.svg",role:"viewer"},outputs:[{name:"result",type:"viewer"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",At)],Wo,"diversitySearchViewer",null),Go([o.decorators.func({name:"diversitySearch",description:"Finds the most diverse sequences","top-menu":"Bio | Search | Diversity Search",outputs:[{name:"result",type:"viewer"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"diversitySearchTopMenu",null),Go([o.decorators.editor({name:"SearchSubsequenceEditor",tags:["editor"]}),Bo("design:type",Function),Bo("design:paramtypes",[r.FuncCall]),Bo("design:returntype",void 0)],Wo,"searchSubsequenceEditor",null),Go([o.decorators.func({name:"Subsequence Search","top-menu":"Bio | Search | Subsequence Search ...",editor:"Bio:SearchSubsequenceEditor"}),Bo("design:type",Function),Bo("design:paramtypes",[r.Column]),Bo("design:returntype",void 0)],Wo,"SubsequenceSearchTopMenu",null),Go([o.decorators.func({name:"Identity",description:"Adds a column with fraction of matching monomers","top-menu":"Bio | Calculate | Identity..."}),Vo(0,o.decorators.param({options:{description:"Table containing Macromolecule column"}})),Vo(1,o.decorators.param({options:{semType:"Macromolecule",description:"Sequences to score"}})),Vo(2,o.decorators.param({options:{description:"Sequence,matching column format"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,String]),Bo("design:returntype",Promise)],Wo,"sequenceIdentityScoring",null),Go([o.decorators.func({name:"Similarity",description:"Adds a column with similarity scores, calculated as sum of monomer fingerprint similarities","top-menu":"Bio | Calculate | Similarity..."}),Vo(0,o.decorators.param({options:{description:"Table containing Macromolecule column"}})),Vo(1,o.decorators.param({options:{semType:"Macromolecule",description:"Sequences to score"}})),Vo(2,o.decorators.param({options:{description:"Sequence,matching column format"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,String]),Bo("design:returntype",Promise)],Wo,"sequenceSimilarityScoring",null),Go([o.decorators.func({name:"Manage Monomer Libraries",description:"Manage HELM monomer libraries"}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"manageMonomerLibraries",null),Go([o.decorators.func({name:"Manage Monomer Libraries View","top-menu":"Bio | Manage | Monomer Libraries"}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"manageLibrariesView",null),Go([o.decorators.func({name:"manageMonomersView",description:"Edit and create monomers","top-menu":"Bio | Manage | Monomers"}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"manageMonomersView",null),Go([o.decorators.app({tags:["app"],name:"Manage Monomer Libraries",browsePath:"Peptides",icon:"files/icons/monomers.png"}),Vo(0,o.decorators.param({options:{metaUrl:!0,optional:!0}})),Bo("design:type",Function),Bo("design:paramtypes",[String]),Bo("design:returntype",Promise)],Wo,"manageMonomerLibrariesView",null),Go([o.decorators.func({name:"Monomer Manager Tree Browser",meta:{role:"appTreeBrowser",app:"Manage Monomer Libraries"}}),Bo("design:type",Function),Bo("design:paramtypes",[r.TreeViewGroup]),Bo("design:returntype",Promise)],Wo,"manageMonomerLibrariesViewTreeBrowser",null),Go([o.decorators.app({tags:["app"],name:"Monomer Collections",browsePath:"Peptides",icon:"files/icons/monomers.png"}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"monomerCollectionsApp",null),Go([o.decorators.fileExporter({description:"As FASTA..."}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"saveAsFasta",null),Go([o.decorators.func({name:"Bio Substructure Filter",description:"Substructure filter for macromolecules",tags:["filter"],meta:{semType:"Macromolecule",role:"filter"},outputs:[{type:"filter",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",qn._i)],Wo,"bioSubstructureFilter",null),Go([o.decorators.func({name:"Bio Substructure Filter Test",description:"Substructure filter for Helm package tests",outputs:[{name:"result",type:"object"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",qn._i)],Wo,"bioSubstructureFilterTest",null),Go([o.decorators.func(),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"webLogoLargeApp",null),Go([o.decorators.func(),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"webLogoAggApp",null),Go([o.decorators.func(),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"getRegionApp",null),Go([o.decorators.func(),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"getRegionHelmApp",null),Go([o.decorators.func(),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"longSeqTableSeparator",null),Go([o.decorators.func(),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"longSeqTableFasta",null),Go([o.decorators.func(),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",void 0)],Wo,"longSeqTableHelm",null),Go([o.decorators.func(),Vo(0,o.decorators.param({type:"object"})),Vo(1,o.decorators.param({type:"object"})),Bo("design:type",Function),Bo("design:paramtypes",[r.Cell,r.Menu]),Bo("design:returntype",void 0)],Wo,"addCopyMenu",null),Go([o.decorators.demo({description:"Sequence similarity tracking and evaluation dataset diversity",demoPath:"Bioinformatics | Similarity, Diversity",path:"/apps/Tutorials/Demo/Bioinformatics/Similarity,%20Diversity"}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"demoBioSimilarityDiversity",null),Go([o.decorators.demo({description:"Exploring sequence space of Macromolecules, comparison with hierarchical clustering results",demoPath:"Bioinformatics | Sequence Space",path:"/apps/Tutorials/Demo/Bioinformatics/Sequence%20Space",meta:{isDemoDashboard:"true"}}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"demoBioSequenceSpace",null),Go([o.decorators.demo({description:"Activity Cliffs analysis on Macromolecules data",demoPath:"Bioinformatics | Activity Cliffs",path:"/apps/Tutorials/Demo/Bioinformatics/Activity%20Cliffs"}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"demoBioActivityCliffs",null),Go([o.decorators.demo({description:"Atomic level structure of Macromolecules",demoPath:"Bioinformatics | Atomic Level",path:"/apps/Tutorials/Demo/Bioinformatics/Atomic%20Level",meta:{demoSkip:"true"}}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"demoBioAtomicLevel",null),Go([o.decorators.demo({description:"SI-RNA sequences, molecular structures, curves and assay data",demoPath:"Bioinformatics | SI-RNA",path:"/apps/Tutorials/Demo/Bioinformatics/SI-RNA",meta:{demoSkip:"true"}}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"demoBioSiRNA",null),Go([o.decorators.func({name:"SDF to JSON Library"}),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame]),Bo("design:returntype",Promise)],Wo,"sdfToJsonLib",null),Go([o.decorators.demo({description:"Antibody sequences, numbering, liabilities, extraction and SAR",demoPath:"Bioinformatics | Antibodies",path:"/apps/Tutorials/Demo/Bioinformatics/Antibodies"}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"demoAntibodies",null),Go([o.decorators.func({friendlyName:"seq2atomic",description:"Converts a `Macromolecule` sequence to its atomic level `Molecule` representation",outputs:[{name:"molfile",type:"string",options:{semType:"Molecule"}}]}),Vo(0,o.decorators.param({options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[String,Boolean]),Bo("design:returntype",Promise)],Wo,"seq2atomic",null),Go([o.decorators.func({name:"seqIdentity",friendlyName:"seqIdentity",description:"Gets identity to a reference sequence"}),Vo(0,o.decorators.param({options:{semType:"Macromolecule"}})),Vo(1,o.decorators.param({options:{semType:"Macromolecule"}})),Bo("design:type",Function),Bo("design:paramtypes",[String,String]),Bo("design:returntype",Promise)],Wo,"seqIdentity",null),Go([o.decorators.func(),Vo(2,o.decorators.param({options:{initialValue:"100"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.FileInfo,String,Number]),Bo("design:returntype",Promise)],Wo,"detectMacromoleculeProbe",null),Go([o.decorators.func({outputs:[{type:"object",name:"result"}]}),Bo("design:type",Function),Bo("design:paramtypes",[]),Bo("design:returntype",Promise)],Wo,"getSeqHelper",null),Go([o.decorators.func(),Vo(1,o.decorators.param({type:"column"})),Vo(2,o.decorators.param({options:{initialValue:"true"}})),Bo("design:type",Function),Bo("design:paramtypes",[r.DataFrame,r.Column,Boolean]),Bo("design:returntype",Promise)],Wo,"getMolFromHelm",null)},4954(e,t,n){"use strict";n.d(t,{a7:()=>d,if:()=>p,BQ:()=>g,nI:()=>m});var i=n(4328),o=n(7389),s=n(6082),r=n(2003),a=n(439);async function l(e,t,n=!1,o){const r=t.getSeqHandler(e);let a;o??=new Map;const l=r.isHelm()?t.getSeqMonomers(e):Object.keys(r.stats.freq).filter(e=>""!==e);for(let e=0;e<l.length;e++)o.has(l[e])||o.set(l[e],`${o.size+1}`);if(r.isHelm())a=await i.functions.call("HELM:getMolFiles",{col:e}),a=function(e,t,n=!1){const i=new Array(e.length);for(let o=0;o<e.length;o++){let s=0,r=0,a="\n Datagrok macromolecule handler\n\n 0 0 0 0 0 0 999 V3000\nM V30 BEGIN CTAB\n";const l=e.get(o);s=l.indexOf("\n",s)+1,s=l.indexOf("\n",s)+1,s=l.indexOf("\n",s)+1;const c=parseInt(l.substring(s,s+3)),u=parseInt(l.substring(s+3,s+6));a+=`M V30 COUNTS ${c} ${u} 0 0 0\n`,a+="M V30 BEGIN ATOM\n";for(let e=0;e<c;e++){s=l.indexOf("\n",s)+1+31,r=l.indexOf(" ",s);const i=l.substring(s,r);a+=n?`M V30 ${e+1} R${t.get(i)} 0.000 0.000 0 0\n`:`M V30 ${e+1} At 0.000 0.000 0 0 MASS=${t.get(i)}\n`}a+="M V30 END ATOM\n",a+="M V30 BEGIN BOND\n";for(let e=0;e<u;e++){s=l.indexOf("\n",s)+1;const t=parseInt(l.substring(s,s+3).trim()),n=parseInt(l.substring(s+3,s+6).trim());a+=`M V30 ${e+1} ${parseInt(l.substring(s+6,s+9).trim())} ${t} ${n}\n`}a+="M V30 END BOND\n",a+="M V30 END CTAB\n",a+="M END",i[o]=a}return i}(a,o,n);else{a=new Array(e.length);for(let t=0;t<e.length;t++){const e=c(r.getSplitted(t),o,n);a[t]=e}}return s.Column.fromStrings("monomericMols",a)}function c(e,t,n=!1){let i="\n Datagrok macromolecule handler\n\n 0 0 0 0 0 0 999 V3000\nM V30 BEGIN CTAB\n";i+=`M V30 COUNTS ${e.length} ${e.length?e.length-1:0} 0 0 0\n`,i+="M V30 BEGIN ATOM\n";for(let o=0;o<e.length;o++){const s=e.getCanonical(o);s!==a._S&&(i+=n?`M V30 ${o+1} R${t.get(s)} 0.000 0.000 0 0\n`:`M V30 ${o+1} At 0.000 0.000 0 0 MASS=${t.get(s)}\n`)}i+="M V30 END ATOM\n",i+="M V30 BEGIN BOND\n";for(let t=0;t<e.length-1;t++)i+=`M V30 ${t+1} 1 ${t+1} ${t+2}\n`;return i+="M V30 END BOND\n",i+="M V30 END CTAB\n",i+="M END",i}var u=n(4870);const h="substr_helm";class d{seqHelper;units;separator;inputsDiv;substructureInput;separatorInput;editHelmLink;columnsInput;grid;col;dialog;constructor(e,t){this.seqHelper=t,this.col=e[0],this.createUI()}editHelmLinkAction(){(0,u.Ku)(this.inputsDiv,this.grid.root),o.tools.waitForElementInDom(this.grid.root).then(()=>{setTimeout(()=>{this.grid.cell(h,0).element.children[0].dispatchEvent(new KeyboardEvent("keydown",{key:"Enter"}))},100)})}updateInputs(){const e=this.units===r.Hi.HELM?o.divV([this.columnsInput,this.editHelmLink]):this.units===r.Hi.SEPARATOR?o.inputs([this.columnsInput,this.substructureInput,this.separatorInput]):o.inputs([this.columnsInput,this.substructureInput]);(0,u.Ku)(this.inputsDiv,e)}updateNotationDiv(){this.units=this.col.meta.units,this.separator=this.col.getTag(r.gp.separator);const e=this.dialog.root.getElementsByClassName("notation-text")[0];e&&(e.textContent=`Notation: ${this.units}`)}createUI(){const e=i.shell.tv.dataFrame;this.columnsInput=o.input.column("Column",{table:e,value:this.col,onValueChanged:e=>{this.col=e,this.updateNotationDiv(),this.updateInputs()},filter:e=>e.semType===s.SEMTYPE.MACROMOLECULE}),this.substructureInput=o.input.string("Substructure",{value:""}),this.editHelmLink=o.link("Edit helm",()=>this.editHelmLinkAction(),void 0,{style:{position:"relative",left:"95px"}});const t=s.DataFrame.create(1);t.columns.addNewString(h).init(e=>""),t.col(h).semType=this.col.semType,t.col(h).meta.units=r.Hi.HELM,this.grid=t.plot.grid(),this.separatorInput=o.input.string("Separator",{value:this.separator}),this.inputsDiv=o.div(),this.units=this.col.meta.units,this.separator=this.col.getTag(r.gp.separator),this.updateInputs(),this.dialog=o.dialog("Substructure Search").add(o.divV([o.divText(`Notation: ${this.units}`,"notation-text"),this.inputsDiv])).onOK(async()=>{let e,n=this.units===r.Hi.HELM?t.get(h,0):this.substructureInput.value;this.units===r.Hi.SEPARATOR&&this.separatorInput.value!==this.separator&&this.separatorInput.value&&(n=n.replaceAll(this.separatorInput.value,this.separator)),e=this.units===r.Hi.HELM?await p(n,this.col,this.seqHelper):m(n,this.col),this.col.dataFrame.filter.and(e)}).show()}}function m(e,t,n){const i=n?function(e,t){const n=`${t}`.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),i=e.charAt(0)===t,o=e.charAt(e.length-1)===t,s=e.replace(new RegExp(`^${n}|${n}$`,"g"),"");return i?o?`${n}${s}${n}`:`${n}${s}${n}|${n}${s}$`:o?`^${s}${n}|${n}${s}${n}`:`^${s}${n}|${n}${s}${n}|${n}${s}$`}(e,n):e,o=s.BitSet.create(t.length);for(let n=0;n<t.length;n++){const s=t.get(n);(s.match(i)||s===e)&&o.set(n,!0,!1)}return o}async function p(e,t,n){t.version!==t.temp["last-invalidated-version"]&&await g(t,n,!0);const o=s.Column.string("helm",1).init(t=>e);o.semType=s.SEMTYPE.MACROMOLECULE,o.meta.units=r.Hi.HELM;const a=await l(o,n,!0,t.temp["monomers-dict"]);return(await i.functions.call("Chem:searchSubstructure",{molStringsColumn:t.temp["monomeric-mols"],molString:a.get(0),molBlockFailover:""})).get(0)}async function g(e,t,n){const i=s.TaskBarProgressIndicator.create(`Invalidating molfiles for ${e.name}`);try{await s.delay(10);const i=new Map,o=await l(e,t,n,i);e.temp["monomeric-mols"]=o,e.temp["monomers-dict"]=i,e.temp["last-invalidated-version"]=e.version}finally{i.close()}}},9287(e,t,n){"use strict";n.d(t,{showAnnotationManagerDialog:()=>u});var i=n(4328),o=n(7389),s=n(6082),r=n(4517),a=n(3736);const l={[r.eI.Structure]:"Structure (FR/CDR)",[r.eI.Liability]:"Liability",[r.eI.PTM]:"Post-translational Modification",[r.eI.Custom]:"Custom"},c={[r.Hq.High]:"High",[r.Hq.Medium]:"Medium",[r.Hq.Low]:"Low",[r.Hq.Info]:"Info"};function u(){const e=i.shell.tv?.dataFrame;if(!e)return void i.shell.warning("No table open");const t=e.columns.bySemTypeAll(s.SEMTYPE.MACROMOLECULE);if(0===t.length)return void i.shell.warning("No macromolecule columns found");let n=t[0];const r=o.input.column("Sequence Column",{table:e,value:n,filter:e=>e.semType===s.SEMTYPE.MACROMOLECULE,onValueChanged:e=>{n=e,h()}}),u=o.divV([],{style:{maxHeight:"380px",overflowY:"auto",paddingRight:"8px"}});function h(){u.innerHTML="";const t=(0,a.Ln)(n);if(0!==t.length)for(const i of t){const t=l[i.category]??i.category,r=i.severity?` [${c[i.severity]??i.severity}]`:"",d=i.start&&i.end?` (${i.start}-${i.end})`:"",m=i.sourceScheme?` ${i.sourceScheme}`:"",p=o.iconFA("trash",()=>{const t=(0,a.Ln)(n).filter(e=>e.id!==i.id);(0,a.fh)(n,t),e.fireValuesChanged(),h()},"Delete");p.style.cursor="pointer",p.style.color="#999",p.style.marginLeft="8px";const g=i.color??"#ccc";let f=g;const y=o.div([],{style:{width:"12px",height:"12px",borderRadius:"2px",backgroundColor:f,display:"inline-block",marginRight:"6px",flexShrink:"0",cursor:"pointer"}});o.colorPicker(s.Color.fromHtml(i.color??"#ccc"),e=>{f=s.Color.toHtml(e)},y,()=>{const t=(0,a.Ln)(n).map(e=>e.id===i.id?{...e,color:f}:e);(0,a.fh)(n,t),e.fireValuesChanged(),h()},()=>{f=g,y.style.backgroundColor=f});const b=o.divH([y,o.divText(`${i.name}${d}${m}${r}`,{style:{flex:"1",fontSize:"12px",padding:"4px"}}),o.divText(t,{style:{color:"#888",fontSize:"11px",marginRight:"8px"}}),p],{style:{alignItems:"center",padding:"4px 0",borderBottom:"1px solid #eee"}});u.append(b)}else u.append(o.divText("No annotations on this column.",{style:{color:"#888",padding:"8px"}}))}h();const d=o.button("Clear All",()=>{(0,a.OW)(e,n),e.fireValuesChanged(),h(),i.shell.info("All annotations cleared")});o.dialog({title:"Manage Annotations"}).add(o.inputs([r])).add(o.h3("Annotations")).add(u).add(o.divH([d],{style:{marginTop:"8px"}})).onOK(()=>{}).show()}},3736(e,t,n){"use strict";n.d(t,{JG:()=>u,Ln:()=>s,Lz:()=>l,OW:()=>m,VT:()=>a,bq:()=>p,fh:()=>r,wi:()=>h,z5:()=>d});var i=n(2003),o=n(4517);function s(e){const t=e.getTag(i.gp.annotations);if(t)try{return JSON.parse(t)}catch{}const n=e.getTag(i.gp.regions);if(n)try{return JSON.parse(n).map((e,t)=>({id:`legacy-region-${t}`,name:e.name,description:e.description,start:e.start,end:e.end,visualType:o.ao.Region,category:o.eI.Structure,autoGenerated:!0}))}catch{}return[]}function r(e,t){e.setTag(i.gp.annotations,JSON.stringify(t));const n=t.filter(e=>e.category===o.eI.Structure);if(n.length>0){const t=n.filter(e=>null!=e.start&&null!=e.end).map(e=>({name:e.name,description:e.description??"",start:e.start,end:e.end}));e.setTag(i.gp.regions,JSON.stringify(t))}}function a(e){return`~${e}_annotations`}function l(e,t){const n=a(t.name);let o=e.columns.byName(n);return o||(o=e.columns.addNewString(n),t.setTag(i.gp.annotationColumnName,n)),o}const c=new WeakMap;function u(e,t){const n=c.get(e);if(n&&n.version===e.version&&void 0!==n.data[t])return n.data[t];const i=e.get(t);if(!i)return null;try{return JSON.parse(i)}catch{return null}}function h(e){const t=c.get(e);if(t&&t.version===e.version)return t.data;const n=new Array(e.length);for(let t=0;t<e.length;t++){const i=e.get(t);if(i)try{n[t]=JSON.parse(i)}catch{n[t]=null}else n[t]=null}return c.set(e,{version:e.version,data:n}),n}function d(e,t,n){e.set(t,n.length>0?JSON.stringify(n):"")}function m(e,t){t.setTag(i.gp.annotations,"");const n=a(t.name);e.columns.byName(n)&&e.columns.remove(n),t.setTag(i.gp.regions,"")}function p(e,t,n,i){let o=e;return n&&(o=o.filter(e=>null==e.endPositionIndex)),i&&(o=o.filter(e=>null!=e.endPositionIndex)),[...o,...t]}},9422(e,t,n){"use strict";n.d(t,{showLiabilityScannerDialog:()=>d});var i=n(4328),o=n(7389),s=n(6082),r=n(3328),a=n(4517),l=n(3736);const c=[{id:"deamid-ng",name:"Deamidation (NG)",pattern:/NG/g,length:2,severity:a.Hq.High,ruleCategory:"deamidation",color:a.D5.liability.deamidation,enabled:!0},{id:"deamid-ns",name:"Deamidation (NS)",pattern:/NS/g,length:2,severity:a.Hq.Medium,ruleCategory:"deamidation",color:a.D5.liability.deamidation,enabled:!0},{id:"deamid-na",name:"Deamidation (NA)",pattern:/NA/g,length:2,severity:a.Hq.Low,ruleCategory:"deamidation",color:a.D5.liability.deamidation,enabled:!0},{id:"deamid-nd",name:"Deamidation (ND)",pattern:/ND/g,length:2,severity:a.Hq.Low,ruleCategory:"deamidation",color:a.D5.liability.deamidation,enabled:!0},{id:"deamid-nt",name:"Deamidation (NT)",pattern:/NT/g,length:2,severity:a.Hq.Low,ruleCategory:"deamidation",color:a.D5.liability.deamidation,enabled:!0},{id:"isom-dg",name:"Isomerization (DG)",pattern:/DG/g,length:2,severity:a.Hq.High,ruleCategory:"isomerization",color:a.D5.liability.isomerization,enabled:!0},{id:"isom-ds",name:"Isomerization (DS)",pattern:/DS/g,length:2,severity:a.Hq.Medium,ruleCategory:"isomerization",color:a.D5.liability.isomerization,enabled:!0},{id:"oxid-m",name:"Oxidation (Met)",pattern:/M/g,length:1,severity:a.Hq.Medium,ruleCategory:"oxidation",color:a.D5.liability.oxidation,enabled:!0},{id:"oxid-w",name:"Oxidation (Trp)",pattern:/W/g,length:1,severity:a.Hq.Low,ruleCategory:"oxidation",color:a.D5.liability.oxidation,enabled:!0},{id:"glyco-nxst",name:"N-glycosylation",pattern:/N[^P][ST]/g,length:3,severity:a.Hq.High,ruleCategory:"glycosylation",color:a.D5.liability.glycosylation,enabled:!0},{id:"free-cys",name:"Free Cysteine",pattern:/C/g,length:1,severity:a.Hq.Info,ruleCategory:"freeCysteine",color:a.D5.liability.freeCysteine,enabled:!1}];function u(e,t){const n=e.getSplitted(t),i=new Array(n.length);for(let e=0;e<n.length;e++)i[e]=n.getOriginal(e);return i.join("")}const h={[a.Hq.High]:"High",[a.Hq.Medium]:"Medium",[a.Hq.Low]:"Low",[a.Hq.Info]:"Info"};function d(){const e=i.shell.tv?.dataFrame;if(!e)return void i.shell.warning("No table open");const t=e.columns.bySemTypeAll(s.SEMTYPE.MACROMOLECULE);if(0===t.length)return void i.shell.warning("No macromolecule columns found");const n=c.map(e=>({...e,pattern:new RegExp(e.pattern.source,"g")})),d=o.input.table("Table",{value:e}),m=o.input.column("Sequence",{table:e,value:t[0],filter:e=>e.semType===s.SEMTYPE.MACROMOLECULE}),p=[],g=o.divV([]);for(const e of n){const t=o.input.bool(e.name,{value:e.enabled,tooltipText:`Severity: ${h[e.severity]??e.severity}`});p.push({rule:e,input:t}),g.append(t.root)}const f=o.input.bool("Highlight in cell renderer",{value:!0}),y=o.input.bool("Create annotation column",{value:!0}),b=o.input.bool("Create summary count column",{value:!1}),w=o.dialog({title:"Scan Sequence Liabilities"}).add(o.inputs([d,m])).add(o.h3("Rules")).add(g).add(o.h3("Output")).add(o.inputs([f,y,b])).onOK(()=>{try{const t=m.value,o=r._package.seqHelper.getSeqHandler(t);for(const{rule:e,input:t}of p)e.enabled=t.value;const s=function(e,t,n){const i=n.filter(e=>e.enabled),o=t.posList,s=new Map,r=new Array(e.length);let l=0;for(let n=0;n<e.length;n++){const e=u(t,n),a=[];for(const t of i){let n;for(t.pattern.lastIndex=0;null!==(n=t.pattern.exec(e));)a.push({annotationId:t.id,positionIndex:n.index,positionName:n.index<o.length?o[n.index]:void 0,matchedMonomers:n[0]}),s.set(t.id,(s.get(t.id)??0)+1),l++}r[n]=a}return{annotations:i.filter(e=>s.has(e.id)).map(e=>({id:e.id,name:e.name,description:`${e.ruleCategory} liability pattern (${s.get(e.id)} hits)`,start:null,end:null,visualType:1===e.length?a.ao.Point:a.ao.Motif,category:a.eI.Liability,color:e.color,severity:e.severity,motifPattern:e.pattern.source,autoGenerated:!0})),rowData:r,totalHits:l}}(t,o,n);(y.value||f.value)&&function(e,t,n){const i=(0,l.Ln)(t).filter(e=>e.category!==a.eI.Liability);(0,l.fh)(t,[...i,...n.annotations]);const o=(0,l.Lz)(e,t);for(let e=0;e<n.rowData.length;e++){const t=(0,l.JG)(o,e)??[];(0,l.z5)(o,e,(0,l.bq)(t,n.rowData[e],!1,!0))}}(e,t,s),b.value&&function(e,t,n){const i=`${t.name}_liability_count`,o=n.rowData.map(e=>e.length),s=e.columns.addNewInt(i);for(let e=0;e<o.length;e++)s.set(e,o[e])}(e,t,s),i.shell.info(`Liability scan: ${s.totalHits} hits found across ${s.annotations.length} rules`),e.fireValuesChanged()}catch(e){i.shell.error(`Liability scan failed: ${e.message??e}`),console.error(e)}});w.show()}},6839(e,t,n){"use strict";n.d(t,{showNumberingSchemeDialog:()=>u});var i=n(4328),o=n(7389),s=n(6082),r=n(2003),a=n(4517),l=n(3736);function c(e){const t=e.func.inputs.find(e=>"scheme"===e.name.toLowerCase()),n=t?.choices??[];return n.length>0?n.slice():["imgt"]}function u(){const e=i.shell.tv?.dataFrame;if(!e)return void i.shell.warning("No table open");const t=e.columns.bySemTypeAll(s.SEMTYPE.MACROMOLECULE);if(0===t.length)return void i.shell.warning("No macromolecule columns found");const n=function(){const e=[],t=s.Func.find({meta:{role:"antibodyNumbering"}});if(0===t.length)throw i.shell.error("No antibody numbering engines found. Make sure the Bio package is up to date."),new Error("No antibody numbering engines found.");for(const n of t){const t=n.package?.name??"";e.push({label:n.friendlyName||n.name,key:t?`${t}:${n.name}`:n.name,func:n})}return e}(),u=n.map(e=>e.label),m=o.input.table("Table",{value:e}),p=o.input.column("Sequence",{table:e,value:t[0],filter:e=>e.semType===s.SEMTYPE.MACROMOLECULE}),g=o.input.choice("Engine",{value:u[0],items:u}),f=c(n[0]),y=o.input.choice("Scheme",{value:f[0],items:f});g.onChanged.subscribe(()=>{const e=n.find(e=>e.label===g.value);if(!e)return;const t=c(e),i=y.value;y.items=t,y.value=t.includes(i??"")?i:t[0]});const b=o.dialog({title:"Apply Antibody Numbering"}).add(o.inputs([m,p,g,y])).onOK(async()=>{const t=p.value,o=y.value,c=g.value,u=n.find(e=>e.label===c)??n[0],m=s.TaskBarProgressIndicator.create(`Applying ${o} numbering...`);try{const n=await u.func.apply({df:e,seqCol:t,scheme:o});!function(e,t,n,o,c,u){if(!n||0===n.rowCount)return void i.shell.warning("No numbering results returned");const m=n.getCol("position_names"),p=n.getCol("chain_type"),g=n.getCol("annotations_json"),f=n.col("numbering_map");if(f)for(let e=0;e<n.rowCount;e++){const n=f.get(e);if(n)try{const i=JSON.parse(n),o=h(t.get(e)??""),s={};for(const[e,t]of Object.entries(i))t<o.length&&(s[e]=o[t]);f.set(e,JSON.stringify(s))}catch{}}let y=-1,b=-1;for(let e=0;e<n.rowCount;e++){const t=m.get(e);if(!t||0===t.length)continue;const n=g.get(e);let i=0;if(n)try{i=JSON.parse(n).length}catch{}i>b&&(b=i,y=e)}const w=y>=0?p.get(y)??"":"",v=y>=0?g.get(y)??"[]":"[]";if(y<0)return void i.shell.warning(`${u} could not number the sequences. Check that they are valid antibody variable region sequences.`);t.setTag(r.gp.numberingScheme,o);try{const e=JSON.parse(v),n=(0,l.Ln)(t).filter(e=>e.category!==a.eI.Structure);(0,l.fh)(t,[...n,...e])}catch(e){console.warn("Failed to set annotation definitions on original column:",e)}if(f)try{const i=(0,l.Lz)(e,t);for(let e=0;e<n.rowCount;e++){const t=f.get(e),n=g.get(e);if(!t||!n)continue;const o=JSON.parse(t),s=JSON.parse(n),r=[];for(const e of s){if(null==e.start||null==e.end)continue;const t=o[e.start],n=o[e.end];null!=t&&null!=n&&r.push({annotationId:e.id,positionIndex:t,endPositionIndex:n,positionName:e.start,matchedMonomers:""})}const a=(0,l.JG)(i,e)??[];(0,l.z5)(i,e,(0,l.bq)(a,r,!0,!1))}}catch(e){console.warn("Failed to store per-row region data on original column:",e)}const C=function(e,t,n){const i=n.col("numbering_map");if(!i)return null;const o=new Set,a=[],l=[],c=[];for(let e=0;e<n.rowCount;e++){const n=i.get(e),s=t.get(e)??"";if(n)try{const e=JSON.parse(n);a.push(e);for(const t of Object.keys(e))o.add(t);const t=Object.values(e),i=Math.min(...t),r=Math.max(...t);l.push(i),c.push(Math.max(0,s.length-r-1))}catch{a.push(null),l.push(0),c.push(0)}else a.push(null),l.push(0),c.push(0)}if(0===o.size)return null;const u=Math.max(0,...l),h=Math.max(0,...c),m=Array.from(o).slice().sort((e,t)=>{const[n,i]=d(e),[o,s]=d(t);return n!==o?n-o:i.localeCompare(s)}),p=[];for(let e=u;e>0;e--)p.push(`N-${e}`);const g=[];for(let e=1;e<=h;e++)g.push(`C+${e}`);const f=[...p,...m,...g],y=f.length,b=u,w=new Map;for(let e=0;e<m.length;e++)w.set(m[e],b+e);const v=e.columns.getUnusedName(`${t.name} (aligned)`),C=s.Column.fromType(s.COLUMN_TYPE.STRING,v,e.rowCount);for(let n=0;n<e.rowCount;n++){const e=n<a.length?a[n]:null,i=t.get(n)??"";if(!e){C.set(n,"-".repeat(y));continue}const o=new Array(y).fill("-");for(const[t,n]of Object.entries(e)){const e=w.get(t);null!=e&&n<i.length&&(o[e]=i[n])}const s=l[n],r=Object.values(e),u=Math.min(...r);for(let e=0;e<s;e++)o[b-s+e]=i[u-s+e];const h=c[n],d=Math.max(...r),p=b+m.length;for(let e=0;e<h;e++)o[p+e]=i[d+1+e];C.set(n,o.join(""))}return C.semType=s.SEMTYPE.MACROMOLECULE,C.setTag(r.gp.aligned,"SEQ.MSA"),C.setTag(r.gp.alphabet,r.YI.PT),C.meta.units=r.Hi.FASTA,C.setTag(s.Tags.CellRenderer,"sequence"),C.setTag(r.gp.positionNames,f.join(", ")),{alignedCol:C,unifiedPositions:f,preOffset:b}}(e,t,n);if(C&&(e.columns.insert(C.alignedCol,e.columns.toList().indexOf(t)+1),i.shell.tv?.dataFrame===e&&i.shell.tv.grid.scrollToCell(t,0),C.alignedCol.setTag(r.gp.numberingScheme,o),c))try{const e=JSON.parse(v),t=(0,l.Ln)(C.alignedCol).filter(e=>e.category!==a.eI.Structure);(0,l.fh)(C.alignedCol,[...t,...e])}catch(e){console.warn("Failed to set column-level annotations on aligned column:",e)}e.fireValuesChanged(),i.shell.info(`Numbering applied: ${o}, chain type: ${w}`)}(e,t,n,o,!0,u.label)}catch(e){i.shell.error(`Numbering failed: ${e.message??e}`),console.error(e)}finally{m.close()}});b.show()}function h(e){const t=[];for(let n=0;n<e.length;n++)"-"!==e[n]&&"."!==e[n]&&t.push(n);return t}function d(e){const t=e.match(/^(\d+)([A-Z]?)$/);return t?[parseInt(t[1],10),t[2]]:[1/0,e]}},417(e,t,n){"use strict";async function i(e,t,i,o){const s=new Worker(new URL(n.p+n.u(909),n.b));try{const n=await function(e,t){return new Promise((n,i)=>{const o=new MessageChannel;o.port1.onmessage=({data:e})=>{o.port1.close(),n(e)},o.port1.onmessageerror=e=>{o.port1.close(),i(e)},e.postMessage({req:t},[o.port2])})}(s,{op:"number",sequences:e,scheme:t,chains:i,minConfidence:o});if(!n.ok)throw new Error(n.error);return n.rows??[]}finally{s.terminate()}}n.d(t,{m:()=>i})},9036(e,t,n){"use strict";n.d(t,{C:()=>m});var i,o,s=n(6082);!function(e){e.IMGT="IMGT",e.Kabat="Kabat",e.Chothia="Chothia",e.AHo="AHo"}(i||(i={})),function(e){e.Heavy="Heavy",e.Light_Kappa="Light_Kappa",e.Light_Lambda="Light_Lambda"}(o||(o={}));const r={[o.Heavy]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"26",chainType:o.Heavy},{name:"CDR1",type:"CDR",startPosition:"27",endPosition:"38",chainType:o.Heavy},{name:"FR2",type:"FR",startPosition:"39",endPosition:"55",chainType:o.Heavy},{name:"CDR2",type:"CDR",startPosition:"56",endPosition:"65",chainType:o.Heavy},{name:"FR3",type:"FR",startPosition:"66",endPosition:"104",chainType:o.Heavy},{name:"CDR3",type:"CDR",startPosition:"105",endPosition:"117",chainType:o.Heavy},{name:"FR4",type:"FR",startPosition:"118",endPosition:"128",chainType:o.Heavy}],[o.Light_Kappa]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"26",chainType:o.Light_Kappa},{name:"CDR1",type:"CDR",startPosition:"27",endPosition:"38",chainType:o.Light_Kappa},{name:"FR2",type:"FR",startPosition:"39",endPosition:"55",chainType:o.Light_Kappa},{name:"CDR2",type:"CDR",startPosition:"56",endPosition:"65",chainType:o.Light_Kappa},{name:"FR3",type:"FR",startPosition:"66",endPosition:"104",chainType:o.Light_Kappa},{name:"CDR3",type:"CDR",startPosition:"105",endPosition:"117",chainType:o.Light_Kappa},{name:"FR4",type:"FR",startPosition:"118",endPosition:"127",chainType:o.Light_Kappa}],[o.Light_Lambda]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"26",chainType:o.Light_Lambda},{name:"CDR1",type:"CDR",startPosition:"27",endPosition:"38",chainType:o.Light_Lambda},{name:"FR2",type:"FR",startPosition:"39",endPosition:"55",chainType:o.Light_Lambda},{name:"CDR2",type:"CDR",startPosition:"56",endPosition:"65",chainType:o.Light_Lambda},{name:"FR3",type:"FR",startPosition:"66",endPosition:"104",chainType:o.Light_Lambda},{name:"CDR3",type:"CDR",startPosition:"105",endPosition:"117",chainType:o.Light_Lambda},{name:"FR4",type:"FR",startPosition:"118",endPosition:"127",chainType:o.Light_Lambda}]},a={[o.Heavy]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"30",chainType:o.Heavy},{name:"CDR1",type:"CDR",startPosition:"31",endPosition:"35",chainType:o.Heavy},{name:"FR2",type:"FR",startPosition:"36",endPosition:"49",chainType:o.Heavy},{name:"CDR2",type:"CDR",startPosition:"50",endPosition:"65",chainType:o.Heavy},{name:"FR3",type:"FR",startPosition:"66",endPosition:"94",chainType:o.Heavy},{name:"CDR3",type:"CDR",startPosition:"95",endPosition:"102",chainType:o.Heavy},{name:"FR4",type:"FR",startPosition:"103",endPosition:"113",chainType:o.Heavy}],[o.Light_Kappa]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"23",chainType:o.Light_Kappa},{name:"CDR1",type:"CDR",startPosition:"24",endPosition:"34",chainType:o.Light_Kappa},{name:"FR2",type:"FR",startPosition:"35",endPosition:"49",chainType:o.Light_Kappa},{name:"CDR2",type:"CDR",startPosition:"50",endPosition:"56",chainType:o.Light_Kappa},{name:"FR3",type:"FR",startPosition:"57",endPosition:"88",chainType:o.Light_Kappa},{name:"CDR3",type:"CDR",startPosition:"89",endPosition:"97",chainType:o.Light_Kappa},{name:"FR4",type:"FR",startPosition:"98",endPosition:"107",chainType:o.Light_Kappa}],[o.Light_Lambda]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"23",chainType:o.Light_Lambda},{name:"CDR1",type:"CDR",startPosition:"24",endPosition:"34",chainType:o.Light_Lambda},{name:"FR2",type:"FR",startPosition:"35",endPosition:"49",chainType:o.Light_Lambda},{name:"CDR2",type:"CDR",startPosition:"50",endPosition:"56",chainType:o.Light_Lambda},{name:"FR3",type:"FR",startPosition:"57",endPosition:"88",chainType:o.Light_Lambda},{name:"CDR3",type:"CDR",startPosition:"89",endPosition:"97",chainType:o.Light_Lambda},{name:"FR4",type:"FR",startPosition:"98",endPosition:"107",chainType:o.Light_Lambda}]},l={[o.Heavy]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"25",chainType:o.Heavy},{name:"CDR1",type:"CDR",startPosition:"26",endPosition:"32",chainType:o.Heavy},{name:"FR2",type:"FR",startPosition:"33",endPosition:"51",chainType:o.Heavy},{name:"CDR2",type:"CDR",startPosition:"52",endPosition:"56",chainType:o.Heavy},{name:"FR3",type:"FR",startPosition:"57",endPosition:"94",chainType:o.Heavy},{name:"CDR3",type:"CDR",startPosition:"95",endPosition:"102",chainType:o.Heavy},{name:"FR4",type:"FR",startPosition:"103",endPosition:"113",chainType:o.Heavy}],[o.Light_Kappa]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"25",chainType:o.Light_Kappa},{name:"CDR1",type:"CDR",startPosition:"26",endPosition:"32",chainType:o.Light_Kappa},{name:"FR2",type:"FR",startPosition:"33",endPosition:"49",chainType:o.Light_Kappa},{name:"CDR2",type:"CDR",startPosition:"50",endPosition:"52",chainType:o.Light_Kappa},{name:"FR3",type:"FR",startPosition:"53",endPosition:"90",chainType:o.Light_Kappa},{name:"CDR3",type:"CDR",startPosition:"91",endPosition:"96",chainType:o.Light_Kappa},{name:"FR4",type:"FR",startPosition:"97",endPosition:"107",chainType:o.Light_Kappa}],[o.Light_Lambda]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"25",chainType:o.Light_Lambda},{name:"CDR1",type:"CDR",startPosition:"26",endPosition:"32",chainType:o.Light_Lambda},{name:"FR2",type:"FR",startPosition:"33",endPosition:"49",chainType:o.Light_Lambda},{name:"CDR2",type:"CDR",startPosition:"50",endPosition:"52",chainType:o.Light_Lambda},{name:"FR3",type:"FR",startPosition:"53",endPosition:"90",chainType:o.Light_Lambda},{name:"CDR3",type:"CDR",startPosition:"91",endPosition:"96",chainType:o.Light_Lambda},{name:"FR4",type:"FR",startPosition:"97",endPosition:"107",chainType:o.Light_Lambda}]},c={[o.Heavy]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"24",chainType:o.Heavy},{name:"CDR1",type:"CDR",startPosition:"25",endPosition:"40",chainType:o.Heavy},{name:"FR2",type:"FR",startPosition:"41",endPosition:"55",chainType:o.Heavy},{name:"CDR2",type:"CDR",startPosition:"56",endPosition:"78",chainType:o.Heavy},{name:"FR3",type:"FR",startPosition:"79",endPosition:"108",chainType:o.Heavy},{name:"CDR3",type:"CDR",startPosition:"109",endPosition:"138",chainType:o.Heavy},{name:"FR4",type:"FR",startPosition:"139",endPosition:"149",chainType:o.Heavy}],[o.Light_Kappa]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"24",chainType:o.Light_Kappa},{name:"CDR1",type:"CDR",startPosition:"25",endPosition:"40",chainType:o.Light_Kappa},{name:"FR2",type:"FR",startPosition:"41",endPosition:"55",chainType:o.Light_Kappa},{name:"CDR2",type:"CDR",startPosition:"56",endPosition:"78",chainType:o.Light_Kappa},{name:"FR3",type:"FR",startPosition:"79",endPosition:"108",chainType:o.Light_Kappa},{name:"CDR3",type:"CDR",startPosition:"109",endPosition:"138",chainType:o.Light_Kappa},{name:"FR4",type:"FR",startPosition:"139",endPosition:"149",chainType:o.Light_Kappa}],[o.Light_Lambda]:[{name:"FR1",type:"FR",startPosition:"1",endPosition:"24",chainType:o.Light_Lambda},{name:"CDR1",type:"CDR",startPosition:"25",endPosition:"40",chainType:o.Light_Lambda},{name:"FR2",type:"FR",startPosition:"41",endPosition:"55",chainType:o.Light_Lambda},{name:"CDR2",type:"CDR",startPosition:"56",endPosition:"78",chainType:o.Light_Lambda},{name:"FR3",type:"FR",startPosition:"79",endPosition:"108",chainType:o.Light_Lambda},{name:"CDR3",type:"CDR",startPosition:"109",endPosition:"138",chainType:o.Light_Lambda},{name:"FR4",type:"FR",startPosition:"139",endPosition:"149",chainType:o.Light_Lambda}]},u={[i.IMGT]:r,[i.Kabat]:a,[i.Chothia]:l,[i.AHo]:c};var h=n(417);function d(e,t,n){if(!t)return[];const s="kabat"===(e||"").toLowerCase()?i.Kabat:i.IMGT,r=u[s],a=function(e,t){return"Light"===e?"L"===t?o.Light_Lambda:o.Light_Kappa:o.Heavy}(t,n),l=r?.[a];if(!l)return[];const c=e.toLowerCase();return l.map(n=>({id:`${c}-${t}-${n.name}`.toLowerCase(),name:n.name,description:`${n.name} (${e.toUpperCase()} ${n.startPosition}-${n.endPosition})`,start:n.startPosition,end:n.endPosition,visualType:"region",category:"structure",sourceScheme:e.toUpperCase(),autoGenerated:!0}))}async function m(e,t){const n=e.length,i=new Array(n);for(let t=0;t<n;t++)i[t]=e.get(t)??"";const o=function(e){return"kabat"===(e||"").toLowerCase()?"kabat":"imgt"}(t),r=await(0,h.m)(i,o),a=s.Column.fromType(s.COLUMN_TYPE.STRING,"position_names",n),l=s.Column.fromType(s.COLUMN_TYPE.STRING,"chain_type",n),c=s.Column.fromType(s.COLUMN_TYPE.STRING,"annotations_json",n),u=s.Column.fromType(s.COLUMN_TYPE.STRING,"numbering_detail",n),m=s.Column.fromType(s.COLUMN_TYPE.STRING,"numbering_map",n);for(let e=0;e<n;e++){const n=r[e];n&&!n.error&&n.positionNames?(a.set(e,n.positionNames),l.set(e,n.chainType),c.set(e,JSON.stringify(d(t,n.chainType,n.chainCode))),u.set(e,JSON.stringify(n.numberingDetail)),m.set(e,JSON.stringify(n.numberingMap))):(a.set(e,""),l.set(e,""),c.set(e,"[]"),u.set(e,""),m.set(e,""))}return s.DataFrame.fromColumns([a,l,c,u,m])}},966(e,t,n){"use strict";n.d(t,{V:()=>r,l:()=>a});var i=n(4328),o=n(6082),s=n(3328);function r(e,t,n=[],o=[],r=!0){const l=s._package.seqHelper,[c,u]=a(e,t,l,n,o);return r&&!c&&i.shell.warning(u),c}function a(e,t,n,s=[],r=[]){let a=!0,l="";if(e.semType!==o.SEMTYPE.MACROMOLECULE)i.shell.warning(t+" analysis is allowed for Macromolecules semantic type"),a=!1;else{const i=n.getSeqHandler(e),o=i.notation;if(s.length>0&&!s.some(e=>o.toUpperCase()==e.toUpperCase()))l=`${t} + ' analysis is allowed for Macromolecules with notation ${0==s.length?"any notation":`notation${s.length>1?"s":""} ${s.map(e=>`"${e}"`).join(", ")} `}.`,a=!1;else if(!i.isHelm()){const e=i.alphabet;r.length>0&&!r.some(t=>e.toUpperCase()==t.toUpperCase())&&(l=`${t} + ' analysis is allowed for Macromolecules with alphabet ${0==r.length?"any alphabet":`alphabet${r.length>1?"s":""} ${r.map(e=>`"${e}"`).join(", ")}.`}.`,a=!1)}}return[a,l]}},4139(e,t,n){"use strict";var i,o,s;n.d(t,{J:()=>l,W_:()=>u,b9:()=>c,gN:()=>r,uF:()=>s}),function(e){e.SPLIT_COL="~split",e.ACTIVITY="~activity",e.ACTIVITY_SCALED="activity_scaled",e.ALIGNED_SEQUENCE="~aligned_sequence",e.AMINO_ACID_RESIDUE="AAR",e.POSITION="Pos",e.P_VALUE="pValue",e.MEAN_DIFFERENCE="Mean difference"}(i||(i={})),function(e){e.AAR="AAR",e.POSITION="Pos",e.SELECTION="selection"}(o||(o={})),function(e){e.MONOMER="Monomer",e.MACROMOLECULE_DIFFERENCE="MacromoleculeDifference",e.ACTIVITY="activity",e.ACTIVITY_SCALED="activityScaled"}(s||(s={}));const r="MSA";var a,l;!function(e){e.CELL_CHANGING="isCellChanging"}(a||(a={})),function(e){e.SEPARATOR="."}(l||(l={}));const c="3.3.1",u="sequenceMSA"},5433(e,t,n){"use strict";n.d(t,{C:()=>d,r:()=>m});var i=n(6082),o=n(7389),s=n(4328),r=n(1757),a=n.n(r),l=n(2003),c=n(2738);let u=null,h=[];async function d(e,t){let n=e??s.shell.t.columns.bySemType("Macromolecule");if(!n)throw new Error("No column with Macromolecule semantic type found");let r=t.getSeqHandler(n),d=r.notation;const p=o.divText("Current notation: "+d,{style:{"text-align":"center","font-weight":"bold","font-size":"14px",padding:"5px"}}),g=[l.Hi.FASTA,l.Hi.SEPARATOR,l.Hi.HELM,l.Hi.BILN],f=await c.$G.getProviderConstructors(),y=o.input.column("Column",{table:s.shell.t,value:n,filter:e=>e.semType===i.SEMTYPE.MACROMOLECULE,nullable:!1,onValueChanged:e=>(n=e,r=t.getSeqHandler(n),d=r.notation,d===l.Hi.HELM&&(v.value="/"),p.textContent="Current notation: "+d,w=g.filter(e=>e!==d),d===l.Hi.CUSTOM&&(w=[l.Hi.HELM]),d===l.Hi.HELM&&f.forEach(e=>{e.implementsFromHelm&&w.unshift(e.notationName)}),A=o.input.choice("Convert to",{value:w[0],items:w,onValueChanged:C}),C(),u?.clear(),void u?.add(o.div([p,y.root,A.root,v.root])))}),b=["-",".","/"];let w=g.filter(e=>e!==d);d===l.Hi.CUSTOM&&(w=[l.Hi.HELM]),d===l.Hi.HELM&&f.forEach(e=>{e.implementsFromHelm&&w.unshift(e.notationName)});const v=o.input.choice("Separator",{value:b[0],items:b}),C=()=>{A.value!==l.Hi.SEPARATOR?a()(v.root).hide():a()(v.root).show()};let A=o.input.choice("Convert to",{value:w[0],items:w,onValueChanged:C});C(),A.onChanged.subscribe(()=>{C()}),null==u&&(u=o.dialog("Convert Sequence Notation").add(o.div([p,y.root,A.root,v.root])).onOK(async()=>{const e=A.value,i=e===l.Hi.SEPARATOR?v.value:void 0;let o;!g.includes(e)&&f.find(t=>t.notationName===e)&&(o=f.find(t=>t.notationName===e)),await m(n,t,e,i,o)}).show({x:350,y:100}),h.push(u.onClose.subscribe(e=>{h.forEach(e=>{e.unsubscribe()}),h=[],u=null})))}async function m(e,t,n,o,r){if(r){const t=e.dataFrame.columns.getUnusedName(`${r.notationName}(${e.name})`),n=i.Column.string(t,e.length);return n.init(t=>{const n=e.get(t);try{return r.convertFromHelm(n,{})}catch(e){return console.error(`Error converting sequence at row ${t}: ${e instanceof Error?e.message:e}`),""}}),n.semType=i.SEMTYPE.MACROMOLECULE,n.meta.units=l.Hi.CUSTOM,n.setTag("separator","-"),n.setTag("aligned","SEQ"),n.setTag("alphabet","UN"),n.setTag(".alphabetIsMultichar","true"),e.dataFrame.columns.add(n),await s.data.detectSemanticTypes(e.dataFrame),n}{const i=t.getSeqHandler(e).convert(n,o);e.dataFrame.columns.add(i);const r=await s.functions.call("Bio:detectMacromolecule",{col:i});return r&&(i.semType=r),await s.data.detectSemanticTypes(e.dataFrame),i}}},6956(e,t,n){"use strict";n.d(t,{m:()=>o,x:()=>i});const i="|",o="H"},2582(e,t,n){"use strict";n.d(t,{f:()=>a});var i=n(6956);class o{constructor(e){const t=e.split(i.x).filter(e=>e);t.forEach(e=>this.validateConnectionItem(e)),this.connectionItems=t}connectionItems;validateConnectionItem(e){const t="(PEPTIDE|RNA|CHEM|BLOB)",n=new RegExp(`${t}[0-9]+,${t}[0-9]+,[0-9]+:R[0-9]+-[0-9]+:R[0-9]+`,"g");if(!e.match(n))throw new Error(`Cannot parse connection item from ${e}`)}getConnectionData(){const e=[];return this.connectionItems.forEach(t=>{const n=[],i=t.split(",");i[2].split("-").forEach((e,t)=>{const o=i[t],s=e.split(":"),r={monomerIdx:parseInt(s[0])-1,rGroupId:parseInt(s[1].slice(1))};n.push({polymerId:o,bond:r})}),e.push(n)}),e}}var s=n(8438);class r{simplePolymer;isNucleotideSequence=!1;constructor(e){this.simplePolymer=e,this.polymerType=this.getPolymerType(),this.isNucleotideSequence="RNA"===this.polymerType,this.idx=this.getIdx();const{monomers:t,monomerTypes:n}=this.getMonomerSymbolsAndTypes();this.monomers=t,this.monomerTypes=n}polymerType;monomers;idx;monomerTypes;get id(){return this.polymerType+this.idx.toString()}getPolymerType(){const e=new RegExp("(PEPTIDE|RNA|CHEM|BLOB)[0-9]+{"),t=this.simplePolymer.match(e);if(!t)throw new Error(`Unsupported polymer type in ${this.simplePolymer}`);return t[1]}getIdx(){const e=new RegExp(`${this.polymerType}([0-9]+){`),t=this.simplePolymer.match(e);if(!t)throw new Error(`Cannot parse simple polymer id from ${this.simplePolymer}`);return parseInt(t[1])}getMonomerSymbolsAndTypes(){const e=new RegExp(`${this.polymerType}${this.idx}{|}`,"g"),t=this.simplePolymer.replace(e,"").split("."),n=[],i=[];return t.forEach(e=>{if(this.isNucleotideSequence){const t=e.split(/\(|\)/).filter(e=>!!e).map(e=>(0,s.D)(e));n.push(...t),t.forEach((e,t)=>i.push(t%3==1?"Branch":"Backbone"))}else n.push((0,s.D)(e)),i.push("Backbone")}),{monomers:n,monomerTypes:i}}getBondData(){const e=[],t=this.monomerTypes.map((e,t)=>{if("Backbone"===e)return t}).filter(e=>void 0!==e),n=this.monomerTypes.map((e,t)=>{if("Branch"===e)return t}).filter(e=>void 0!==e);for(let n=0;n<t.length-1;n++){const i=t[n],o=t[n+1];e.push([{monomerIdx:i,rGroupId:2},{monomerIdx:o,rGroupId:1}])}for(let t=0;t<n.length;t++){const i=n[t],o=i-1;e.push([{monomerIdx:o,rGroupId:3},{monomerIdx:i,rGroupId:1}])}return e}}class a{helmString;constructor(e){this.helmString=e;const t=e.indexOf("}$"),n=e.substring(0,t+1),i=e.indexOf("$",t+2),s=e.substring(t+2,i),a=n.split("}|");for(let e=0;e<a.length-1;e++)a[e]=a[e]+"}";this.simplePolymers=a.map(e=>new r(e)),this.connectionList=new o(s),this.bondData=this.getBondData(),this.bondedRGroupsMap=this.getBondedRGroupsMap()}bondData;simplePolymers;connectionList;bondedRGroupsMap;getBondedRGroupsMap(){const e=this.simplePolymers.map(e=>e.monomers.length).reduce((e,t)=>e+t,0),t=Array.from({length:e},()=>[]);return this.bondData.forEach(e=>{e.forEach(e=>{const n=e.monomerIdx,i=e.rGroupId;t[n].push(i)})}),t}toString(){return this.helmString}getPolymerTypeByMonomerIdx(e){return this.getSimplePolymerByMonomerIdx(e).polymerType}getSimplePolymerByMonomerIdx(e){const t=this.getMonomerIdxShifts(),n=Object.values(t).sort((e,t)=>t-e).find(t=>e>=t);if(null==n)throw new Error(`Cannot find simple polymer for monomer ${e}`);const i=Object.keys(t).find(e=>t[e]===n);return this.simplePolymers.find(e=>e.id===i)}shiftBondMonomerIds(e,t){t.forEach(t=>{t.forEach(t=>{t.monomerIdx+=e})})}getMonomerIdxShifts(){const e={};let t=0;return this.simplePolymers.forEach(n=>{e[n.id]=t,t+=n.monomers.length}),e}getBondData(){const e=this.getMonomerIdxShifts(),t=[];return this.simplePolymers.forEach(n=>{const i=n.getBondData(),o=e[n.id];this.shiftBondMonomerIds(o,i),t.push(...i)}),this.connectionList.getConnectionData().forEach(n=>{const i=[];n.forEach(t=>{const n=e[t.polymerId],o=t.bond;o.monomerIdx+=n,i.push(o)}),t.push(i)}),t}}},8604(e,t,n){"use strict";n.d(t,{G:()=>i,V:()=>o});const i={explicit:["HELMCoreLibrary.json","polytool-lib.json"],exclude:[],duplicateMonomerPreferences:{}},o={PEPTIDE:334,RNA:390,CHEM:0}},1619(e,t,n){"use strict";n.d(t,{D:()=>x});var i=n(4328),o=n(6082),s=n(7389),r=n(2003),a=n(4025),l=n(608),c=n(966),u=n(4139),h=n(3328),d=n(5072),m=n.n(d),p=n(7825),g=n.n(p),f=n(7659),y=n.n(f),b=n(5056),w=n.n(b),v=n(540),C=n.n(v),A=n(1113),T=n.n(A),E=n(6369),S={};S.styleTagTransform=T(),S.setAttributes=w(),S.insert=y().bind(null,"head"),S.domAPI=g(),S.insertStyleElement=C(),m()(E.A,S),E.A&&E.A.locals&&E.A.locals;class M{mode="kalign";currentFunc=null;currentFuncCall=null}async function x(e,t){return new Promise(async(n,d)=>{try{const m=e.col?.dataFrame??i.shell.t;if(!m)return void d(new l.Ap(s.divText("MSA requires a dataset with a macromolecule column.")));const p=e.col??m.columns.bySemType(o.SEMTYPE.MACROMOLECULE);if(!p)return void d(new l.Ap(s.divText("MSA requires a dataset with a macromolecule column.")));const g=new M;let f=p;const y=s.input.column("Sequence",{table:m,value:p,onValueChanged:async e=>{if(!e||e.semType!==o.SEMTYPE.MACROMOLECULE)return q.disabled=!0,await o.delay(0),void(y.value=f);f=e,q.disabled=!1,await F(e)},filter:e=>e.semType===o.SEMTYPE.MACROMOLECULE});y.setTooltip("Sequences column to use for alignment");const b=s.input.column("Clusters",{table:m,value:e.clustersCol});b.nullable=!0;const w=s.input.bool("Selected Rows Only",{value:!1}),v=s.input.float("Gap open",{value:e?.kalign?.gapOpen});v.setTooltip("Gap opening penalty at group-to-group alignment");const C=s.input.float("Gap extend",{value:e?.kalign?.gapExtend});C.setTooltip("Gap extension penalty to skip the alignment");const A=s.input.float("Terminal gap",{value:e?.kalign?.terminalGap});A.setTooltip("Penalty for opening a gap at the beginning or end of the sequence");const T=s.p(`Kalign version: ${u.b9}`,"kalign-version"),E=s.inputs([v,C,A]);E.hidden=!0;const S=s.button("Alignment parameters",()=>{E.hidden=!E.hidden,[v,C,A].forEach(e=>{e.root.style.removeProperty("max-width"),e.captionLabel.style.removeProperty("max-width")})},"Adjust alignment parameters such as penalties for opening and extending gaps");S.classList.add("msa-params-button"),S.prepend(s.icons.settings(()=>null,"Settings"));const x=[E,S,T],L=o.Func.find({meta:{role:u.W_}});L.sort((e,t)=>{const n="true"===e.options.defaultAlignment?1:0;return("true"===t.options.defaultAlignment?1:0)-n});const I=s.input.choice("Engine",{value:L.length>0?L[0].friendlyName:"",items:L.map(e=>e.friendlyName)}),_=s.div("",{style:{fontSize:"12px",opacity:"0.7",marginBottom:"6px"}}),N=s.div(),R=s.button("Alignment parameters",()=>{N.hidden=!N.hidden},"Adjust engine-specific alignment parameters");R.classList.add("msa-params-button"),R.prepend(s.icons.settings(()=>null,"Settings"));const $=s.input.bool("Include HELM",{value:!0});$.setTooltip("Also add the aligned HELM column alongside the converted notation"),$.root.style.display="none";const O=[I.root,_,R,N,$.root];async function H(){N.innerHTML="",g.currentFuncCall=null;const e=I.value;if(g.currentFunc=L.find(t=>t.friendlyName===e)??null,_.textContent=g.currentFunc?.description??"",!g.currentFunc)return;g.currentFuncCall=g.currentFunc.prepare({});const t=await g.currentFuncCall.buildEditor(N);t.length>0&&"column"===t[0].inputType&&(t[0].root.style.display="none")}function D(e){g.mode=e;for(const t of x)t.style.display="kalign"===e?"":"none";for(const t of O)t.style.display="engine"===e?"":"none"}async function F(e){try{if(e.semType!==o.SEMTYPE.MACROMOLECULE)return;const n=(0,c.l)(e,e.name,t,[r.Hi.FASTA,r.Hi.SEPARATOR],[r.YI.DNA,r.YI.RNA,r.YI.PT])[0],s=(0,c.l)(e,e.name,t,[r.Hi.HELM],[])[0],l=(0,c.l)(e,e.name,t,[r.Hi.SEPARATOR,r.Hi.CUSTOM,r.Hi.BILN],[r.YI.UN])[0];if(n)D("kalign"),v.value=null,C.value=null,A.value=null;else if(s||l){if(0===L.length)return i.shell.warning("No MSA engines found for non-canonical sequences."),void D("kalign");D("engine"),await H();const t=e.temp?.[a.j.notationProvider],n=t?t.constructor:null,o=!0===n?.implementsFromHelm;$.root.style.display=o?"":"none"}else D("kalign")}catch(e){const t=e instanceof Error?e.message:e.toString();i.shell.error(t),h._package.logger.error(t)}}async function k(){const e=y.value;if(!e||e.semType!==o.SEMTYPE.MACROMOLECULE)throw new Error("Chosen column must be of Macromolecule semantic type");return"kalign"===g.mode?G(e,m):B(e,m)}async function G(e,n){const i=n.columns.getUnusedName(`msa(${e.name})`),o=t.getSeqHandler(e),s=o.isFasta()?e:o.convert(r.Hi.FASTA);return(0,l.eE)(n,s,!1,i,b.value,v.value??void 0,C.value??void 0,A.value??void 0,w.value)}async function B(e,n){if(!g.currentFunc||!g.currentFuncCall)throw new Error("No MSA engine selected");const i=t.getSeqHandler(e);let s;s=i.isHelm()?e:(i.isSeparator()&&(i.alphabet,r.YI.UN),i.convert(r.Hi.HELM));const c=g.currentFunc,u=c.inputs[0].name,h={};for(let e=1;e<c.inputs.length;e++){const t=c.inputs[e].name;h[t]=g.currentFuncCall.inputs[t]}const d=await async function(e,t,n,i,s,a,c){const u=i.length;s??=o.Column.string("Clusters",u).init("0"),s.type!==o.COLUMN_TYPE.STRING&&(s=s.convertTo(o.TYPE.STRING));const h=s.categories,d=s.getRawData(),m=new Array(h.length);if(a){const e=c.selection;if(0===e.trueCount)throw new Error("No selected rows in the table.");for(let t=-1;-1!==(t=e.findNext(t,!0));)(m[d[t]]??=[]).push(t)}else for(let e=0;e<u;e++)(m[d[e]]??=[]).push(e);(0,l.aZ)(m,h);const p=c.columns.getUnusedName(`msa(${i.name})`),g=new Array(u).fill("");let f=null;for(const s of m){if(!s||0===s.length)continue;const r=s.map(e=>i.get(e)),a=o.Column.fromStrings("seq",r);P(i,a),o.DataFrame.fromColumns([a]);const l=e.prepare({[t]:a,...n});await l.call();const c=l.getOutputParamValue();f=c;for(let e=0;e<s.length;e++)g[s[e]]=c.get(e)??""}const y=o.Column.fromStrings(p,g);if(f){y.meta.units=f.meta.units,y.semType=f.semType;for(const e of[r.gp.alphabet,r.gp.separator,r.gp.alphabetIsMultichar]){const t=f.getTag(e);t&&y.setTag(e,t)}}return y}(c,u,h,s,b.value,w.value,n),m=e.temp?.[a.j.notationProvider],p=m?m.constructor:null;if(p?.implementsFromHelm){const t=n.columns.getUnusedName(`msa(${e.name})`),i=o.Column.string(t,d.length);return i.init(e=>{const t=d.get(e);if(!t)return"";try{return p.convertFromHelm(t,{})}catch{return""}}),i.semType=o.SEMTYPE.MACROMOLECULE,i.meta.units=r.Hi.CUSTOM,i.setTag(r.gp.aligned,"SEQ.MSA"),i.setTag(r.gp.alphabet,r.YI.UN),$.value&&n.columns.add(d),i}return d}async function V(){if(!e.engine||"engine"!==g.mode)return;const t=L.find(t=>t.name===e.engine||t.friendlyName===e.engine);if(t&&(I.value=t.friendlyName,await H(),e.engineParams&&g.currentFuncCall))for(const[t,n]of Object.entries(e.engineParams))g.currentFuncCall.inputs[t]=n}I.onChanged.subscribe(()=>H());const U=s.dialog("MSA").add(y).add(b).add(I).add(_).add(R).add(N).add($).add(E).add(S).add(T).add(w).onOK(async()=>{const e=o.TaskBarProgressIndicator.create("Performing MSA...");try{const e=await k();m.columns.add(e),await i.data.detectSemanticTypes(m),e.meta.units!==r.Hi.HELM&&e.setTag(r.gp.aligned,"SEQ.MSA"),n(e)}catch(e){d(e)}finally{e.close()}}),q=U.getButton("OK");if(D("kalign"),y.fireChanged(),e.col){await F(e.col),await V();const W=o.TaskBarProgressIndicator.create("Performing MSA...");try{const Y=await k();m.columns.add(Y),await i.data.detectSemanticTypes(m),Y.meta.units!==r.Hi.HELM&&Y.setTag(r.gp.aligned,"SEQ.MSA"),n(Y)}catch(j){d(j)}finally{W.close()}return}U.show()}catch(K){d(K)}})}function P(e,t){t.semType=e.semType,t.meta.units=e.meta.units;for(const n of[r.gp.alphabet,r.gp.separator,r.gp.alphabetIsMultichar]){const i=e.getTag(n);i&&t.setTag(n,i)}}},608(e,t,n){"use strict";n.d(t,{Ap:()=>D,aZ:()=>B,eE:()=>k});var i=n(7389),o=n(6082),s=n(1991),r=n.n(s),a=n(3516),l=n(2003);const c=Symbol("Comlink.proxy"),u=Symbol("Comlink.endpoint"),h=Symbol("Comlink.releaseProxy"),d=Symbol("Comlink.thrown"),m=e=>"object"==typeof e&&null!==e||"function"==typeof e,p=new Map([["proxy",{canHandle:e=>m(e)&&e[c],serialize(e){const{port1:t,port2:n}=new MessageChannel;return g(e,t),[n,[n]]},deserialize:e=>(e.start(),y(e))}],["throw",{canHandle:e=>m(e)&&d in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}}]]);function g(e,t=self){t.addEventListener("message",function n(i){if(!i||!i.data)return;const{id:o,type:s,path:r}=Object.assign({path:[]},i.data),a=(i.data.argumentList||[]).map(E);let l;try{const t=r.slice(0,-1).reduce((e,t)=>e[t],e),n=r.reduce((e,t)=>e[t],e);switch(s){case"GET":l=n;break;case"SET":t[r.slice(-1)[0]]=E(i.data.value),l=!0;break;case"APPLY":l=n.apply(t,a);break;case"CONSTRUCT":l=function(e){return Object.assign(e,{[c]:!0})}(new n(...a));break;case"ENDPOINT":{const{port1:t,port2:n}=new MessageChannel;g(e,n),l=function(e,t){return A.set(e,t),e}(t,[t])}break;case"RELEASE":l=void 0;break;default:return}}catch(e){l={value:e,[d]:0}}Promise.resolve(l).catch(e=>({value:e,[d]:0})).then(e=>{const[i,r]=T(e);t.postMessage(Object.assign(Object.assign({},i),{id:o}),r),"RELEASE"===s&&(t.removeEventListener("message",n),f(t))})}),t.start&&t.start()}function f(e){(function(e){return"MessagePort"===e.constructor.name})(e)&&e.close()}function y(e,t){return w(e,[],t)}function b(e){if(e)throw new Error("Proxy has been released and is not useable")}function w(e,t=[],n=function(){}){let i=!1;const o=new Proxy(n,{get(n,s){if(b(i),s===h)return()=>S(e,{type:"RELEASE",path:t.map(e=>e.toString())}).then(()=>{f(e),i=!0});if("then"===s){if(0===t.length)return{then:()=>o};const n=S(e,{type:"GET",path:t.map(e=>e.toString())}).then(E);return n.then.bind(n)}return w(e,[...t,s])},set(n,o,s){b(i);const[r,a]=T(s);return S(e,{type:"SET",path:[...t,o].map(e=>e.toString()),value:r},a).then(E)},apply(n,o,s){b(i);const r=t[t.length-1];if(r===u)return S(e,{type:"ENDPOINT"}).then(E);if("bind"===r)return w(e,t.slice(0,-1));const[a,l]=C(s);return S(e,{type:"APPLY",path:t.map(e=>e.toString()),argumentList:a},l).then(E)},construct(n,o){b(i);const[s,r]=C(o);return S(e,{type:"CONSTRUCT",path:t.map(e=>e.toString()),argumentList:s},r).then(E)}});return o}function v(e){return Array.prototype.concat.apply([],e)}function C(e){const t=e.map(T);return[t.map(e=>e[0]),v(t.map(e=>e[1]))]}const A=new WeakMap;function T(e){for(const[t,n]of p)if(n.canHandle(e)){const[i,o]=n.serialize(e);return[{type:"HANDLER",name:t,value:i},o]}return[{type:"RAW",value:e},A.get(e)||[]]}function E(e){switch(e.type){case"HANDLER":return p.get(e.name).deserialize(e.value);case"RAW":return e.value}}function S(e,t,n){return new Promise(i=>{const o=new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-");e.addEventListener("message",function t(n){!n.data||!n.data.id||n.data.id!==o||(e.removeEventListener("message",t),i(n.data))}),e.start&&e.start(),e.postMessage(Object.assign({id:o},t),n)})}const M="KGZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO2NvbnN0ICQ9U3ltYm9sKCJDb21saW5rLnByb3h5IiksQT1TeW1ib2woIkNvbWxpbmsuZW5kcG9pbnQiKSxSPVN5bWJvbCgiQ29tbGluay5yZWxlYXNlUHJveHkiKSx5PVN5bWJvbCgiQ29tbGluay50aHJvd24iKSxfPWU9PnR5cGVvZiBlPT0ib2JqZWN0IiYmZSE9PW51bGx8fHR5cGVvZiBlPT0iZnVuY3Rpb24iLEw9e2NhbkhhbmRsZTplPT5fKGUpJiZlWyRdLHNlcmlhbGl6ZShlKXtjb25zdHtwb3J0MTpyLHBvcnQyOml9PW5ldyBNZXNzYWdlQ2hhbm5lbDtyZXR1cm4gdyhlLHIpLFtpLFtpXV19LGRlc2VyaWFsaXplKGUpe3JldHVybiBlLnN0YXJ0KCksQyhlKX19LE89e2NhbkhhbmRsZTplPT5fKGUpJiZ5IGluIGUsc2VyaWFsaXplKHt2YWx1ZTplfSl7bGV0IHI7cmV0dXJuIGUgaW5zdGFuY2VvZiBFcnJvcj9yPXtpc0Vycm9yOiEwLHZhbHVlOnttZXNzYWdlOmUubWVzc2FnZSxuYW1lOmUubmFtZSxzdGFjazplLnN0YWNrfX06cj17aXNFcnJvcjohMSx2YWx1ZTplfSxbcixbXV19LGRlc2VyaWFsaXplKGUpe3Rocm93IGUuaXNFcnJvcj9PYmplY3QuYXNzaWduKG5ldyBFcnJvcihlLnZhbHVlLm1lc3NhZ2UpLGUudmFsdWUpOmUudmFsdWV9fSxFPW5ldyBNYXAoW1sicHJveHkiLExdLFsidGhyb3ciLE9dXSk7ZnVuY3Rpb24gdyhlLHI9c2VsZil7ci5hZGRFdmVudExpc3RlbmVyKCJtZXNzYWdlIixmdW5jdGlvbiBpKHMpe2lmKCFzfHwhcy5kYXRhKXJldHVybjtjb25zdHtpZDpvLHR5cGU6YSxwYXRoOm59PU9iamVjdC5hc3NpZ24oe3BhdGg6W119LHMuZGF0YSksYz0ocy5kYXRhLmFyZ3VtZW50TGlzdHx8W10pLm1hcChtKTtsZXQgbDt0cnl7Y29uc3QgdT1uLnNsaWNlKDAsLTEpLnJlZHVjZSgoZCxwKT0+ZFtwXSxlKSxmPW4ucmVkdWNlKChkLHApPT5kW3BdLGUpO3N3aXRjaChhKXtjYXNlIkdFVCI6bD1mO2JyZWFrO2Nhc2UiU0VUIjp1W24uc2xpY2UoLTEpWzBdXT1tKHMuZGF0YS52YWx1ZSksbD0hMDticmVhaztjYXNlIkFQUExZIjpsPWYuYXBwbHkodSxjKTticmVhaztjYXNlIkNPTlNUUlVDVCI6e2NvbnN0IGQ9bmV3IGYoLi4uYyk7bD16KGQpfWJyZWFrO2Nhc2UiRU5EUE9JTlQiOntjb25zdHtwb3J0MTpkLHBvcnQyOnB9PW5ldyBNZXNzYWdlQ2hhbm5lbDt3KGUscCksbD1OKGQsW2RdKX1icmVhaztjYXNlIlJFTEVBU0UiOmw9dm9pZCAwO2JyZWFrO2RlZmF1bHQ6cmV0dXJufX1jYXRjaCh1KXtsPXt2YWx1ZTp1LFt5XTowfX1Qcm9taXNlLnJlc29sdmUobCkuY2F0Y2godT0+KHt2YWx1ZTp1LFt5XTowfSkpLnRoZW4odT0+e2NvbnN0W2YsZF09Uyh1KTtyLnBvc3RNZXNzYWdlKE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxmKSx7aWQ6b30pLGQpLGE9PT0iUkVMRUFTRSImJihyLnJlbW92ZUV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLGkpLE0ocikpfSl9KSxyLnN0YXJ0JiZyLnN0YXJ0KCl9ZnVuY3Rpb24gVChlKXtyZXR1cm4gZS5jb25zdHJ1Y3Rvci5uYW1lPT09Ik1lc3NhZ2VQb3J0In1mdW5jdGlvbiBNKGUpe1QoZSkmJmUuY2xvc2UoKX1mdW5jdGlvbiBDKGUscil7cmV0dXJuIGIoZSxbXSxyKX1mdW5jdGlvbiBoKGUpe2lmKGUpdGhyb3cgbmV3IEVycm9yKCJQcm94eSBoYXMgYmVlbiByZWxlYXNlZCBhbmQgaXMgbm90IHVzZWFibGUiKX1mdW5jdGlvbiBiKGUscj1bXSxpPWZ1bmN0aW9uKCl7fSl7bGV0IHM9ITE7Y29uc3Qgbz1uZXcgUHJveHkoaSx7Z2V0KGEsbil7aWYoaChzKSxuPT09UilyZXR1cm4oKT0+ZyhlLHt0eXBlOiJSRUxFQVNFIixwYXRoOnIubWFwKGM9PmMudG9TdHJpbmcoKSl9KS50aGVuKCgpPT57TShlKSxzPSEwfSk7aWYobj09PSJ0aGVuIil7aWYoci5sZW5ndGg9PT0wKXJldHVybnt0aGVuOigpPT5vfTtjb25zdCBjPWcoZSx7dHlwZToiR0VUIixwYXRoOnIubWFwKGw9PmwudG9TdHJpbmcoKSl9KS50aGVuKG0pO3JldHVybiBjLnRoZW4uYmluZChjKX1yZXR1cm4gYihlLFsuLi5yLG5dKX0sc2V0KGEsbixjKXtoKHMpO2NvbnN0W2wsdV09UyhjKTtyZXR1cm4gZyhlLHt0eXBlOiJTRVQiLHBhdGg6Wy4uLnIsbl0ubWFwKGY9PmYudG9TdHJpbmcoKSksdmFsdWU6bH0sdSkudGhlbihtKX0sYXBwbHkoYSxuLGMpe2gocyk7Y29uc3QgbD1yW3IubGVuZ3RoLTFdO2lmKGw9PT1BKXJldHVybiBnKGUse3R5cGU6IkVORFBPSU5UIn0pLnRoZW4obSk7aWYobD09PSJiaW5kIilyZXR1cm4gYihlLHIuc2xpY2UoMCwtMSkpO2NvbnN0W3UsZl09RihjKTtyZXR1cm4gZyhlLHt0eXBlOiJBUFBMWSIscGF0aDpyLm1hcChkPT5kLnRvU3RyaW5nKCkpLGFyZ3VtZW50TGlzdDp1fSxmKS50aGVuKG0pfSxjb25zdHJ1Y3QoYSxuKXtoKHMpO2NvbnN0W2MsbF09RihuKTtyZXR1cm4gZyhlLHt0eXBlOiJDT05TVFJVQ1QiLHBhdGg6ci5tYXAodT0+dS50b1N0cmluZygpKSxhcmd1bWVudExpc3Q6Y30sbCkudGhlbihtKX19KTtyZXR1cm4gb31mdW5jdGlvbiBEKGUpe3JldHVybiBBcnJheS5wcm90b3R5cGUuY29uY2F0LmFwcGx5KFtdLGUpfWZ1bmN0aW9uIEYoZSl7Y29uc3Qgcj1lLm1hcChTKTtyZXR1cm5bci5tYXAoaT0+aVswXSksRChyLm1hcChpPT5pWzFdKSldfWNvbnN0IFA9bmV3IFdlYWtNYXA7ZnVuY3Rpb24gTihlLHIpe3JldHVybiBQLnNldChlLHIpLGV9ZnVuY3Rpb24geihlKXtyZXR1cm4gT2JqZWN0LmFzc2lnbihlLHtbJF06ITB9KX1mdW5jdGlvbiBTKGUpe2Zvcihjb25zdFtyLGldb2YgRSlpZihpLmNhbkhhbmRsZShlKSl7Y29uc3RbcyxvXT1pLnNlcmlhbGl6ZShlKTtyZXR1cm5be3R5cGU6IkhBTkRMRVIiLG5hbWU6cix2YWx1ZTpzfSxvXX1yZXR1cm5be3R5cGU6IlJBVyIsdmFsdWU6ZX0sUC5nZXQoZSl8fFtdXX1mdW5jdGlvbiBtKGUpe3N3aXRjaChlLnR5cGUpe2Nhc2UiSEFORExFUiI6cmV0dXJuIEUuZ2V0KGUubmFtZSkuZGVzZXJpYWxpemUoZS52YWx1ZSk7Y2FzZSJSQVciOnJldHVybiBlLnZhbHVlfX1mdW5jdGlvbiBnKGUscixpKXtyZXR1cm4gbmV3IFByb21pc2Uocz0+e2NvbnN0IG89VSgpO2UuYWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsZnVuY3Rpb24gYShuKXshbi5kYXRhfHwhbi5kYXRhLmlkfHxuLmRhdGEuaWQhPT1vfHwoZS5yZW1vdmVFdmVudExpc3RlbmVyKCJtZXNzYWdlIixhKSxzKG4uZGF0YSkpfSksZS5zdGFydCYmZS5zdGFydCgpLGUucG9zdE1lc3NhZ2UoT2JqZWN0LmFzc2lnbih7aWQ6b30sciksaSl9KX1mdW5jdGlvbiBVKCl7cmV0dXJuIG5ldyBBcnJheSg0KS5maWxsKDApLm1hcCgoKT0+TWF0aC5mbG9vcihNYXRoLnJhbmRvbSgpKk51bWJlci5NQVhfU0FGRV9JTlRFR0VSKS50b1N0cmluZygxNikpLmpvaW4oIi0iKX1jb25zdCBXPWFzeW5jKCk9PldlYkFzc2VtYmx5LnZhbGlkYXRlKG5ldyBVaW50OEFycmF5KFswLDk3LDExNSwxMDksMSwwLDAsMCwxLDUsMSw5NiwwLDEsMTIzLDMsMiwxLDAsMTAsMTAsMSw4LDAsNjUsMCwyNTMsMTUsMjUzLDk4LDExXSkpLGs9ImVhZ2VyIix4PSJsYXp5IixqPXtzc3c6WyJzaW1kIl0sbWluaW1hcDI6WyJzaW1kIl19LHQ9e3Rvb2xzOltdLGNvbmZpZzp7fSxmaWxlczpbXSxiYXNlOnt9LGZzOnt9LGFzeW5jIGluaXQoKXtpZih0LnRvb2xzLmxlbmd0aD09PTApdGhyb3ciRXhwZWN0aW5nIGF0IGxlYXN0IDEgdG9vbC4iO2lmKG5ldyBTZXQodC50b29scy5tYXAocj0+YCR7ci50b29sfS8ke3IucHJvZ3JhbXx8ci50b29sfWApKS5zaXplIT09dC50b29scy5sZW5ndGgpdGhyb3ciRm91bmQgZHVwbGljYXRlIHRvb2xzOyBjYW4gb25seSBoYXZlIGVhY2ggdG9vbC9wcm9ncmFtIGNvbWJpbmF0aW9uIGF0IG1vc3Qgb25jZS4iO2lmKHQuYmFzZT10LnRvb2xzLmZpbmQocj0+ci5yZWluaXQhPT0hMCksIXQuYmFzZSl0aHJvdyJDb3VsZCBub3QgZmluZCBhIHRvb2wgd2l0aCBgcmVpbml0OiBmYWxzZWAgdG8gdXNlIGFzIHRoZSBiYXNlIG1vZHVsZS4gVG8gZml4IHRoaXMgaXNzdWUsIGluY2x1ZGUgdGhlIHRvb2wgYGJhc2UvMS4wLjBgIHdoZW4gaW5pdGlhbGl6aW5nIEFpb2xpLiI7cmV0dXJuIHQuYmFzZS5pc0Jhc2VNb2R1bGU9ITAsYXdhaXQgdGhpcy5fc2V0dXAodC5iYXNlKSxhd2FpdCB0aGlzLl9pbml0TW9kdWxlcygpLHQuX2xvZygiUmVhZHkiKSwhMH0sYXN5bmMgX2luaXRNb2R1bGVzKCl7YXdhaXQgUHJvbWlzZS5hbGwodC50b29scy5tYXAodGhpcy5fc2V0dXApKSxhd2FpdCB0aGlzLl9zZXR1cEZTKCl9LG1vdW50KGU9W10pe2NvbnN0IHI9YCR7dC5jb25maWcuZGlyU2hhcmVkfSR7dC5jb25maWcuZGlyRGF0YX1gLGk9YCR7dC5jb25maWcuZGlyU2hhcmVkfSR7dC5jb25maWcuZGlyTW91bnRlZH1gO2xldCBzPVtdLG89W10sYT1bXTshQXJyYXkuaXNBcnJheShlKSYmIShlIGluc3RhbmNlb2YgRmlsZUxpc3QpJiYoZT1bZV0pLHQuX2xvZyhgTW91bnRpbmcgJHtlLmxlbmd0aH0gZmlsZXNgKTtmb3IobGV0IG4gb2YgZSl7aWYobiBpbnN0YW5jZW9mIEZpbGV8fChuPT1udWxsP3ZvaWQgMDpuLmRhdGEpaW5zdGFuY2VvZiBCbG9iJiZuLm5hbWV8fHR5cGVvZihuPT1udWxsP3ZvaWQgMDpuLmRhdGEpPT0ic3RyaW5nIiYmbi5uYW1lKXR5cGVvZihuPT1udWxsP3ZvaWQgMDpuLmRhdGEpPT0ic3RyaW5nIiYmKG4uZGF0YT1uZXcgQmxvYihbbi5kYXRhXSx7dHlwZToidGV4dC9wbGFpbiJ9KSkscy5wdXNoKG4pO2Vsc2UgaWYobi5uYW1lJiZuLnVybClvLnB1c2gobik7ZWxzZSBpZih0eXBlb2Ygbj09InN0cmluZyImJm4uc3RhcnRzV2l0aCgiaHR0cCIpKW49e3VybDpuLG5hbWU6bi5zcGxpdCgiLy8iKS5wb3AoKS5yZXBsYWNlKC9cLy9nLCItIil9LG8ucHVzaChuKTtlbHNlIHRocm93J0Nhbm5vdCBtb3VudCBmaWxlKHMpIHNwZWNpZmllZC4gTXVzdCBiZSBhIEZpbGUsIEJsb2IsIGEgVVJMIHN0cmluZywgb3IgeyBuYW1lOiAiZmlsZS50eHQiLCBkYXRhOiAic3RyaW5nIiB9Lic7YS5wdXNoKG4ubmFtZSl9dHJ5e3QuZnMudW5tb3VudChpKX1jYXRjaHt9Zm9yKGxldCBuIG9mIG8pdC5mcy5jcmVhdGVMYXp5RmlsZShyLG4ubmFtZSxuLnVybCwhMCwhMCk7cmV0dXJuIHQuZmlsZXM9dC5maWxlcy5jb25jYXQocyksdC5iYXNlLm1vZHVsZS5GUy5tb3VudCh0LmJhc2UubW9kdWxlLldPUktFUkZTLHtmaWxlczp0LmZpbGVzLmZpbHRlcihuPT5uIGluc3RhbmNlb2YgRmlsZSksYmxvYnM6dC5maWxlcy5maWx0ZXIobj0+KG49PW51bGw/dm9pZCAwOm4uZGF0YSlpbnN0YW5jZW9mIEJsb2IpfSxpKSxzLm1hcChuPT57Y29uc3QgYz1gJHtpfS8ke24ubmFtZX1gLGw9YCR7cn0vJHtuLm5hbWV9YDt0cnl7dC5mcy51bmxpbmsobCl9Y2F0Y2h7fXQuX2xvZyhgQ3JlYXRpbmcgc3ltbGluazogJHtsfSAtLT4gJHtjfWApLHQuZnMuc3ltbGluayhjLGwpfSksYS5tYXAobj0+YCR7cn0vJHtufWApfSxhc3luYyBleGVjKGUscj1udWxsKXtpZih0Ll9sb2coYEV4ZWN1dGluZyAlYyR7ZX0lYyBhcmdzPSR7cn1gLCJjb2xvcjpkYXJrYmx1ZTsgZm9udC13ZWlnaHQ6Ym9sZCIsIiIpLCFlKXRocm93IkV4cGVjdGluZyBhIGNvbW1hbmQiO2xldCBpPWU7cj09bnVsbCYmKHI9ZS5zcGxpdCgiICIpLGk9ci5zaGlmdCgpKTtjb25zdCBzPXQudG9vbHMuZmluZChhPT57dmFyIGM7bGV0IG49aTtyZXR1cm4oKGM9YT09bnVsbD92b2lkIDA6YS5mZWF0dXJlcyk9PW51bGw/dm9pZCAwOmMuc2ltZCk9PT0hMCYmKG49YCR7bn0tc2ltZGApLGEucHJvZ3JhbT09bn0pO2lmKHM9PW51bGwpdGhyb3dgUHJvZ3JhbSAke2l9IG5vdCBmb3VuZC5gO3Muc3Rkb3V0PSIiLHMuc3RkZXJyPSIiLHMubG9hZGluZz09eCYmKHMubG9hZGluZz1rLGF3YWl0IHRoaXMuX2luaXRNb2R1bGVzKCkpO3RyeXtzLm1vZHVsZS5jYWxsTWFpbihyKX1jYXRjaChhKXtjb25zb2xlLmVycm9yKGEpfXRyeXtzLm1vZHVsZS5GUy5jbG9zZShzLm1vZHVsZS5GUy5zdHJlYW1zWzFdKSxzLm1vZHVsZS5GUy5jbG9zZShzLm1vZHVsZS5GUy5zdHJlYW1zWzJdKX1jYXRjaHt9cy5tb2R1bGUuRlMuc3RyZWFtc1sxXT1zLm1vZHVsZS5GUy5vcGVuKCIvZGV2L3N0ZG91dCIsInciKSxzLm1vZHVsZS5GUy5zdHJlYW1zWzJdPXMubW9kdWxlLkZTLm9wZW4oIi9kZXYvc3RkZXJyIiwidyIpO2xldCBvPXtzdGRvdXQ6cy5zdGRvdXQsc3RkZXJyOnMuc3RkZXJyfTtyZXR1cm4gdC5jb25maWcucHJpbnRJbnRlcmxlYXZlZCYmKG89cy5zdGRvdXQpLHMucmVpbml0PT09ITAmJmF3YWl0IHRoaXMucmVpbml0KHMudG9vbCksb30sY2F0KGUpe3JldHVybiB0Ll9maWxlb3AoImNhdCIsZSl9LGxzKGUpe3JldHVybiB0Ll9maWxlb3AoImxzIixlKX0sZG93bmxvYWQoZSl7cmV0dXJuIHQuX2ZpbGVvcCgiZG93bmxvYWQiLGUpfSxwd2QoKXtyZXR1cm4gdC5mcy5jd2QoKX0sY2QoZSl7Zm9yKGxldCByIG9mIHQudG9vbHMpIXIubW9kdWxlfHxyLm1vZHVsZS5GUy5jaGRpcihlKX0sbWtkaXIoZSl7cmV0dXJuIHQuZnMubWtkaXIoZSksITB9LHJlYWQoe3BhdGg6ZSxsZW5ndGg6cixmbGFnOmk9InIiLG9mZnNldDpzPTAscG9zaXRpb246bz0wfSl7Y29uc3QgYT10LmZzLm9wZW4oZSxpKSxuPW5ldyBVaW50OEFycmF5KHIpO3JldHVybiB0LmZzLnJlYWQoYSxuLHMscixvKSx0LmZzLmNsb3NlKGEpLG59LHdyaXRlKHtwYXRoOmUsYnVmZmVyOnIsZmxhZzppPSJ3KyIsb2Zmc2V0OnM9MCxwb3NpdGlvbjpvPTB9KXtjb25zdCBhPXQuZnMub3BlbihlLGkpO3QuZnMud3JpdGUoYSxyLHMsci5sZW5ndGgsbyksdC5mcy5jbG9zZShhKX0sYXN5bmMgcmVpbml0KGUpe2NvbnN0IHI9dC50b29scy5maW5kKHM9PnMudG9vbD09ZSksaT10LmJhc2UubW9kdWxlLkZTLmN3ZCgpO09iamVjdC5hc3NpZ24ocixyLmNvbmZpZyksci5yZWFkeT0hMSxhd2FpdCB0aGlzLmluaXQoKSxyLmlzQmFzZU1vZHVsZSYmdGhpcy5tb3VudCgpLHRoaXMuY2QoaSl9LF9zdGRpblR4dDoiIixfc3RkaW5QdHI6MCxnZXQgc3RkaW4oKXtyZXR1cm4gdC5fc3RkaW5UeHR9LHNldCBzdGRpbihlPSIiKXt0Ll9sb2coYFNldHRpbmcgc3RkaW4gdG8gJWMke2V9JWNgLCJjb2xvcjpkYXJrYmx1ZSIsIiIpLHQuX3N0ZGluVHh0PWUsdC5fc3RkaW5QdHI9MH0sYXN5bmMgX3NldHVwKGUpe2lmKGUucmVhZHkpcmV0dXJuO2lmKHQuX2xvZyhgU2V0dGluZyB1cCAke2UudG9vbH0gKGJhc2UgPSAke2UuaXNCYXNlTW9kdWxlPT09ITB9KS4uLmApLGUuY29uZmlnPU9iamVjdC5hc3NpZ24oe30sZSksZS51cmxQcmVmaXh8fChlLnVybFByZWZpeD1gJHt0LmNvbmZpZy51cmxDRE59LyR7ZS50b29sfS8ke2UudmVyc2lvbn1gKSxlLnByb2dyYW18fChlLnByb2dyYW09ZS50b29sKSxlLmZlYXR1cmVzfHwoZS5mZWF0dXJlcz17fSwoaltlLnByb2dyYW1dfHxbXSkuaW5jbHVkZXMoInNpbWQiKSYmKGF3YWl0IFcoKT8oZS5wcm9ncmFtKz0iLXNpbWQiLGUuZmVhdHVyZXMuc2ltZD0hMCk6dC5fbG9nKGBXZWJBc3NlbWJseSBTSU1EIGlzIG5vdCBzdXBwb3J0ZWQgaW4gdGhpcyBicm93c2VyOyB3aWxsIGxvYWQgbm9uLVNJTUQgdmVyc2lvbiBvZiAke2UucHJvZ3JhbX0uYCkpKSxlLmlzQmFzZU1vZHVsZSYmKGUubG9hZGluZz1rKSxlLmxvYWRpbmc9PT14KXt0Ll9sb2coYFdpbGwgbGF6eS1sb2FkICR7ZS50b29sfTsgc2tpcHBpbmcgaW5pdGlhbGl6YXRpb24uYCk7cmV0dXJufXNlbGYuaW1wb3J0U2NyaXB0cyhgJHtlLnVybFByZWZpeH0vJHtlLnByb2dyYW19LmpzYCksZS5tb2R1bGU9YXdhaXQgTW9kdWxlKHt0aGlzUHJvZ3JhbTplLnByb2dyYW0sbG9jYXRlRmlsZTooaSxzKT0+YCR7ZS51cmxQcmVmaXh9LyR7aX1gLHN0ZGluOigpPT50Ll9zdGRpblB0cjx0LnN0ZGluLmxlbmd0aD90LnN0ZGluLmNoYXJDb2RlQXQodC5fc3RkaW5QdHIrKyk6KHQuc3RkaW49IiIsbnVsbCkscHJpbnQ6aT0+e3QuY29uZmlnLnByaW50U3RyZWFtP3Bvc3RNZXNzYWdlKHt0eXBlOiJiaW93YXNtIix2YWx1ZTp7c3Rkb3V0Oml9fSk6ZS5zdGRvdXQrPWkrYApgfSxwcmludEVycjppPT57Y29uc3Qgcz10LmNvbmZpZy5wcmludEludGVybGVhdmVkPyJzdGRvdXQiOiJzdGRlcnIiO3QuY29uZmlnLnByaW50U3RyZWFtP3Bvc3RNZXNzYWdlKHt0eXBlOiJiaW93YXNtIix2YWx1ZTp7W3NdOml9fSk6ZVtzXSs9aStgCmB9fSk7Y29uc3Qgcj1lLm1vZHVsZS5GUztlLmlzQmFzZU1vZHVsZT8odC5fbG9nKGBTZXR0aW5nIHVwICR7ZS50b29sfSB3aXRoIGJhc2UgbW9kdWxlIGZpbGVzeXN0ZW0uLi5gKSxyLm1rZGlyKHQuY29uZmlnLmRpclNoYXJlZCw1MTEpLHIubWtkaXIoYCR7dC5jb25maWcuZGlyU2hhcmVkfS8ke3QuY29uZmlnLmRpckRhdGF9YCw1MTEpLHIubWtkaXIoYCR7dC5jb25maWcuZGlyU2hhcmVkfS8ke3QuY29uZmlnLmRpck1vdW50ZWR9YCw1MTEpLHIuY2hkaXIoYCR7dC5jb25maWcuZGlyU2hhcmVkfS8ke3QuY29uZmlnLmRpckRhdGF9YCksdC5mcz1yKToodC5fbG9nKGBTZXR0aW5nIHVwICR7ZS50b29sfSB3aXRoIGZpbGVzeXN0ZW0uLi5gKSxyLm1rZGlyKHQuY29uZmlnLmRpclNoYXJlZCksci5tb3VudChlLm1vZHVsZS5QUk9YWUZTLHtyb290OnQuY29uZmlnLmRpclNoYXJlZCxmczp0LmZzfSx0LmNvbmZpZy5kaXJTaGFyZWQpLHIuY2hkaXIodC5mcy5jd2QoKSkpLGUuc3Rkb3V0PSIiLGUuc3RkZXJyPSIiLGUucmVhZHk9ITB9LGFzeW5jIF9zZXR1cEZTKCl7Y29uc3QgZT10LmZzO2ZvcihsZXQgciBvZiB0LnRvb2xzKXtpZighci5yZWFkeSljb250aW51ZTtjb25zdCBpPXIubW9kdWxlLkZTLHM9YC8ke3IudG9vbH1gLG89YCR7dC5jb25maWcuZGlyU2hhcmVkfSR7c31gOyFpLmFuYWx5emVQYXRoKHMpLmV4aXN0c3x8ZS5hbmFseXplUGF0aChvKS5leGlzdHN8fCh0Ll9sb2coYE1vdW50aW5nICR7c30gb250byAke3QuYmFzZS50b29sfSBmaWxlc3lzdGVtIGF0ICR7b31gKSxlLm1rZGlyKG8pLGUubW91bnQodC5iYXNlLm1vZHVsZS5QUk9YWUZTLHtyb290OnMsZnM6aX0sbykpfX0sX2ZpbGVvcChlLHIpe3QuX2xvZyhgUnVubmluZyAke2V9ICR7cn1gKTtjb25zdCBpPXQuZnMuYW5hbHl6ZVBhdGgocik7aWYoIWkuZXhpc3RzKXJldHVybiB0Ll9sb2coYEZpbGUgJHtyfSBub3QgZm91bmQuYCksITE7c3dpdGNoKGUpe2Nhc2UiY2F0IjpyZXR1cm4gdC5mcy5yZWFkRmlsZShyLHtlbmNvZGluZzoidXRmOCJ9KTtjYXNlImxzIjpyZXR1cm4gdC5mcy5pc0ZpbGUoaS5vYmplY3QubW9kZSk/dC5mcy5zdGF0KHIpOnQuZnMucmVhZGRpcihyKTtjYXNlImRvd25sb2FkIjpjb25zdCBzPW5ldyBCbG9iKFt0aGlzLmNhdChyKV0pO3JldHVybiBVUkwuY3JlYXRlT2JqZWN0VVJMKHMpfXJldHVybiExfSxfbG9nKGUpe2lmKCF0LmNvbmZpZy5kZWJ1ZylyZXR1cm47bGV0IHI9Wy4uLmFyZ3VtZW50c107ci5zaGlmdCgpLGNvbnNvbGUubG9nKGAlY1tXZWJXb3JrZXJdJWMgJHtlfWAsImZvbnQtd2VpZ2h0OmJvbGQiLCIiLC4uLnIpfX07dyh0KX0pKCk7Cg==",x=typeof window<"u"&&window.Blob&&new Blob([atob(M)],{type:"text/javascript;charset=utf-8"});function P(){const e=x&&(window.URL||window.webkitURL).createObjectURL(x);try{return e?new Worker(e):new Worker("data:application/javascript;base64,"+M)}finally{e&&(window.URL||window.webkitURL).revokeObjectURL(e)}}const L={urlCDN:"https://biowasm.com/cdn/v3",urlCDNStg:"https://stg.biowasm.com/cdn/v3",dirShared:"/shared",dirMounted:"/mnt",dirData:"/data",printInterleaved:!0,printStream:!1,callback:null,debug:!1,env:"prd"};class I{constructor(e,t={}){if(null==e)throw"Expecting array of tools as input to Aioli constructor.";return Array.isArray(e)||(e=[e]),t=Object.assign({},L,t),e=e.map(this._parseTool),"stg"===t.env&&(t.urlCDN=t.urlCDNStg),this.tools=e,this.config=t,null!=this.config.callback&&(this.callback=this.config.callback),delete this.config.callback,this.init()}async init(){const e=new P;this.callback&&(e.onmessage=e=>{"biowasm"===e.data.type&&this.callback(e.data.value)});const t=y(e);return t.tools=this.tools,t.config=this.config,await t.init(),t}_parseTool(e){if("string"!=typeof e)return e;const t=e.split("/");if(2!=t.length&&3!=t.length)throw"Expecting '<tool>/<version>' or '<tool>/<program>/<version>'";return{tool:t[0],program:3==t.length?t[1]:t[0],version:t[t.length-1]}}}var _=n(3629);class N{static getAvailableScales(){return Object.entries(this.scales).map(([e,t])=>e)}static getScale(e){return(0,_.vA)(!(void 0===this.scales[e]),`Scale '${e}' was not found.`),this.scales[e]}}N.scales={WimleyWhite:{"-":0,A:.17,C:-.24,D:-.07,E:-.01,F:-1.13,G:.01,H:.17,I:-.31,K:.99,L:-.56,M:-.23,N:.42,P:.45,Q:.58,R:.81,S:.13,T:.14,V:.07,W:-1.85,Y:-.94},categorial:{"-":0,A:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,K:9,L:10,M:11,N:12,P:13,Q:14,R:15,S:16,T:17,V:18,W:19,Y:20}};class R{constructor(e="categorial"){this.aa2num=N.getScale(e),this.num2aa={},Object.entries(this.aa2num).forEach(([e,t])=>this.num2aa[t]=e)}static _truncateSequence(e){let t=0,n=e.length;const i=["NH2","COOH"];if(e.startsWith(i[0])){const n=i[0].length;(0,_.vA)("-"==e[n],`Wrong sequence format: ${i[0]} without following '-' in '${e}'.`),t=n}if(e.endsWith(i[1])){const t=i[1].length+1;(0,_.vA)("-"==e[n-t],`Wrong sequence format: ${i[1]} without '-' precending in '${e}'.`),n-=t}return e.substring(t,n)}static _dropDefises(e){return e.replace(/(-)([^-]+)/g,"$2")}static clean(e){return R._dropDefises(R._truncateSequence(e))}encode(e){const t=e.length,n=new Array(t).fill(0);for(let i=0;i<t;++i){const t=e[i];(0,_.vA)(t in this.aa2num,`Unknown char '${t}' found in sequence '${e}'`),n[i]=this.encodeLettter(t)}return n}encodeLettter(e){return this.aa2num[e]}decode(e){let t="";for(let n=0;n<e.length;++n){const i=e[n];(0,_.vA)(i in this.num2aa,`Unknown code '${i}' found in vector '${e}'`),t+=this.num2aa[i]}return t}}var $=n(4139);const O="input.fa",H="result.fasta";class D extends Error{element;constructor(e,t){super(e.innerText,t),this.element=e}}function F(e){return e.reduce((e,t,n)=>e+`>sample${n+1}\n${t}\n`,"")}async function k(e,t,n=!1,i="",s=null,r,c,u,h){let d=t.toList();n&&(d=d.map(e=>R.clean(e).replace(/\-/g,"")));const m=t.length;s??=o.Column.string("Clusters",m).init("0"),s.type!=o.COLUMN_TYPE.STRING&&(s=s.convertTo(o.TYPE.STRING)),s.compact();const p=s.categories,g=s.getRawData(),f=new Array(p.length),y=new Array(p.length);if(h){const t=e.selection;if(0===t.length)throw new Error("No selected rows in the table.");for(let e=-1;-1!==(e=t.findNext(e,!0));){const t=g[e];(f[t]??=[]).push(d[e]),(y[t]??=[]).push(e)}}else for(let e=0;e<m;++e){const t=g[e];(f[t]??=[]).push(d[e]),(y[t]??=[]).push(e)}B(y,p);const b=await new I(["base/1.0.0",{tool:"kalign",version:$.b9,reinit:!0}]),w=o.Column.string(i,m);for(let e=0;e<p.length;++e){const t=f[e];if(!t||0===t.length)continue;const n=F(t);await b.fs.writeFile(O,n);const i=`${void 0!==r?` --gpo ${r}`:""}${void 0!==c?` --gpe ${c}`:""}${void 0!==u?` --tgpe ${u}`:""}`,o=await b.exec(`kalign ${O} -f fasta -o ${H}${i}`);console.warn(o);const s=await b.cat(H);if(!s){const e=G(o,1);throw new Error(e)}const l=new a.m(s).sequencesArray,h=y[e];for(let e=0;e<l.length;++e)w.set(h[e],l[e])}const v=t.meta.units,C=t.getTag(l.gp.alphabet);return w.meta.units=v,w.setTag(l.gp.aligned,"SEQ.MSA"),w.setTag(l.gp.alphabet,C),w.semType=o.SEMTYPE.MACROMOLECULE,w}function G(e,t){const n=[],i=/^.+ERROR : (.+)$/gm;let o;for(;null!=(o=i.exec(e))&&(null==t||n.length<t);)n.push(o[1]);return n.join("\n")}function B(e,t){const n=e.map((e,t)=>[e,t]).filter(([e,t])=>1==e.length).map(([e,t])=>t);if(n.length>0){const e=i.div([i.divText(`MSA analysis is not available on single sequence clusters #${n.length}:`),...r()(n).take(3).map(e=>{let o=t[e];return o.length>25&&(o=o.slice(0,25)+"..."),i.divText(`"${o}"${e<n.length-1?", ":"."}`)}).toArray(),...n.length>3?[i.divText("...")]:[]]);throw new D(e)}}},8152(e,t,n){"use strict";n.d(t,{GD:()=>d,Gf:()=>h});var i=n(4328),o=n(6082),s=n(2003),r=n(608),a=n(4139),l=n(3328);const c=["AlignedSeq","AlignedSubpeptide","HELM","ID","PolymerID"],u=new class{dcName="bio";async getDockerContainer(){return await i.dapi.docker.dockerContainers.filter(this.dcName).first()}};async function h(e,t="mafft --auto",n=1.53,i=0){const o=await u.getDockerContainer(),s=e.length,r=[];for(let t=0;t<s;t++){const n=e.get(t);n&&r.push({ID:t.toString(),HELM:n})}const a=function(e,t){const n=new Array(t).fill(null);for(const t of e.Alignment)n[parseInt(t.ID)]=m(t);return n}(await g(o.id,r,t,n,i),s);return p(e.dataFrame?.columns?.getUnusedName(`msa(${e.name})`)??`msa(${e.name})`,a)}async function d(e,t,n,i="ginsi",s=1.53,a=0,l=null,c,h=!1){const d=await u.getDockerContainer(),f=t.length;l??=o.Column.int("Clusters",f).init(0),l.type!==o.COLUMN_TYPE.STRING&&(l=l.convertTo(o.TYPE.STRING));const y=l.categories,b=l.getRawData(),w=new Array(y.length),v=new Array(y.length),C=h?function*(e){for(let t=-1;-1!==(t=e.findNext(t,!0));)yield t}(e.selection):function*(e){for(let t=0;t<e;t++)yield t}(f);for(const e of C){const n=b[e];if(!y[n])continue;const i=t.get(e);i&&((w[n]??=[]).push({ID:e.toString(),HELM:i}),(v[n]??=[]).push(e))}(0,r.aZ)(v,y);const A=new Array(f).fill(null);for(const e of w){if(!e||0===e.length)continue;const t=await g(d.id,e,i,s,a,c);for(const e of t.Alignment)A[parseInt(e.ID)]=m(e)}return p(n,A)}function m(e){return Object.entries(e).filter(([e])=>!c.includes(e)).map(([,e])=>"-"!==e?e:"").join(a.J.SEPARATOR)}function p(e,t){const n=o.Column.fromStrings(e,t);return n.meta.units=s.Hi.SEPARATOR,n.setTag(s.gp.separator,a.J.SEPARATOR),n.setTag(s.gp.aligned,"SEQ.MSA"),n.setTag(s.gp.alphabet,s.YI.UN),n.setTag(s.gp.alphabetIsMultichar,"true"),n.semType=o.SEMTYPE.MACROMOLECULE,n}async function g(e,t,n,o,s,r){const a={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(t)},c=`/align?method=${n}&gap_open=${o}&gap_extend=${s}`,u=window.performance.now(),h=await i.dapi.docker.dockerContainers.fetchProxy(e,c,a),d=window.performance.now();l._package.logger.debug(`Bio: requestAlignedObjects() ET: ${d-u} ms`);const m="application/json"===h.headers.get("content-type");if(!h.ok){if(m){const e=await h.json();if(e["pepsea-error"])throw new Error(`PepSeA error: ${e["pepsea-error"]}`);if(e["datagrok-error"])throw new Error(`Datagrok error: ${e["datagrok-error"]}`);throw new Error(h.statusText)}const e=await h.text();throw new Error(`Error: ${e}`)}if(!m){const e=await h.text();throw new Error(`Error: PepSeA expected JSON response, got '${e}'.`)}const p=await h.json();return"pepsea-stderr"in p&&r?.warning(p["pepsea-stderr"]),p}},3890(e,t,n){"use strict";n.d(t,{TE:()=>c,aS:()=>h,wz:()=>u});var i=n(6082),o=n(7389),s=n(4328),r=n(1991),a=n.n(r),l=n(3328);function c(){const e=s.shell.tv.grid,t=e.dataFrame,n=a().count(0).take(t.columns.length).map(e=>t.columns.byIndex(e)).filter(e=>e.semType!==i.SEMTYPE.MACROMOLECULE).toArray().find(e=>-1!==e.name.toLowerCase().indexOf("id")),r=n?[n]:[],c=o.input.columns("Seq id columns",{table:t,value:r,filter:e=>e.semType!==i.SEMTYPE.MACROMOLECULE}),h=a().count(0).take(t.columns.length).map(e=>t.columns.byIndex(e)).filter(e=>!(!e||e.semType!==i.SEMTYPE.MACROMOLECULE)&&l._package.seqHelper.getSeqHandler(e).isFasta()).toArray(),d=h.length>0?h[0]:null,m=o.input.column("Seq column",{table:t,value:d,filter:e=>!(!e||e.semType!==i.SEMTYPE.MACROMOLECULE)&&l._package.seqHelper.getSeqHandler(e).isFasta()}),p=o.input.int("FASTA line width",{value:60});o.dialog({title:"Save as FASTA"}).add(o.inputs([c,m,p])).onOK(()=>{const t=c.value??[],n=m.value??null,i=p.value??60;n||s.shell.warning("Seq column is mandatory to save as FASTA.");const o=u(t,l._package.seqHelper.getSeqHandler(n),i),r=document.createElement("a");r.setAttribute("href",`data:text/plain;charset=utf-8,${encodeURIComponent(o)}`),r.setAttribute("download",`${e.dataFrame.name}.fasta`),r.click()}).show()}function u(e,t,n=60,i="\n"){const o=[];for(let s=0;s<t.length;s++){const r=e.map(e=>e.get(s).toString()).join("|"),a=h(t.getSplitted(s),n);o.push(`>${r}${i}`);for(const e of a)o.push(`${e}${i}`)}return"".concat(...o)}function h(e,t=60){let n=0;const i=e.length,o=[];for(;n<i;){const i=a().count(n).take(Math.min(e.length-n,t)).map(t=>e.getOriginal(t)).toArray(),s=i.map(e=>e.length>1?`[${e}]`:e).reduce((e,t)=>e+t,"");o.push(s),n+=i.length}return o}},8754(e,t,n){"use strict";n.d(t,{V:()=>u});var i=n(4328),o=n(6077),s=n(2003),r=n(8312),a=n(5553),l=n(966),c=n(330);async function u(e,t,n,u,h,d,m){let p;if(n){const n=await(0,r.Q)(),i=n.getSeqHandler(t);let o,a;i.isHelm()?o=t:(a=t.name,t.name=`__${a}`,o=i.convert(s.Hi.HELM),o.name=a,e.columns.add(o,!1));try{p=await n.helmToAtomicLevel(o,!0,!0,h)}finally{o!==t&&(e.columns.remove(o.name),t.name=a)}}else{if(!(0,l.l)(t,"To Atomic Level",d)[0])return{molCol:null,warnings:["Column is not suitable"]};p=await(0,o.C4)(e,t,h,d,m)}if(p.molCol){const o=(0,c.qj)(e,t.name);p.molCol.name=o,e.columns.add(p.molCol,!0),await(0,a.Qc)(t,p.molCol,h,d,m,n),p.molCol.setTag(".sequence-src-highlight-monomers",String(u)),await i.data.detectSemanticTypes(e)}return p}},4870(e,t,n){"use strict";n.d(t,{Kd:()=>a,Ku:()=>r,me:()=>s});var i=n(4328),o=n(6082);function s(){const e=i.shell.t.columns.bySemTypeAll(o.SEMTYPE.MACROMOLECULE);return null==e?(i.shell.error("Current table does not contain macromolecules"),[]):e}function r(e,t){e.innerHTML="",e.append(t)}function a(e,t,n,i,o){const s=()=>{const o=e.col(t);o&&(o.width=n),i&&(e.props.rowHeight=i)};if(o)return void s();const r=e.onAfterDrawOverlay.subscribe(()=>{r.unsubscribe(),setTimeout(()=>{s()})})}},250(e,t,n){"use strict";n.d(t,{VN:()=>P,n5:()=>C,Ue:()=>S,Tc:()=>E,oP:()=>L,eN:()=>I});var i=n(4328),o=n(7389),s=n(6082),r=n(1757),a=n.n(r),l=n(1991),c=n.n(l),u=n(1858),h=n(2003),d=n(4326);function m(e){var t;return"string"==typeof e||e instanceof String?e:("object"==typeof e||e instanceof Object)&&"$thrownJsError"in e?m(e.$thrownJsError):e instanceof Error?null!==(t=e.stack)&&void 0!==t?t:e.message:e.toString()}var p=n(8070),g=n(7602),f=n(439),y=n(819);var b=n(3328);function w(e,t,n){return Math.abs(e-t)<=n}var v,C,A=n(6307),T=n(6197);HTMLCanvasElement.prototype.getCursorPosition=function(e,t){const n=this.getBoundingClientRect();return new s.Point((e.clientX-n.left)*t,(e.clientY-n.top)*t)},s.Rect.prototype.contains=function(e,t){return this.left<=e&&e<=this.right&&this.top<=t&&t<=this.bottom};class E{rowCount;value;plotValue;valueList=null;valueIdx=0;bounds;constructor(e=0,t){this.value=this.rowCount=e,this.bounds=t}push(e){this.valueList||(this.valueList=new Array(this.rowCount),this.valueIdx=0),this.valueList[this.valueIdx]=e,++this.valueIdx}aggregate(e){this.value=e(this.valueList)??0,this.valueList=null}}class S{pos;name;_label;get label(){return this._label?this._label:this.name}_freqs;sumRowCount=0;sumPlotValue;sumPlotValueForHeight;constructor(e,t,n,i){this.pos=e,this.name=t,this._freqs=n??{},i?.sumRowCount&&(this.sumRowCount=i.sumRowCount),i?.sumValueForHeight&&(this.sumPlotValue=i.sumValueForHeight),i?.label&&(this._label=i.label)}getMonomers(){return Object.keys(this._freqs)}hasMonomer(e){return e in this._freqs}getFreq(e){let t=this._freqs[e];return t||(t=this._freqs[e]=new E),t}aggregate(e){const t=function(e){return t=>{const n=function(e){let t;const n="agg";return t=e instanceof Float32Array?s.Column.fromFloat32Array(n,e):e instanceof Int32Array?s.Column.fromInt32Array(n,e):s.Column.fromList(s.COLUMN_TYPE.FLOAT,n,e),t}(t);return n.aggregate(e)}}(e);for(const[e,n]of Object.entries(this._freqs))n.aggregate(t)}getMinValue(){return Math.min(...Object.values(this._freqs).map(e=>e.value))}calcPlotValue(e){for(const t of Object.values(this._freqs))t.plotValue=t.value-e}calcHeights(e){this.sumPlotValue=0;for(const e of Object.values(this._freqs))this.sumPlotValue+=e.plotValue;if(this.sumPlotValueForHeight=0,e===d.fH.Entropy){const e=Object.keys(this._freqs).length,t=.01*this.sumPlotValue,n=t/e;for(const e of Object.values(this._freqs)){const i=(e.plotValue+n)/(this.sumPlotValue+t);this.sumPlotValueForHeight+=-i*Math.log2(i)}}else if(e===d.fH.full)for(const[e,t]of Object.entries(this._freqs)){const e=t.plotValue/this.sumPlotValue;this.sumPlotValueForHeight+=e}}calcScreen(e,t,n,i,o,r,a,l,c){const u=i===d.fH.Entropy?n*(o-this.sumPlotValueForHeight)/o:n;let h=c*l+(n-u-1);const m=Object.entries(this._freqs).sort((e,t)=>e[0]!==f._S&&t[0]!==f._S?t[1].value-e[1].value:e[0]===f._S&&t[0]===f._S?0:e[0]===f._S?-1:1);for(const[n,i]of m){const n=u*i.plotValue/this.sumPlotValue;i.bounds=new s.Rect((e-t)*l*r,h,a*l,n),h+=n}}render(e,t,n,i,o,s,r){for(const[a,l]of Object.entries(this._freqs))if(a!==f._S){let c=a;const u=l.bounds,d=u.left;let p=y.S$;if(s)try{p=s.getMonomerTextColor(o,a);const e=s.getMonomer((0,T.Y)(o),a);e&&e.symbol!==a&&(c=e.symbol)}catch(e){m(e)}const g=(0,h.zS)(c,r);e.resetTransform(),e.strokeStyle="lightgray",e.lineWidth=1,e.rect(d,u.top,u.width,u.height),e.fillStyle=p,e.textAlign="left",e.font=t;const f=e.measureText(g);e.setTransform(u.width/f.width,0,0,u.height/i,d,u.top),e.fillText(g,0,-n)}}getMonomerAt(e,t){const n=Object.entries(this._freqs).find(([n,i])=>i.bounds.contains(e,t));return n?n[0]:void 0}buildCompositionTable(e,t){if("-"in this._freqs)throw new Error("Unexpected monomer symbol '-'.");return(0,A.F)(Object.assign({},...Object.entries(this._freqs).map(([e,t])=>({[e]:t.rowCount}))),e,t)}}!function(e){e.STYLE="Style",e.BEHAVIOR="Behavior",e.LAYOUT="Layout",e.DATA="Data"}(v||(v={})),function(e){e.sequenceColumnName="sequenceColumnName",e.valueAggrType="valueAggrType",e.valueColumnName="valueColumnName",e.startPositionName="startPositionName",e.endPositionName="endPositionName",e.skipEmptySequences="skipEmptySequences",e.skipEmptyPositions="skipEmptyPositions",e.shrinkEmptyTail="shrinkEmptyTail",e.backgroundColor="backgroundColor",e.positionHeight="positionHeight",e.positionWidth="positionWidth",e.verticalAlignment="verticalAlignment",e.horizontalAlignment="horizontalAlignment",e.fixWidth="fixWidth",e.fitArea="fitArea",e.minHeight="minHeight",e.maxHeight="maxHeight",e.maxMonomerLetters="maxMonomerLetters",e.showPositionLabels="showPositionLabels",e.positionMarginState="positionMarginState",e.positionMargin="positionMargin",e.filterSource="filterSource"}(C||(C={}));const M=d.Fo;var x;!function(e){e[e.None=0]="None",e[e.Render=1]="Render",e[e.Layout=1]="Layout",e[e.Freqs=2]="Freqs"}(x||(x={}));const P=new class{render=20};class L extends s.JsViewer{static residuesSet="nucleotides";viewed=!1;seqHelper;seqHandler;initialized=!1;monomerLib=null;host;msgHost;canvas;slider;textBaseline;seqCol=null;positions=[];visibleSlider=!1;allowResize=!0;turnOfResizeForOneSetValue=!1;sequenceColumnName;valueAggrType;valueColumnName;skipEmptySequences;skipEmptyPositions;positionWidth;_positionWidth;_positionWidthWithMargin;get positionWidthWithMargin(){return this._positionWidthWithMargin}minHeight;backgroundColor=4294967295;maxHeight;maxMonomerLetters;showPositionLabels;positionMarginState;positionMargin=0;_positionMargin;startPositionName;endPositionName;fixWidth;verticalAlignment;horizontalAlignment;fitArea;shrinkEmptyTail;positionHeight;filterSource;positionNames=[];positionLabels=void 0;startPosition=-1;endPosition=-1;error=null;get Length(){return this.skipEmptyPositions?this.positions.length:this.startPosition<=this.endPosition?this.endPosition-this.startPosition+1:0}get positionMarginValue(){return this.positionMarginState===d.mH.AUTO&&!0===this.seqHandler.getAlphabetIsMultichar()||this.positionMarginState===d.mH.ON?this.positionMargin:0}constructor(){super(),this.seqHelper=b._package.seqHelper,this.textBaseline="top",this.seqHandler=null,this.sequenceColumnName=this.string(C.sequenceColumnName,M.sequenceColumnName,{category:v.DATA,semType:s.SEMTYPE.MACROMOLECULE,description:"Column with sequences"});const e=[s.AGG.KEY,s.AGG.PIVOT,s.AGG.MISSING_VALUE_COUNT,s.AGG.SKEW,s.AGG.KURT,s.AGG.SELECTED_ROWS_COUNT],t=Object.values(s.AGG).filter(t=>!e.includes(t));this.valueColumnName=this.string(C.valueColumnName,M.valueColumnName,{category:v.DATA,columnTypeFilter:"numerical",description:"Column with values used in aggregation for position heights"}),this.valueAggrType=this.string(C.valueAggrType,M.valueAggrType,{category:v.DATA,choices:t,description:"Aggregation method for value column"}),this.startPositionName=this.string(C.startPositionName,M.startPositionName,{category:v.DATA,description:"Position or column name for start position. If column with given name is found, its values will be used as start position. If number is supplied, it will be used as start position of WebLogo."}),this.endPositionName=this.string(C.endPositionName,M.endPositionName,{category:v.DATA,description:"Position or column name for end position. If column with given name is found, its values will be used as end position. If number is supplied, it will be used as end position of WebLogo."}),this.skipEmptySequences=this.bool(C.skipEmptySequences,M.skipEmptySequences,{category:v.DATA,description:"Skip sequences which are empty in all positions"}),this.skipEmptyPositions=this.bool(C.skipEmptyPositions,M.skipEmptyPositions,{category:v.DATA,description:"Skip positions which are empty in all sequences"}),this.shrinkEmptyTail=this.bool(C.shrinkEmptyTail,M.shrinkEmptyTail,{category:v.DATA,description:"Skip empty tail (if found for all sequences within a subset) in WebLogo"}),this.backgroundColor=this.int(C.backgroundColor,M.backgroundColor,{category:v.STYLE,description:"Background color of WebLogo canvas"}),this.positionHeight=this.string(C.positionHeight,M.positionHeight,{category:v.STYLE,choices:Object.values(d.fH),description:"Monomer-Position height mode. Entropy of 100%(full height)"}),this._positionWidth=this.positionWidth=this.float(C.positionWidth,M.positionWidth,{category:v.LAYOUT,editor:"slider",min:4,max:100,description:'Width of position in WebLogo. If "Fit Area" is enabled, width will be calculated to fit horizontal space'}),this.verticalAlignment=this.string(C.verticalAlignment,M.verticalAlignment,{category:v.LAYOUT,choices:Object.values(d.Lp)}),this.horizontalAlignment=this.string(C.horizontalAlignment,M.horizontalAlignment,{category:v.LAYOUT,choices:Object.values(d.P4)}),this.fixWidth=this.bool(C.fixWidth,M.fixWidth,{category:v.LAYOUT,userEditable:!1}),this.fitArea=this.bool(C.fitArea,M.fitArea,{category:v.LAYOUT,description:"Fit WebLogo to the horizontal space. Calculates position width as maximum between provided width value and value needed to fit whole horizontal space."}),this.minHeight=this.int(C.minHeight,M.minHeight,{category:v.LAYOUT,editor:"slider",min:10,max:250,description:"Minimum height of WebLogo"}),this.maxHeight=this.int(C.maxHeight,M.maxHeight,{category:v.LAYOUT,editor:"slider",min:25,max:Math.max(window.innerHeight??0,1e3),nullable:!0,description:"Maximum height of WebLogo"}),this.maxMonomerLetters=this.int(C.maxMonomerLetters,M.maxMonomerLetters,{category:v.LAYOUT,editor:"slider",min:1,max:40,description:"Maximum monomer letters to display before shortening"}),this.showPositionLabels=this.bool(C.showPositionLabels,M.showPositionLabels,{category:v.LAYOUT,description:"Show position labels on top of the weblogo"}),this.positionMarginState=this.string(C.positionMarginState,M.positionMarginState,{category:v.LAYOUT,choices:Object.values(d.mH),description:"Calculate optimal margins between positions or turn it on/off"});let n=0;"auto"===this.positionMarginState&&(n=4),this.positionMargin=this.int(C.positionMargin,n,{category:v.LAYOUT,min:0,max:25,description:"Margin between positions in WebLogo"}),this.filterSource=this.string(C.filterSource,M.filterSource,{category:v.BEHAVIOR,choices:Object.values(d.lT),description:"Data source for weblogo. Selected or filtered rows."}),this.slider=o.rangeSlider(0,100,0,20,!1,{style:"barbell"}),this.canvas=o.canvas(),this.canvas.classList.value="bio-wl-canvas",this.canvas.style.width="100%",b.PackageFunctions.getMonomerLibHelper().then(e=>{this.monomerLib=e.getMonomerLib(),this.render(x.Render,"monomerLib"),this.subs.push(this.monomerLib.onChanged.subscribe(()=>{this.render(x.Render,"monomerLib changed")}))}),this.viewSyncer=new g.g(b._package.logger)}static viewerCounter=-1;viewerId=++L.viewerCounter;toLog(){return`WebLogoViewer<${this.viewerId}>`}setData(){const e=`${this.toLog()}.setData()`;b._package.logger.debug(`${e}, in`),this.viewSyncer.sync(`${e}`,async()=>{if(!this.setDataInProgress){this.setDataInProgress=!0;try{this.viewed&&(this.renderRequestSub.unsubscribe(),await this.destroyView(),this.viewed=!1),this.updateSeqCol(),this.updateEditors(),this.viewed||(await this.buildView(),this.viewed=!0)}finally{this.setDataInProgress=!1}}}),b._package.logger.debug(`${e}, out`)}viewSyncer;setDataInProgress=!1;viewSubs=[];async destroyView(){for(const e of this.viewSubs)e.unsubscribe();this.viewSubs=[];const e=this.dataFrame?"data":"null";b._package.logger.debug(`${this.toLog()}.destroyView( dataFrame = ${e} ) start`),this.host.remove(),this.msgHost=void 0,this.host=void 0,b._package.logger.debug(`${this.toLog()}.destroyView() end`)}async buildView(){const e=this.dataFrame?"data":"null";b._package.logger.debug(`${this.toLog()}.buildView( dataFrame = ${e} ) start`),window.devicePixelRatio,this.viewSubs.push(s.debounce(this.renderRequest,P.render).subscribe(this.renderRequestOnDebounce.bind(this))),this.helpUrl="/help/visualize/viewers/web-logo.md",this.msgHost=o.div("No message",{classes:"bio-wl-msg"}),this.msgHost.style.display="none",this.canvas=o.canvas(),this.canvas.style.width="100%",this.slider.root.style.position="absolute",this.slider.root.style.zIndex="999",this.slider.root.style.display="none",this.slider.root.style.height="0.7em",this.visibleSlider=!1,this.host=o.div([this.msgHost,this.canvas],{classes:"bio-wl-host",style:{display:"flex",flexDirection:"row",flexGrow:"0",flexWrap:"wrap"}}),this.root.append(this.host),this.root.append(this.slider.root),this.error&&(this.msgHost.innerText=this.error.message,o.tooltip.bind(this.msgHost,this.error.stack),this.msgHost.style.setProperty("display",null)),this.dataFrame&&(this.viewSubs.push(this.dataFrame.filter.onChanged.subscribe(this.dataFrameFilterOnChanged.bind(this))),this.viewSubs.push(this.dataFrame.selection.onChanged.subscribe(this.dataFrameSelectionOnChanged.bind(this)))),this.viewSubs.push(o.onSizeChanged(this.root).subscribe(this.rootOnSizeChanged.bind(this))),this.viewSubs.push(this.slider.onValuesChanged.subscribe(this.sliderOnValuesChanged.bind(this))),this.viewSubs.push((0,u.fromEvent)(this.canvas,"mousemove").subscribe(this.canvasOnMouseMove.bind(this))),this.viewSubs.push((0,u.fromEvent)(this.canvas,"mousedown").subscribe(this.canvasOnMouseDown.bind(this))),this.viewSubs.push((0,u.fromEvent)(this.canvas,"wheel").subscribe(this.canvasOnWheel.bind(this))),this.render(x.Freqs,"buildView"),b._package.logger.debug(`${this.toLog()}.buildView() end`)}lastSize={width:-1,height:-1};rootOnSizeChanged(e){const t={width:e.target.clientWidth,height:e.target.clientHeight};this.lastSize.width==t.width&&this.lastSize.height==t.height||(b._package.logger.debug(`${this.toLog()}.rootOnSizeChanged(), ${JSON.stringify(t)}, start `),this.render(x.Layout,"rootOnSizeChanged")),this.lastSize=t}updateEditors(){this.props.getProperty(C.valueColumnName).choices=c()(this.dataFrame.columns.numerical).map(e=>e.name).toArray()}updateSeqCol(){if(this.dataFrame&&(this.seqCol=this.sequenceColumnName?this.dataFrame.col(this.sequenceColumnName):null,null==this.seqCol&&(this.seqCol=(0,h.mn)(this.dataFrame),this.sequenceColumnName=this.seqCol?this.seqCol.name:null),this.seqCol)){try{this.seqHandler=this.seqHelper.getSeqHandler(this.seqCol),this.render(x.Freqs,"updateSeqCol()"),this.error=null}catch(e){throw this.seqCol=null,this.error=e instanceof Error?e:new Error(e.toString()),e}this.seqCol||(this.seqHandler=null,this.positionNames=[],this.positionLabels=[],this.startPosition=-1,this.endPosition=-1)}}getFilter(){let e;switch(this.filterSource){case d.lT.Filtered:e=this.dataFrame.filter;break;case d.lT.Selected:e=0===this.dataFrame.selection.trueCount?this.dataFrame.filter:this.dataFrame.selection}return e}setSliderVisibility(e){e?(this.slider.root.style.display="inherit",this.visibleSlider=!0):(this.slider.root.style.display="none",this.visibleSlider=!1)}calcLayout(e){this.host&&this.canvas&&this.slider&&(this.host.classList.remove("bio-wl-fixWidth","bio-wl-fitArea"),this.canvas.classList.remove("bio-wl-fixWidth","bio-wl-fitArea"),this._positionWidth=this.positionWidth,this._positionMargin=this.positionMargin,this._positionWidthWithMargin=this._positionWidth+this.positionMarginValue,this.fixWidth?this.calcLayoutFixWidth(e):this.calcLayoutNoFitArea(e),this.slider.root.style.width=`${this.host.clientWidth}px`)}calcLayoutFixWidth(e){if(!this.host||!this.canvas||!this.slider)return;this.host.classList.add("bio-wl-fixWidth"),this.canvas.classList.add("bio-wl-fitArea");const t=this._positionWidthWithMargin*this.Length,n=Math.min(Math.max(this.minHeight,this.root.clientHeight),this.maxHeight??this.root.clientHeight);this.host.style.justifyContent=d.P4.LEFT,this.host.style.removeProperty("margin-left"),this.host.style.removeProperty("margin-top"),this.host.style.width=this.canvas.style.width=`${t}px`,this.host.style.height=this.canvas.style.height=`${n}px`,this.host.style.left=this.canvas.style.left="0",this.host.style.top=this.canvas.style.top="0",this.host.style.setProperty("overflow","hidden","important"),this.slider.root.style.display="none",this.slider.setValues(0,Math.max(0,this.Length-1),0,Math.max(0,this.Length-1)),this.canvas.width=t*e,this.canvas.height=n*e}calcLayoutNoFitArea(e){if(!this.host||!this.canvas||!this.slider)return;let t=this._positionWidthWithMargin*this.Length,n=Math.min(this.root.clientWidth,t);this.fitArea&&t<this.root.clientWidth&&(this._positionWidth=Math.floor(this._positionWidth*this.root.clientWidth/t),this._positionWidthWithMargin=this._positionWidth+this.positionMarginValue,t=this._positionWidthWithMargin*this.Length,n=Math.min(this.root.clientWidth,t));const i=Math.min(Math.max(this.minHeight,this.root.clientHeight),this.maxHeight??this.root.clientHeight);this.canvas.style.width=`${n}px`,this.canvas.style.height=`${i}px`,this.host.style.width=`${this.root.clientWidth}px`,this.host.style.height=`${this.root.clientHeight}px`,this.host.style.justifyContent=this.horizontalAlignment,this.host.style.alignContent=this.verticalAlignment===d.Lp.TOP?"start":this.verticalAlignment===d.Lp.MIDDLE?"center":this.verticalAlignment===d.Lp.BOTTOM?"end":"inherit",this.root.clientHeight<this.minHeight&&(this.host.style.alignContent="start",this.host.style.width=`${n+8}px`);const o=t>n;if(this.setSliderVisibility(o),o){this.slider.root.style.removeProperty("display"),this.host.style.justifyContent="left",this.host.style.height=this.root.clientHeight-this.slider.root.offsetHeight+"px",this.canvas.style.height=i-this.slider.root.offsetHeight+"px",this.slider.root.style.top=`${this.host.offsetHeight}px`;let e=Math.min(Math.max(0,this.slider.min),this.Length-.001),t=Math.min(Math.max(0,this.slider.max),this.Length-.001);const n=this.canvas.clientWidth/this._positionWidthWithMargin;t=Math.min(Math.max(e,0)+n,this.Length-.001),e=Math.max(0,Math.min(t,this.Length-.001)-n),this.safeUpdateSlider(0,Math.max(this.Length-.001),e,t)}else this.safeUpdateSlider(0,Math.max(0,this.Length-.001),0,Math.max(0,this.Length-.001));this.canvas.width=n*e,this.canvas.height=i*e}calcLayoutFitArea(e){if(!this.host||!this.canvas||!this.slider)return;const t=this._positionWidth*this.Length,n=Math.min(Math.max(this.minHeight,this.root.clientHeight),this.maxHeight??this.root.clientHeight),i=t>0?(this.root.clientWidth-this.positionMarginValue*this.Length)/t:0,o=this.root.clientHeight/n,s=Math.max(1,Math.min(i,o));this._positionWidth=this.positionWidth*s,this._positionWidthWithMargin=this._positionWidth+this.positionMarginValue;const r=(this._positionWidth+this.positionMarginValue)*this.Length,a=s*n,l=Math.min(this.root.clientWidth,r);this.canvas.style.width=`${l}px`,this.canvas.style.height=`${a}px`,this.host.style.width=`${l}px`,this.host.style.height=`${this.root.clientHeight}px`,this.host.style.justifyContent=this.horizontalAlignment,this.host.style.alignContent=this.verticalAlignment===d.Lp.TOP?"start":this.verticalAlignment===d.Lp.MIDDLE?"center":this.verticalAlignment===d.Lp.BOTTOM?"end":"inherit",this.root.clientHeight<this.minHeight&&(this.host.style.alignContent="start",this.host.style.width=`${l+6}px`),this.host.style.width=`${this.host}px`;const c=r>l;if(this.setSliderVisibility(c),c){this.slider.root.style.removeProperty("display"),this.host.style.justifyContent="left",this.host.style.height=this.root.clientHeight-this.slider.root.offsetHeight+"px",this.slider.root.style.top=`${this.host.offsetHeight}px`;let e=Math.min(Math.max(0,this.slider.min),this.Length-.001),t=Math.min(Math.max(0,this.slider.max),this.Length-.001);const n=this.root.clientWidth/this._positionWidthWithMargin;t=Math.min(Math.max(e,0)+n,this.Length-.001),e=Math.max(0,Math.min(t,this.Length-.001)-n),this.safeUpdateSlider(0,Math.max(0,this.Length-.001),e,t)}else this.safeUpdateSlider(0,Math.max(0,this.Length-.001),0,Math.max(0,this.Length-.001));this.canvas.width=l*e,this.canvas.height=a*e}safeUpdateSlider(e,t,n,i){w(e,this.slider.minRange,.1)&&w(t,this.slider.maxRange,.1)&&w(n,this.slider.min,.1)&&w(i,this.slider.max,.1)||this.slider.setValues(e,t,n,i)}onPropertyChanged(e){switch(super.onPropertyChanged(e),e.name){case C.sequenceColumnName:this.updateSeqCol();break;case C.sequenceColumnName:case C.startPositionName:case C.endPositionName:case C.filterSource:case C.shrinkEmptyTail:case C.skipEmptyPositions:case C.positionHeight:case C.valueColumnName:case C.valueAggrType:this.render(x.Freqs,`onPropertyChanged( ${e.name} )`);break;case C.minHeight:case C.maxHeight:case C.maxMonomerLetters:case C.positionWidth:case C.showPositionLabels:case C.fixWidth:case C.fitArea:case C.horizontalAlignment:case C.verticalAlignment:case C.positionMargin:case C.positionMarginState:this.render(x.Layout,`onPropertyChanged(${e.name})`);break;case C.backgroundColor:this.render(x.Render,`onPropertyChanged(${e.name})`)}}onTableAttached(){b._package.logger.debug(`${this.toLog()}.onTableAttached(), `),super.onTableAttached(),this.setData()}detach(){const e=`${this.toLog()}.detach()`;b._package.logger.debug(`${e}, in`);const t=super.detach.bind(this);this.viewSyncer.sync(`${e}`,async()=>{this.setDataInProgress||(this.viewed&&(await this.destroyView(),this.viewed=!1),t())}),b._package.logger.debug(`${e}, out`)}_onSizeChanged=new u.Subject;get onSizeChanged(){return this._onSizeChanged}_onFreqsCalculated=new u.Subject;get onFreqsCalculated(){return this._onFreqsCalculated}_onLayoutCalculated=new u.Subject;get onLayoutCalculated(){return this._onLayoutCalculated}getMonomer(e,t){const n=e.x,i=Math.floor(e.x/(this._positionWidthWithMargin*t)+Math.floor(this.slider.min)),o=this.positions[i];if(!o)return[null,null,null];const s=o.getMonomerAt(n,e.y);return null==s?[o,null,null]:[o,s,o.getFreq(s)]}_nullSequence(e="X"){return this.skipEmptySequences?"":new Array(this.Length).fill(e).join("")}_removeEmptyPositions(){this.skipEmptyPositions&&(this.positions=c()(this.positions).filter(e=>!e.hasMonomer(f._S)||e.getFreq(f._S).rowCount!==e.sumRowCount).toArray())}requestedRenderLevel=x.Freqs;renderRequest=new u.Subject;renderRequestSub;render(e,t){b._package.logger.debug(`${this.toLog()}.render( recalcLevelVal=${e}, reason='${t}' )`),this.requestedRenderLevel=Math.max(this.requestedRenderLevel,e),this.renderRequest.next(this.requestedRenderLevel)}async renderInt(e){if(b._package.logger.debug(`${this.toLog()}.render.renderInt( renderLevel=${e} ), start `),this.msgHost&&(this.msgHost.style.display="none"),!this.seqCol||!this.dataFrame||null==this.host||null==this.slider)return;const t=window.devicePixelRatio,n=this.showPositionLabels?12:0;if(e>=x.Freqs&&(()=>{if(b._package.logger.debug(`${this.toLog()}.render.calculateFreqsInt(), start `),!this.host||!this.seqCol||!this.dataFrame)return;const e=this.seqCol.getTag(h.gp.positionNames),t=this.seqCol.getTag(h.gp.positionLabels);let n;!e&&this.endPositionName&&/\d+/.test(this.endPositionName)?n=Number(this.endPositionName):e&&this.endPositionName&&(n=e.split(h.z1).indexOf(this.endPositionName),n=-1!==n?n:void 0);const i=this.getFilter(),o=0===i.trueCount?this.seqHandler.maxLength:c().count(0).take(this.seqHandler.length).map(e=>{const t=this.seqHandler.getSplitted(e,n);return i.get(e)&&t?t.length:0}).reduce((e,t)=>Math.max(e,t),0);this.positionNames=e?e.split(h.z1).map(e=>e.trim()):[...Array(o).keys()].map(e=>`${e+1}`),this.positionLabels=t?t.split(h.z1).map(e=>e.trim()):void 0,this.startPosition=this.startPositionName&&this.positionNames&&this.positionNames.includes(this.startPositionName)?this.positionNames.indexOf(this.startPositionName):0,this.endPosition=this.endPositionName&&this.positionNames&&this.positionNames.includes(this.endPositionName)?this.positionNames.indexOf(this.endPositionName):o-1;const r=this.startPosition<=this.endPosition?this.endPosition-this.startPosition+1:0;this.seqHandler=this.seqHelper.getSeqHandler(this.seqCol);const a=this.startPosition<=this.endPosition?this.endPosition-this.startPosition+1:0;this.positions=new Array(a);for(let e=0;e<r;e++){const t=this.positionNames[this.startPosition+e],n=this.positionLabels?this.positionLabels[this.startPosition+e]:void 0;this.positions[e]=new S(this.startPosition+e,t,{},{label:n})}this.dataFrame.rowCount;const l=i.getSelectedIndexes();for(let e=0;e<r;++e){for(const t of l){const n=this.seqHandler.getSplitted(t),i=e+this.startPosition<n.length?n.getCanonical(this.startPosition+e):this.seqHandler.defaultGapOriginal,o=this.seqHandler.defaultGapOriginal===i?f._S:i,s=this.positions[e],r=s.getFreq(o);++s.sumRowCount,r.value=++r.rowCount}if(this.valueAggrType===s.AGG.TOTAL_COUNT)continue;let t=null;try{t=this.dataFrame.getCol(this.valueColumnName),t.matches("numerical")||(t=null)}catch{t=null}if(t){for(const n of l){const i=this.seqHandler.getSplitted(n),o=e+this.startPosition<i.length?i.getCanonical(this.startPosition+e):this.seqHandler.defaultGapOriginal,s=this.seqHandler.defaultGapOriginal===o?f._S:o,r=t.get(n);this.positions[e].getFreq(s).push(r)}this.positions[e].aggregate(this.valueAggrType)}}const u=this.valueAggrType===s.AGG.TOTAL_COUNT?0:Math.min(0,Math.min(...this.positions.map(e=>e.getMinValue())));for(let e=0;e<r;++e)this.positions[e].calcPlotValue(u),this.positions[e].calcHeights(this.positionHeight);this._removeEmptyPositions(),this._onFreqsCalculated.next()})(),this.calcLayout(t),-1===this.startPosition)return;const o=Math.max(Math.floor(this.slider.min),0),r=Math.min(this.positions.length-1,Math.floor(this.slider.max));e>=x.Layout&&((e,t,n,o)=>{b._package.logger.debug(`${this.toLog()}.render.calculateLayoutInt(), start `);const r=this.canvas.height-o*n;let a;if(this.valueAggrType===s.AGG.TOTAL_COUNT){const e=this.seqHandler.getAlphabetSize();this.positionHeight==d.fH.Entropy&&null==e&&i.shell.error("WebLogo: alphabet is undefined."),a=Math.log2(e)}else a=Math.max(...c().count(e).takeWhile(e=>e<=t).map(e=>this.positions[e].sumPlotValueForHeight));for(let i=e;i<=t;++i)i in this.positions?this.positions[i].calcScreen(i,this.slider.min,r,this.positionHeight,a,this._positionWidthWithMargin,this._positionWidth,n,o):b._package.logger.warning(`${this.toLog()}.render.calculateLayoutInt() this.positions.length = ${this.positions.length}, jPos = ${i}`);b._package.logger.debug(`${this.toLog()}.render.calculateLayoutInt(), end `),this._onLayoutCalculated.next()})(o,r,window.devicePixelRatio,n);const a=this.canvas.getContext("2d");if(a){a.save();try{this.Length,a.resetTransform(),a.fillStyle=function(e){const t=s.Color.a(e);return`#${(16777215&e).toString(16).padStart(6,"0")}`+t.toString(16).padStart(2,"0")}(this.backgroundColor),a.fillRect(0,0,this.canvas.width,this.canvas.height),a.textBaseline=this.textBaseline;const e=10*t;a.resetTransform(),a.fillStyle="black",a.textAlign="center",a.font=`${e.toFixed(1)}px Roboto, Roboto Local, sans-serif`,n>0&&this.positions.length>0&&function(e,t,n,i,o,s,r,a){e.save();try{e.textAlign="center";let l=null,c=null;for(let t=Math.floor(r);t<=Math.floor(a);t++){const n=s[t],i=e.measureText(n.name),o=i.actualBoundingBoxDescent-i.actualBoundingBoxAscent;l=null==l?i.width:Math.max(l,i.width),c=null==c?o:Math.max(c,o)}const u=l<i*t-2?1:(i*t-2)/l;for(let l=Math.floor(r);l<=Math.floor(a);l++){const a=s[l],h=(l-r)*n*t+i*t/2,d=(o*t-c)/2;e.setTransform(u,0,0,1,h,d),e.measureText(a.label),e.fillText(a.label,0,0)}}finally{e.restore()}}(a,t,this._positionWidthWithMargin,this._positionWidth,n,this.positions,this.slider.min,this.slider.max);const i="16px Roboto, Roboto Local, sans-serif",l=.25,c=12.2,u=this.seqHandler.defaultBiotype;for(let e=o;e<=r;e++)this.positions[e].render(a,i,l,c,u,this.monomerLib,this.maxMonomerLetters)}finally{a.restore()}b._package.logger.debug(`${this.toLog()}.render.renderInt( recalcLevel=${e} ), end`)}}renderRequestOnDebounce(e){const t=`${this.toLog()}.renderRequestOnDebounce()`;"HTML"!==a()(this.root).offsetParent().get()[0]?.tagName?(this.requestedRenderLevel=x.None,this.viewSyncer.sync(t,async()=>{await this.renderInt(e)})):b._package.logger.warning(`${t}, $(this.root).offsetParent() is the 'HTML' tag.`)}_lastWidth;_lastHeight;sliderOnValuesChanged(e){try{const e={minRange:this.slider.minRange,min:this.slider.min,max:this.slider.max,maxRange:this.slider.maxRange};if(this.canvas&&this.canvas.offsetWidth>0&&(this._positionWidthWithMargin??0)>0){const t=e.max-e.min,n=this.canvas.offsetWidth/t-this.positionMarginValue;w(n,this.positionWidth,.1)?this.render(x.Layout,"sliderOnValuesChanged"):this.getProperty(C.positionWidth)?.set(this,n)}}catch(e){const t=m(e);b._package.logger.error(`${this.toLog()}.sliderOnValuesChanged() error:\n`+t)}}dataFrameFilterOnChanged(e){b._package.logger.debug(`${this.toLog()}.dataFrameFilterChanged()`);try{this.filterSource===d.lT.Filtered&&this.render(x.Freqs,"dataFrameFilterOnChanged")}catch(e){const t=m(e);b._package.logger.error(`${this.toLog()}.dataFrameFilterOnChanged() error:\n`+t)}}dataFrameSelectionOnChanged(e){b._package.logger.debug(`${this.toLog()}.dataFrameSelectionOnChanged()`);try{this.filterSource===d.lT.Selected&&this.render(x.Freqs,"dataFrameSelectionOnChanged")}catch(e){const t=m(e);b._package.logger.error(`${this.toLog()}.dataFrameSelectionOnChanged() error:\n`+t)}}canvasOnMouseMove(e){if(!this.monomerLib||!this.seqHandler)return;const t=window.devicePixelRatio;try{const n=e,i=this.canvas.getCursorPosition(n,t),[r,a]=this.getMonomer(i,t),l=this.showPositionLabels?12*t:0;if(null!==r&&null==a&&0<=i.y&&i.y<=l){const e=[o.divText(`Position ${r.label}`)];if(this.valueAggrType===s.AGG.TOTAL_COUNT){const t=this.seqHandler.defaultBiotype;e.push(r.buildCompositionTable(t,this.monomerLib))}const t=o.divV(e);t.style.maxHeight="80vh",o.tooltip.show(t,n.x+16,n.y+16)}else if(null!==r&&a&&this.dataFrame&&this.seqCol&&this.seqHandler){const e=r.getFreq(a),t=[o.div(`${a}`),o.div(`${e.rowCount} rows`)];this.valueAggrType!==s.AGG.TOTAL_COUNT&&t.push(o.div(`${this.valueAggrType}: ${e.value.toFixed(3)}`));const i=o.divV(t);o.tooltip.show(i,n.x+16,n.y+16)}else o.tooltip.hide()}catch(e){const t=m(e);b._package.logger.error(`${this.toLog()}.canvasOnMouseMove() error:\n`+t)}}canvasOnMouseDown(e){try{const t=e,n=window.devicePixelRatio,[i,o]=this.getMonomer(this.canvas.getCursorPosition(t,n),n);if(null!==i&&null!==o&&this.dataFrame&&this.seqCol&&this.seqHandler){const e=s.BitSet.create(this.dataFrame.selection.length,e=>function(e,t,n,i,o,s){const r=t.getSplitted(i),a=s.pos<r.length?r.getCanonical(s.pos):null;return null!==a&&a===o}(this.dataFrame,this.seqHandler,this.getFilter(),e,o,i));this.dataFrame.selection.init(t=>e.get(t))}}catch(e){const t=m(e);b._package.logger.error(`${this.toLog()}.canvasOnMouseDown() error:\n`+t)}}canvasOnWheel(e){const t=window.devicePixelRatio;try{if(!this.visibleSlider)return;const n=this.canvas.width/(this._positionWidthWithMargin*t),i=e.deltaY/100*Math.max(Math.floor(n/5),1);this.slider.scrollBy(this.slider.min+i)}catch(e){const t=m(e);b._package.logger.error(`${this.toLog()}.canvasOnWheel() error:\n`+t)}}_onRendered=new u.Subject;get onRendered(){return this._onRendered}invalidate(e){const t=`invalidate(${e?` <- ${e} `:""})`,n=`${this.toLog()}.${t}`;this.render(x.None,t),this.viewSyncer.sync(`${n}`,async()=>{this._onRendered.next()})}async awaitRendered(e=5e3){await(0,p.PE)(this.onRendered,()=>{},()=>{this.invalidate()},e);const t=this.viewSyncer.resetErrors();if(t.length>0)throw t[0]}}function I(e,t,n,i,o){let s=0,r=-1;for(;-1!=(r=n.findNext(r,!0));){const e=t.getSplitted(r),n=o.pos,a=n<e.length?e.getCanonical(n):null;null!==a&&a===i&&s++}return s}},1687(e,t,n){"use strict";n.d(t,{_i:()=>E,AR:()=>T});var i=n(7389),o=n(6082),s=n(4328),r=n(1991),a=n.n(r),l=n(1858),c=n(2003),u=n(8070),h=n(7602),d=n(4954),m=n(4574),p=n(1757),g=n.n(p),f=n(9124),y=n(9192),b=n(4870),w=n(3328);class v extends m.O{seqHelper;emptyProps=new m.n("",void 0,w._package.logger);helmEditor;_filterPanel=i.div("",{style:{cursor:"pointer"}});logger;static viewerCounter=-1;viewerId=++v.viewerCounter;viewerToLog(){return`HelmBioFilter<${this.viewerId}>`}get type(){return"HelmBioFilter"}constructor(e){super(),this.seqHelper=e,this.logger=w._package.logger}viewSubs=[];async detach(){await super.detach();for(const e of this.viewSubs)e.unsubscribe()}async attach(){this.viewerToLog();try{const e=await(0,f.b2)();let t,n;this.helmEditor=e.createHelmWebEditor(),this.logger.warning("TEST: HelmBioFilter.init().sync() waitForElementInDom waiting..."),await i.tools.waitForElementInDom(this._filterPanel),this.logger.warning("TEST: HelmBioFilter.init().sync() waitForElementInDom ready"),this.updateFilterPanel(),this.viewSubs.push((0,l.fromEvent)(this._filterPanel,"click").subscribe(()=>{t=i.div(),n=e.createWebEditorApp(t,this.props.substructure),i.dialog({showHeader:!1,showFooter:!0}).add(t).onOK(()=>{try{const e=n.canvas.getHelm(!0).replace(/<\/span>/g,"").replace(/<span style='background:#bbf;'>/g,"");this.props=new m.n(e,void 0,w._package.logger)}catch(e){this.logger.error(e)}finally{g()(t).empty(),t=null,n=null}}).onCancel(()=>{g()(t).empty(),t=null,n=null}).show({modal:!0,fullScreen:!0})})),this.viewSubs.push(i.onSizeChanged(this._filterPanel).subscribe(e=>{try{if(n){const e=n.canvas.getHelm(!0).replace(/<\/span>/g,"").replace(/<span style='background:#bbf;'>/g,"");this.updateFilterPanel(e)}}catch(e){const[t,n]=(0,y.AP)(e);this.logger.error(t,void 0,n)}}))}catch(e){const[t,n]=(0,y.AP)(e),o=this._filterPanel;o.innerText="error",o.classList.add("d4-error"),i.tooltip.bind(o,t)}}applyProps(){this.helmEditor&&this.updateFilterPanel(this.props.substructure)}get filterPanel(){return this._filterPanel}updateFilterPanel(e){if(!this.helmEditor)throw new Error("helmEditor is not created, the filter is not in dom yet");const t=this._filterPanel.parentElement.clientWidth<100?100:this._filterPanel.parentElement.clientWidth,n=t/2;if(e)(0,b.Ku)(this._filterPanel,this.helmEditor.host),this.helmEditor.editor.setHelm(e),this.helmEditor.resizeEditor(t,n);else{const e=i.divText("Click to edit","helm-substructure-filter");(0,b.Ku)(this._filterPanel,e)}}async substructureSearch(e){const t=`${this.viewerToLog()}.substructureSearch( column = <${e.name}> )`;w._package.logger.debug(`${t}, start`);try{return await o.delay(10),await(0,d.if)(this.props.substructure,e,this.seqHelper)}finally{w._package.logger.debug(`${t}, end`)}}}const C="bio-substructure-filter";class A{props;filterId;dataFrameId;columnName;bitset;constructor(e,t,n,i,o){this.props=e,this.filterId=t,this.dataFrameId=n,this.columnName=i,this.bitset=o}}class T extends m.n{separator;constructor(e,t,n){super(e,!1,n),this.separator=t,this.readOnly=!0}}class E extends o.Filter{seqHelper;logger;bioFilter=null;bitset=null;loader;notation=void 0;filterSyncer;get calculating(){return"initial"==this.loader.style.display}set calculating(e){this.loader.style.display=e?"initial":"none"}get filterSummary(){return this.bioFilter?.filterSummary??""}get isFiltering(){return super.isFiltering&&(this.bioFilter?.isFiltering??!1)}get isReadyToApplyFilter(){return!this.calculating&&null!=this.bitset}get debounceTime(){if(null==this.column)return 1e3;const e=this.column.length;return e<500?0:e>1e4?1e3:Math.floor((e-500)/9500*1e3)}constructor(e,t){super(),this.seqHelper=e,this.logger=t,this.root=i.divV([]),this.loader=i.loader(),this.calculating=!1,this.filterSyncer=new h.g(this.logger)}static filterCounter=-1;filterId=++E.filterCounter;filterToLog(){return`BioSubstructureFilter<${this.filterId}>`}viewSubs=[];attach(e){const t=super.attach.bind(this),n=`${this.filterToLog()}.attach()`;this.filterSyncer.sync(n,async()=>{e&&await e.meta.detectSemanticTypes(),t(e),this.column||(this.columnName?this.column=this.dataFrame.getCol(this.columnName):this.column=e.columns.bySemType(o.SEMTYPE.MACROMOLECULE)),this.seqHelper.getSeqHandler(this.column),this.columnName??=this.column?.name,this.notation??=this.column?.meta.units,this.bioFilter=this.notation===c.Hi.FASTA?new S:this.notation===c.Hi.SEPARATOR?new M(this.column.getTag(c.gp.separator)):new v(this.seqHelper),this.root.appendChild(this.bioFilter.filterPanel),this.root.appendChild(this.loader),await this.bioFilter.attach(),this.viewSubs.push(o.debounce(this.bioFilter.onChanged,this.debounceTime).subscribe(this.bioFilterOnChangedDebounced.bind(this))),this.viewSubs.push(s.events.onResetFilterRequest.subscribe(this.grokEventsOnResetFilterRequest.bind(this))),this.viewSubs.push(s.events.onCustomEvent(C).subscribe(this.filterOnSync.bind(this)))})}detach(){const e=super.detach.bind(this),t=`${this.filterToLog()}.detach()`;this.filterSyncer.sync(t,async()=>{for(const e of this.viewSubs)e.unsubscribe();this.viewSubs=[],e(),this.bioFilter&&this.bioFilter.detach(),this.bioFilter=null})}filterOnSync(e){e.filterId!==this.filterId&&this.bioFilter&&e.dataFrameId===this.dataFrame.id&&e.columnName===this.columnName&&(this.bioFilter.props=e.props)}applyFilter(){const e=`${this.filterToLog()}.applyFilter()`;this.logger.debug(`${e}, IN`),this.bitset&&!this.isDetached&&this.dataFrame?.filter.and(this.bitset)}saveState(){const e=`${this.filterToLog()}.saveState()`,t=super.saveState();return this.logger.debug(`${e}, super.state = ${JSON.stringify(t)}`),this.bioFilter&&(t.props=this.bioFilter.saveProps()),t}applyState(e){const t=`${this.filterToLog()}.applyState()`;super.applyState(e),this.filterSyncer.sync(t,async()=>{e.props&&this.bioFilter&&(this.bioFilter.props=o.toJs(e.props??{}))})}fireFilterSync(){const e=`${this.filterToLog()}.fireFilterSync()`;this.logger.debug(`${e}, bioFilter = ${this.bioFilter?this.bioFilter.constructor.name:"null"}`+(this.bioFilter?`, props = ${JSON.stringify(this.bioFilter.saveProps())}`:"")),this.bioFilter&&s.events.fireCustomEvent(C,new A(this.bioFilter.props,this.filterId,this.dataFrame.id,this.columnName,this.bitset))}bioFilterOnChangedDebounced(){if(!this.dataFrame)return;const e=`${this.filterToLog()}.bioFilterOnChangedDebounced()`;if(this.logger.debug(`${e}, start, isFiltering = ${this.isFiltering}, props = ${this.bioFilter?JSON.stringify(this.bioFilter?.saveProps()):"null"}`),!this.isFiltering)return this.bitset=null,void this.dataFrame.rows.requestFilter();a()(this.dataFrame.rows.filters).has(`${this.columnName}: ${this.filterSummary}`)||this.filterSyncer.sync(e,async()=>{this.calculating=!0;try{this.logger.debug(`${e}, before substructureSearch`),this.bitset=await(this.bioFilter?.substructureSearch(this.column)),this.logger.debug(`${e}, after substructureSearch`),this.calculating=!1,this.fireFilterSync(),this.dataFrame?.rows.requestFilter()}finally{this.calculating=!1,this.logger.debug(`${e}, end`)}})}grokEventsOnResetFilterRequest(){const e=`${this.filterToLog()}.grokEventsOnResetFilterRequest()`;this.logger.debug(`${e}`),this.bioFilter?.resetFilter()}_onRendered=new l.Subject;get onRendered(){return this._onRendered}invalidate(e){const t=`${this.filterToLog()}.invalidate(${e?` <- ${e} `:""})`;this.filterSyncer.sync(t,async()=>{this._onRendered.next()})}async awaitRendered(e=1e4){const t=`awaitRendered( ${e} )`,n=`${this.filterToLog()}.${t}`;await o.delay(10),await(0,u.PE)(this.onRendered,()=>{this.logger.debug(`${n}, _onRendered event caught`)},()=>{this.invalidate(t)},e,`${n} timeout`);const i=this.filterSyncer.resetErrors();if(i.length>0)throw i[0]}}class S extends m.O{emptyProps=new m.n("",void 0,w._package.logger);substructureInput;get type(){return"FastaBioFilter"}constructor(){super(),this.substructureInput=i.input.string("",{value:"",onValueChanged:e=>{window.setTimeout(()=>{this.props=new m.n(e,void 0,w._package.logger),this._propsChanging||this.onChanged.next()},0)},placeholder:"Substructure"})}applyProps(){this.substructureInput.value!==this.props.substructure&&(this.substructureInput.value=this.props.substructure)}get filterPanel(){return this.substructureInput.root}get isFiltering(){return""!==this.substructureInput.value}async substructureSearch(e){return(0,d.nI)(this.props.substructure,e)}async attach(){}async detach(){await super.detach()}}class M extends m.O{emptyProps=new T("",void 0,w._package.logger);substructureInput;separatorInput;colSeparator="";get type(){return"SeparatorBioFilter"}constructor(e){super(),this.substructureInput=i.input.string("",{value:"",onValueChanged:e=>{this.props=new T(e,this.props.separator,w._package.logger),setTimeout(()=>{this._propsChanging||this.onChanged.next()})},placeholder:"Substructure"}),this.separatorInput=i.input.string("",{value:this.colSeparator=e,onValueChanged:e=>{const t=e||"";this.props=new T(this.props.substructure,t,w._package.logger),setTimeout(()=>{this._propsChanging||this.onChanged.next()})},placeholder:"Separator"})}applyProps(){this.substructureInput.value!==this.props.substructure&&(this.substructureInput.value=this.props.substructure);const e=this.props.separator??this.colSeparator;this.separatorInput.value!==e&&(this.separatorInput.value=e)}get filterSummary(){return this.props.separator?this.props.separator:this.colSeparator,`${this.props.substructure}, {sep}`}get isFiltering(){return""!==this.props.substructure}resetFilter(){this.props=new T("",void 0,w._package.logger)}get filterPanel(){return i.divV([this.substructureInput.root,this.separatorInput.root])}get substructure(){return this.separatorInput.value&&this.separatorInput.value!==this.colSeparator?this.substructureInput.value.replaceAll(this.separatorInput.value,this.colSeparator):this.substructureInput.value}set substructure(e){this.substructureInput.value=e}async substructureSearch(e){return(0,d.nI)(this.substructure,e,this.colSeparator)}async attach(){}async detach(){await super.detach()}}},1757(e){"use strict";e.exports=$},6082(e){"use strict";e.exports=DG},4328(e){"use strict";e.exports=grok},1858(e){"use strict";e.exports=rxjs},9713(e){"use strict";e.exports=rxjs.operators},7389(e){"use strict";e.exports=ui},1991(e){"use strict";e.exports=wu},8343(e,t,n){"use strict";const{normalizeIPv6:i,normalizeIPv4:o,removeDotSegments:s,recomposeAuthority:r,normalizeComponentEncoding:a}=n(4834),l=n(343);function c(e,t,n,i){const o={};return i||(e=m(u(e,n),n),t=m(u(t,n),n)),!(n=n||{}).tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=s(t.path||""),o.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=s(t.path||""),o.query=t.query):(t.path?("/"===t.path.charAt(0)?o.path=s(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path:o.path="/"+t.path,o.path=s(o.path)),o.query=t.query):(o.path=e.path,void 0!==t.query?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function u(e,t){const n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},i=Object.assign({},t),o=[],a=l[(i.scheme||n.scheme||"").toLowerCase()];a&&a.serialize&&a.serialize(n,i),void 0!==n.path&&(i.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),void 0!==n.scheme&&(n.path=n.path.split("%3A").join(":")))),"suffix"!==i.reference&&n.scheme&&o.push(n.scheme,":");const c=r(n);if(void 0!==c&&("suffix"!==i.reference&&o.push("//"),o.push(c),n.path&&"/"!==n.path.charAt(0)&&o.push("/")),void 0!==n.path){let e=n.path;i.absolutePath||a&&a.absolutePath||(e=s(e)),void 0===c&&(e=e.replace(/^\/\//u,"/%2F")),o.push(e)}return void 0!==n.query&&o.push("?",n.query),void 0!==n.fragment&&o.push("#",n.fragment),o.join("")}const h=Array.from({length:127},(e,t)=>/[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(t))),d=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function m(e,t){const n=Object.assign({},t),s={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},r=-1!==e.indexOf("%");let a=!1;"suffix"===n.reference&&(e=(n.scheme?n.scheme+":":"")+"//"+e);const c=e.match(d);if(c){if(s.scheme=c[1],s.userinfo=c[3],s.host=c[4],s.port=parseInt(c[5],10),s.path=c[6]||"",s.query=c[7],s.fragment=c[8],isNaN(s.port)&&(s.port=c[5]),s.host){const e=o(s.host);if(!1===e.isIPV4){const t=i(e.host);s.host=t.host.toLowerCase(),a=t.isIPV6}else s.host=e.host,a=!0}void 0!==s.scheme||void 0!==s.userinfo||void 0!==s.host||void 0!==s.port||void 0!==s.query||s.path?void 0===s.scheme?s.reference="relative":void 0===s.fragment?s.reference="absolute":s.reference="uri":s.reference="same-document",n.reference&&"suffix"!==n.reference&&n.reference!==s.reference&&(s.error=s.error||"URI is not a "+n.reference+" reference.");const e=l[(n.scheme||s.scheme||"").toLowerCase()];if(!(n.unicodeSupport||e&&e.unicodeSupport)&&s.host&&(n.domainHost||e&&e.domainHost)&&!1===a&&function(e){let t=0;for(let n=0,i=e.length;n<i;++n)if(t=e.charCodeAt(n),t>126||h[t])return!0;return!1}(s.host))try{s.host=URL.domainToASCII(s.host.toLowerCase())}catch(e){s.error=s.error||"Host's domain name can not be converted to ASCII: "+e}(!e||e&&!e.skipNormalize)&&(r&&void 0!==s.scheme&&(s.scheme=unescape(s.scheme)),r&&void 0!==s.host&&(s.host=unescape(s.host)),s.path&&(s.path=escape(unescape(s.path))),s.fragment&&(s.fragment=encodeURI(decodeURIComponent(s.fragment)))),e&&e.parse&&e.parse(s,n)}else s.error=s.error||"URI can not be parsed.";return s}const p={SCHEMES:l,normalize:function(e,t){return"string"==typeof e?e=u(m(e,t),t):"object"==typeof e&&(e=m(u(e,t),t)),e},resolve:function(e,t,n){const i=Object.assign({scheme:"null"},n);return u(c(m(e,i),m(t,i),i,!0),{...i,skipEscape:!0})},resolveComponents:c,equal:function(e,t,n){return"string"==typeof e?(e=unescape(e),e=u(a(m(e,n),!0),{...n,skipEscape:!0})):"object"==typeof e&&(e=u(a(e,!0),{...n,skipEscape:!0})),"string"==typeof t?(t=unescape(t),t=u(a(m(t,n),!0),{...n,skipEscape:!0})):"object"==typeof t&&(t=u(a(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()},serialize:u,parse:m};e.exports=p,e.exports.default=p,e.exports.fastUri=p},343(e){"use strict";const t=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu,n=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function i(e){return"boolean"==typeof e.secure?e.secure:"wss"===String(e.scheme).toLowerCase()}function o(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function s(e){const t="https"===String(e.scheme).toLowerCase();return e.port!==(t?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}const r={scheme:"http",domainHost:!0,parse:o,serialize:s},a={scheme:"ws",domainHost:!0,parse:function(e){return e.secure=i(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e){if(e.port!==(i(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,n]=e.resourceName.split("?");e.path=t&&"/"!==t?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}},l={http:r,https:{scheme:"https",domainHost:r.domainHost,parse:o,serialize:s},ws:a,wss:{scheme:"wss",domainHost:a.domainHost,parse:a.parse,serialize:a.serialize},urn:{scheme:"urn",parse:function(e,t){if(!e.path)return e.error="URN can not be parsed",e;const i=e.path.match(n);if(i){const n=t.scheme||e.scheme||"urn";e.nid=i[1].toLowerCase(),e.nss=i[2];const o=`${n}:${t.nid||e.nid}`,s=l[o];e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e},serialize:function(e,t){const n=t.scheme||e.scheme||"urn",i=e.nid.toLowerCase(),o=`${n}:${t.nid||i}`,s=l[o];s&&(e=s.serialize(e,t));const r=e,a=e.nss;return r.path=`${i||t.nid}:${a}`,t.skipEscape=!0,r},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(e,n){const i=e;return i.uuid=i.nss,i.nss=void 0,n.tolerant||i.uuid&&t.test(i.uuid)||(i.error=i.error||"UUID is not valid."),i},serialize:function(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t},skipNormalize:!0}};e.exports=l},4914(e){"use strict";e.exports={HEX:{0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15}}},4834(e,t,n){"use strict";const{HEX:i}=n(4914),o=/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u;function s(e){if(c(e,".")<3)return{host:e,isIPV4:!1};const t=e.match(o)||[],[n]=t;return n?{host:l(n,"."),isIPV4:!0}:{host:e,isIPV4:!1}}function r(e,t=!1){let n="",o=!0;for(const t of e){if(void 0===i[t])return;"0"!==t&&!0===o&&(o=!1),o||(n+=t)}return t&&0===n.length&&(n="0"),n}function a(e){if(c(e,":")<2)return{host:e,isIPV6:!1};const t=function(e){let t=0;const n={error:!1,address:"",zone:""},i=[],o=[];let s=!1,a=!1,l=!1;function c(){if(o.length){if(!1===s){const e=r(o);if(void 0===e)return n.error=!0,!1;i.push(e)}o.length=0}return!0}for(let r=0;r<e.length;r++){const u=e[r];if("["!==u&&"]"!==u)if(":"!==u)if("%"===u){if(!c())break;s=!0}else o.push(u);else{if(!0===a&&(l=!0),!c())break;if(t++,i.push(":"),t>7){n.error=!0;break}r-1>=0&&":"===e[r-1]&&(a=!0)}}return o.length&&(s?n.zone=o.join(""):l?i.push(o.join("")):i.push(r(o))),n.address=i.join(""),n}(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+="%"+t.zone,n+="%25"+t.zone),{host:e,escapedHost:n,isIPV6:!0}}}function l(e,t){let n="",i=!0;const o=e.length;for(let s=0;s<o;s++){const r=e[s];"0"===r&&i?(s+1<=o&&e[s+1]===t||s+1===o)&&(n+=r,i=!1):(i=r===t,n+=r)}return n}function c(e,t){let n=0;for(let i=0;i<e.length;i++)e[i]===t&&n++;return n}const u=/^\.\.?\//u,h=/^\/\.(?:\/|$)/u,d=/^\/\.\.(?:\/|$)/u,m=/^\/?(?:.|\n)*?(?=\/|$)/u;e.exports={recomposeAuthority:function(e){const t=[];if(void 0!==e.userinfo&&(t.push(e.userinfo),t.push("@")),void 0!==e.host){let n=unescape(e.host);const i=s(n);if(i.isIPV4)n=i.host;else{const t=a(i.host);n=!0===t.isIPV6?`[${t.escapedHost}]`:e.host}t.push(n)}return"number"!=typeof e.port&&"string"!=typeof e.port||(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0},normalizeComponentEncoding:function(e,t){const n=!0!==t?escape:unescape;return void 0!==e.scheme&&(e.scheme=n(e.scheme)),void 0!==e.userinfo&&(e.userinfo=n(e.userinfo)),void 0!==e.host&&(e.host=n(e.host)),void 0!==e.path&&(e.path=n(e.path)),void 0!==e.query&&(e.query=n(e.query)),void 0!==e.fragment&&(e.fragment=n(e.fragment)),e},removeDotSegments:function(e){const t=[];for(;e.length;)if(e.match(u))e=e.replace(u,"");else if(e.match(h))e=e.replace(h,"/");else if(e.match(d))e=e.replace(d,"/"),t.pop();else if("."===e||".."===e)e="";else{const n=e.match(m);if(!n)throw new Error("Unexpected dot segment condition");{const i=n[0];e=e.slice(i.length),t.push(i)}}return t.join("")},normalizeIPv4:s,normalizeIPv6:a,stringArrayToHexStripped:r}},3837(e){"use strict";e.exports=JSON.parse('{"$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON AnySchema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}')},7216(e){"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/applicator","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/applicator":true},"$dynamicAnchor":"meta","title":"Applicator vocabulary meta-schema","type":["object","boolean"],"properties":{"prefixItems":{"$ref":"#/$defs/schemaArray"},"items":{"$dynamicRef":"#meta"},"contains":{"$dynamicRef":"#meta"},"additionalProperties":{"$dynamicRef":"#meta"},"properties":{"type":"object","additionalProperties":{"$dynamicRef":"#meta"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$dynamicRef":"#meta"},"propertyNames":{"format":"regex"},"default":{}},"dependentSchemas":{"type":"object","additionalProperties":{"$dynamicRef":"#meta"},"default":{}},"propertyNames":{"$dynamicRef":"#meta"},"if":{"$dynamicRef":"#meta"},"then":{"$dynamicRef":"#meta"},"else":{"$dynamicRef":"#meta"},"allOf":{"$ref":"#/$defs/schemaArray"},"anyOf":{"$ref":"#/$defs/schemaArray"},"oneOf":{"$ref":"#/$defs/schemaArray"},"not":{"$dynamicRef":"#meta"}},"$defs":{"schemaArray":{"type":"array","minItems":1,"items":{"$dynamicRef":"#meta"}}}}')},8226(e){"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/content","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/content":true},"$dynamicAnchor":"meta","title":"Content vocabulary meta-schema","type":["object","boolean"],"properties":{"contentEncoding":{"type":"string"},"contentMediaType":{"type":"string"},"contentSchema":{"$dynamicRef":"#meta"}}}')},518(e){"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/core","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/core":true},"$dynamicAnchor":"meta","title":"Core vocabulary meta-schema","type":["object","boolean"],"properties":{"$id":{"$ref":"#/$defs/uriReferenceString","$comment":"Non-empty fragments not allowed.","pattern":"^[^#]*#?$"},"$schema":{"$ref":"#/$defs/uriString"},"$ref":{"$ref":"#/$defs/uriReferenceString"},"$anchor":{"$ref":"#/$defs/anchorString"},"$dynamicRef":{"$ref":"#/$defs/uriReferenceString"},"$dynamicAnchor":{"$ref":"#/$defs/anchorString"},"$vocabulary":{"type":"object","propertyNames":{"$ref":"#/$defs/uriString"},"additionalProperties":{"type":"boolean"}},"$comment":{"type":"string"},"$defs":{"type":"object","additionalProperties":{"$dynamicRef":"#meta"}}},"$defs":{"anchorString":{"type":"string","pattern":"^[A-Za-z_][-A-Za-z0-9._]*$"},"uriString":{"type":"string","format":"uri"},"uriReferenceString":{"type":"string","format":"uri-reference"}}}')},4588(e){"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/format-annotation","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/format-annotation":true},"$dynamicAnchor":"meta","title":"Format vocabulary meta-schema for annotation results","type":["object","boolean"],"properties":{"format":{"type":"string"}}}')},5707(e){"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/meta-data","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/meta-data":true},"$dynamicAnchor":"meta","title":"Meta-data vocabulary meta-schema","type":["object","boolean"],"properties":{"title":{"type":"string"},"description":{"type":"string"},"default":true,"deprecated":{"type":"boolean","default":false},"readOnly":{"type":"boolean","default":false},"writeOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true}}}')},9547(e){"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/unevaluated","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/unevaluated":true},"$dynamicAnchor":"meta","title":"Unevaluated applicator vocabulary meta-schema","type":["object","boolean"],"properties":{"unevaluatedItems":{"$dynamicRef":"#meta"},"unevaluatedProperties":{"$dynamicRef":"#meta"}}}')},7082(e){"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/meta/validation","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/validation":true},"$dynamicAnchor":"meta","title":"Validation vocabulary meta-schema","type":["object","boolean"],"properties":{"type":{"anyOf":[{"$ref":"#/$defs/simpleTypes"},{"type":"array","items":{"$ref":"#/$defs/simpleTypes"},"minItems":1,"uniqueItems":true}]},"const":true,"enum":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/$defs/nonNegativeInteger"},"minLength":{"$ref":"#/$defs/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"maxItems":{"$ref":"#/$defs/nonNegativeInteger"},"minItems":{"$ref":"#/$defs/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"maxContains":{"$ref":"#/$defs/nonNegativeInteger"},"minContains":{"$ref":"#/$defs/nonNegativeInteger","default":1},"maxProperties":{"$ref":"#/$defs/nonNegativeInteger"},"minProperties":{"$ref":"#/$defs/nonNegativeIntegerDefault0"},"required":{"$ref":"#/$defs/stringArray"},"dependentRequired":{"type":"object","additionalProperties":{"$ref":"#/$defs/stringArray"}}},"$defs":{"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"$ref":"#/$defs/nonNegativeInteger","default":0},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}}}')},1678(e){"use strict";e.exports=JSON.parse('{"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://json-schema.org/draft/2020-12/schema","$vocabulary":{"https://json-schema.org/draft/2020-12/vocab/core":true,"https://json-schema.org/draft/2020-12/vocab/applicator":true,"https://json-schema.org/draft/2020-12/vocab/unevaluated":true,"https://json-schema.org/draft/2020-12/vocab/validation":true,"https://json-schema.org/draft/2020-12/vocab/meta-data":true,"https://json-schema.org/draft/2020-12/vocab/format-annotation":true,"https://json-schema.org/draft/2020-12/vocab/content":true},"$dynamicAnchor":"meta","title":"Core and Validation specifications meta-schema","allOf":[{"$ref":"meta/core"},{"$ref":"meta/applicator"},{"$ref":"meta/unevaluated"},{"$ref":"meta/validation"},{"$ref":"meta/meta-data"},{"$ref":"meta/format-annotation"},{"$ref":"meta/content"}],"type":["object","boolean"],"$comment":"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.","properties":{"definitions":{"$comment":"\\"definitions\\" has been replaced by \\"$defs\\".","type":"object","additionalProperties":{"$dynamicRef":"#meta"},"deprecated":true,"default":{}},"dependencies":{"$comment":"\\"dependencies\\" has been split and replaced by \\"dependentSchemas\\" and \\"dependentRequired\\" in order to serve their differing semantics.","type":"object","additionalProperties":{"anyOf":[{"$dynamicRef":"#meta"},{"$ref":"meta/validation#/$defs/stringArray"}]},"deprecated":true,"default":{}},"$recursiveAnchor":{"$comment":"\\"$recursiveAnchor\\" has been replaced by \\"$dynamicAnchor\\".","$ref":"meta/core#/$defs/anchorString","deprecated":true},"$recursiveRef":{"$comment":"\\"$recursiveRef\\" has been replaced by \\"$dynamicRef\\".","$ref":"meta/core#/$defs/uriReferenceString","deprecated":true}}}')},2079(e){"use strict";e.exports=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}')}},i={};function o(e){var t=i[e];if(void 0!==t)return t.exports;var s=i[e]={id:e,loaded:!1,exports:{}};return n[e].call(s.exports,s,s.exports,o),s.loaded=!0,s.exports}o.m=n,o.amdO={},o.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return o.d(t,{a:t}),t},o.d=(e,t)=>{for(var n in t)o.o(t,n)&&!o.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o.f={},o.e=e=>Promise.all(Object.keys(o.f).reduce((t,n)=>(o.f[n](e,t),t),[])),o.u=e=>e+".js",o.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),o.hmd=e=>((e=Object.create(e)).children||(e.children=[]),Object.defineProperty(e,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+e.id)}}),e),o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),e={},t="bio:",o.l=(n,i,s,r)=>{if(e[n])e[n].push(i);else{var a,l;if(void 0!==s)for(var c=document.getElementsByTagName("script"),u=0;u<c.length;u++){var h=c[u];if(h.getAttribute("src")==n||h.getAttribute("data-webpack")==t+s){a=h;break}}a||(l=!0,(a=document.createElement("script")).charset="utf-8",o.nc&&a.setAttribute("nonce",o.nc),a.setAttribute("data-webpack",t+s),a.src=n),e[n]=[i];var d=(t,i)=>{a.onerror=a.onload=null,clearTimeout(m);var o=e[n];if(delete e[n],a.parentNode&&a.parentNode.removeChild(a),o&&o.forEach(e=>e(i)),t)return t(i)},m=setTimeout(d.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=d.bind(null,a.onerror),a.onload=d.bind(null,a.onload),l&&document.head.appendChild(a)}},o.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;o.g.importScripts&&(e=o.g.location+"");var t=o.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var n=t.getElementsByTagName("script");if(n.length)for(var i=n.length-1;i>-1&&(!e||!/^http(s?):/.test(e));)e=n[i--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),o.p=e})(),(()=>{o.b="undefined"!=typeof document&&document.baseURI||self.location.href;var e={242:0,255:0,529:0};o.f.j=(t,n)=>{var i=o.o(e,t)?e[t]:void 0;if(0!==i)if(i)n.push(i[2]);else{var s=new Promise((n,o)=>i=e[t]=[n,o]);n.push(i[2]=s);var r=o.p+o.u(t),a=new Error;o.l(r,n=>{if(o.o(e,t)&&(0!==(i=e[t])&&(e[t]=void 0),i)){var s=n&&("load"===n.type?"missing":n.type),r=n&&n.target&&n.target.src;a.message="Loading chunk "+t+" failed.\n("+s+": "+r+")",a.name="ChunkLoadError",a.type=s,a.request=r,i[1](a)}},"chunk-"+t,t)}};var t=(t,n)=>{var i,s,[r,a,l]=n,c=0;if(r.some(t=>0!==e[t])){for(i in a)o.o(a,i)&&(o.m[i]=a[i]);l&&l(o)}for(t&&t(n);c<r.length;c++)s=r[c],o.o(e,s)&&e[s]&&e[s][0](),e[s]=0},n=self.webpackChunkbio=self.webpackChunkbio||[];n.forEach(t.bind(null,0)),n.push=t.bind(null,n.push.bind(n))})(),o.nc=void 0;var s={};(()=>{"use strict";o.r(s),o.d(s,{_package:()=>Ge,initAutoTests:()=>Ve,test:()=>Be,tests:()=>t.CN});var e=o(6082),t=o(5749);(0,t.L1)("_first",()=>{(0,t.t6)("_first",async()=>{})});var n=o(8070),i=o(8924),r=o(7362),a=o(1093);(0,t.L1)("Palettes",()=>{(0,t.t6)("testPaletteN",async()=>{await async function(){const e=a.A.Chromatogram;(0,n.E3)(e instanceof r.e,!0),(0,n.E3)(e instanceof a.A,!0)}()}),(0,t.t6)("testPaletteAA",async()=>{await async function(){const e=i.X.Lesk,t=i.X.RasMol,o=i.X.GrokGroups;(0,n.E3)(e instanceof r.e,!0),(0,n.E3)(t instanceof r.e,!0),(0,n.E3)(o instanceof r.e,!0),(0,n.E3)(e instanceof i.X,!0),(0,n.E3)(t instanceof i.X,!0),(0,n.E3)(o instanceof i.X,!0)}()}),(0,t.t6)("testPalettePtMe",async()=>{const e=i.X.GrokGroups.get("MeNle"),n=i.X.GrokGroups.get("MeA"),o=i.X.GrokGroups.get("MeG"),s=i.X.GrokGroups.get("MeF"),r=i.X.GrokGroups.get("L"),a=i.X.GrokGroups.get("A"),l=i.X.GrokGroups.get("G"),c=i.X.GrokGroups.get("F");(0,t.E3)(e,r),(0,t.E3)(n,a),(0,t.E3)(o,l),(0,t.E3)(s,c)})});var l=o(4328),c=o(2003),u=o(8312);class h{units;aligned;alphabet;alphabetSize;alphabetIsMultichar;separator;constructor(e,t,n,i,o,s){this.units=e,this.aligned=t,this.alphabet=n,this.alphabetSize=i,this.alphabetIsMultichar=o,this.separator=s}}async function d(t,n){const i=(await t()).getCol(n),o=await l.functions.call("Bio:detectMacromolecule",{col:i});if(o&&(i.semType=o),i.semType===e.SEMTYPE.MACROMOLECULE){const e=`Negative test detected semType='${i.semType}', units='${i.meta.units}'.`;throw new Error(e)}}async function m(n,i,o,s,r,a,u,h,d=null){const m=(await n()).col(i),p=await l.functions.call("Bio:detectMacromolecule",{col:m});p&&(m.semType=p),(0,t.E3)(m.semType,e.SEMTYPE.MACROMOLECULE),(0,t.E3)(m.meta.units,s),(0,t.E3)(m.getTag(c.gp.aligned),r),(0,t.E3)(m.getTag(c.gp.alphabet),a),d&&(0,t.E3)(m.getTag(c.gp.separator),d);const g=o.getSeqHandler(m);(0,t.E3)(g.getAlphabetSize(),u),(0,t.E3)(g.getAlphabetIsMultichar(),h),g.isHelm()||((0,t.E3)(g.aligned,r),(0,t.E3)(g.alphabet,a))}var p=o(4025);async function g(n,i){const o=e.Column.fromList(e.TYPE.STRING,"seq",n),s=await l.functions.call("Bio:detectMacromolecule",{col:o});s&&(o.semType=s),(0,t.E3)(o.semType,e.SEMTYPE.MACROMOLECULE);const r=i.getSeqHandler(o);return await r.refinerPromise,i.getSeqHandler(o),o}async function f(e,n,i=!1){const o=await g(e,n);(0,t.E3)(o.meta.units===c.Hi.BILN,!i,`Incorrectly detected as ${o.meta.units}`),(0,t.E3)(null!=o.temp[p.j.notationProvider],!i,"No notation provider for BILN")}async function y(e,n,i){const o=await g(e,i),s=i.getSeqHandler(o);for(let i=0;i<e.length;i++){const o=s.getHelm(i);(0,t.E3)(o===n[i],!0,`Incorrect HELM conversion for ${e[i]}: Expected ${n[i]} \n Got ${o}`)}const r=s.getConverter(c.Hi.HELM);for(let i=0;i<e.length;i++){const o=r(e[i]);(0,t.E3)(o===n[i],!0,`Incorrect HELM conversion for ${e[i]}: Expected ${n[i]} \n Got ${o}`)}}async function b(n,i,o){const s=e.Column.fromList(e.TYPE.STRING,"helm",n),r=e.DataFrame.fromColumns([s]);await r.meta.detectSemanticTypes(),await l.data.detectSemanticTypes(r),(0,t.E3)(s.semType===e.SEMTYPE.MACROMOLECULE,!0,`Incorrectly detected as ${s.semType}`),(0,t.E3)(s.meta.units===c.Hi.HELM,!0,`Incorrectly detected as ${s.meta.units}`);const a=o.getSeqHandler(s).getConverter(c.Hi.BILN);for(let e=0;e<n.length;e++){const o=a(n[e]);(0,t.E3)(o===i[e],!0,`Incorrect BILN conversion for ${n[e]}: Expected ${i[e]} \n Got ${o}`)}}const w=[{name:"Valid Biln",seqs:["A-C(1,3)-G-G-H-A-V-E-A-K-Y-L-V-C(3,3)-S.G-I-V-E-A-C(2,3)-C(1,3)-T-S-I-C(2,3)-S-L-Y-Q-L-E-N-Y-C(3,3)-Y","A-C(1,3)-G-G-H-A-V-E-A-K-Y-L-V-C(3,3)-S.G-I-V-E-A-C(2,3)-C(1,3)-T-S-I-C(2,3)-S-L-Y-Q-L-E-N-Y-C(3,3)-Y","C-C(1,3)-S-W-P-A-R-C(2,3)-L-H-Q-D-L-C(3,3)-NH2.C(1,1)(2,2)(3,3)","C-C(1,3)-S-W-P-A-R-C(2,3)-L-H-Q-D-L-C(3,3)-NH2.[C](1,1)(2,2)(3,3)","D-T-H-F-P-I-C(1,3)-I-F-C(2,3)-C(3,3)-G-C(2,3)-C(4,3)-H-R-S-K-C(3,3)-G-M-C(4,3)-C(1,3)-K-T"],negative:!1},{name:"Simple Separator Neg",seqs:["meI/hHis/Aca/N/T/dE/Thr_PO3H2/Aca/D-Tyr_Et/Tyr_ab-dehydroMe/dV/E/N/D-Orn/D-aThr//Phe_4Me","meI/hHis/Aca/Cys_SEt/T/dK/Thr_PO3H2/Aca/Tyr_PO3H2/D-Chg/dV/Phe_ab-dehydro/N/D-Orn/D-aThr//Phe_4Me","Lys_Boc/hHis/Aca/Cys_SEt/T/dK/Thr_PO3H2/Aca/Tyr_PO3H2/D-Chg/dV/Thr_PO3H2/N/D-Orn/D-aThr//Phe_4Me","meI/hHis/Aca/Cys_SEt/T/dK/Thr_PO3H2/Aca/Tyr_PO3H2/D-Chg/dV/Thr_PO3H2/N/D-Orn/D-aThr//Phe_4Me","meI/hHis/Aca/N/T/dK/Thr_PO3H2/Aca/D-Tyr_Et/Tyr_ab-dehydroMe/dV/Chg/N/D-Orn/D-aThr//Phe_4Me"],negative:!0},{name:"Valid Biln without cyclization",seqs:["meI-hHis-Aca-N-T-dE-Thr_PO3H2-Aca-[D-Tyr_Et]-[Tyr_ab-dehydroMe]-dV-E-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-[D-Chg]-dV-[Phe_ab-dehydro]-N-[D-Orn]-[D-aThr]--Phe_4Me","Lys_Boc-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-[D-Chg]-dV-Thr_PO3H2-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-[D-Chg]-dV-Thr_PO3H2-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-N-T-dK-Thr_PO3H2-Aca-[D-Tyr_Et]-[Tyr_ab-dehydroMe]-dV-Chg-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-N-T-dK-Thr_PO3H2-Aca-[D-Tyr_Et]-Tyr_Bn-dV-E-N-dV---Phe_4Me","meI-hHis-Aca-N-T-dK-Thr_PO3H2-Aca-[D-Tyr_Et]-Aze-dV-E-N-dV---Phe_4Me","meI-hHis-Aca-N-T-dK-Thr_PO3H2-Aca-[D-Tyr_Et]-meQ-dV-E-N-dV---Phe_4Me"],negative:!1}],v=[{name:"Linear",biln:["meI-hHis-Aca-N-T-dE-Thr_PO3H2-Aca-[D-Tyr_Et]-[Tyr_ab-dehydroMe]-dV-E-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-[D-Chg]-dV-[Phe_ab-dehydro]-N-[D-Orn]-[D-aThr]--Phe_4Me","Lys_Boc-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-[D-Chg]-dV-Thr_PO3H2-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-[D-Chg]-dV-Thr_PO3H2-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-N-T-dK-Thr_PO3H2-Aca-[D-Tyr_Et]-[Tyr_ab-dehydroMe]-dV-Chg-N-[D-Orn]-[D-aThr]--Phe_4Me"],helm:["PEPTIDE1{[meI].[hHis].[Aca].N.T.[dE].[Thr_PO3H2].[Aca].[D-Tyr_Et].[Tyr_ab-dehydroMe].[dV].E.N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$","PEPTIDE1{[meI].[hHis].[Aca].[Cys_SEt].T.[dK].[Thr_PO3H2].[Aca].[Tyr_PO3H2].[D-Chg].[dV].[Phe_ab-dehydro].N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$","PEPTIDE1{[Lys_Boc].[hHis].[Aca].[Cys_SEt].T.[dK].[Thr_PO3H2].[Aca].[Tyr_PO3H2].[D-Chg].[dV].[Thr_PO3H2].N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$","PEPTIDE1{[meI].[hHis].[Aca].[Cys_SEt].T.[dK].[Thr_PO3H2].[Aca].[Tyr_PO3H2].[D-Chg].[dV].[Thr_PO3H2].N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$","PEPTIDE1{[meI].[hHis].[Aca].N.T.[dK].[Thr_PO3H2].[Aca].[D-Tyr_Et].[Tyr_ab-dehydroMe].[dV].[Chg].N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$"]},{name:"Cyclic",biln:["C-C(1,3)-S-W-P-A-R-C(2,3)-L-H-Q-D-L-C(3,3)-NH2.[C](1,1)(2,2)(3,3)","D-T-H-F-P-I-C(1,3)-I-F-C(2,3)-C(3,3)-G-C(2,3)-C(4,3)-H-R-S-K-C(3,3)-G-M-C(4,3)-C(1,3)-K-T","L-C(1,3)-G-S-H-L-V-E-A-L-Y-L-V-C(2,3)-G.G-I-V-E-Q-C(3,3)-C(1,3)-T-S-I-C(3,3)-S-L-Y-Q-L-E-N-Y-C(2,3)-N","H-Aib-E-G-T-F-T-S-D(2,3)-V-S-S-Y-L-E-G-Q-A-A-K(1,3)-E-F-I-A-W-L-V-R-G-R-G.C(2,3)-gGlu-G-G(1,2)","F(4,2).dI(1,1)(3,3)-Trp_Ome-Asp_OMe-Cys_Bn-meG-Phe_3Cl-dD-T-dI(4,3)-T-dK-aG-3Pal-xiIle-meD-Ala_tBu(1,2).L(2,1)-Pro_4Me3OH-S-NMe2Abz-Q-3Pal-xiIle-D-Hyp-Ala_tBu-dI(3,3)-Trp_Ome-Asp_OMe-N-meG-Phe_34diCl-Phe_34diCl(2,2)"],helm:["PEPTIDE1{C.C.S.W.P.A.R.C.L.H.Q.D.L.C.[NH2]}|PEPTIDE2{C}$PEPTIDE1,PEPTIDE2,14:R3-1:R3|PEPTIDE1,PEPTIDE2,8:R3-1:R2|PEPTIDE1,PEPTIDE2,2:R3-1:R1$$$V2.0","PEPTIDE1{D.T.H.F.P.I.C.I.F.C.C.G.C.C.H.R.S.K.C.G.M.C.C.K.T}$PEPTIDE1,PEPTIDE1,10:R3-13:R3|PEPTIDE1,PEPTIDE1,11:R3-19:R3|PEPTIDE1,PEPTIDE1,14:R3-22:R3|PEPTIDE1,PEPTIDE1,7:R3-23:R3$$$V2.0","PEPTIDE1{L.C.G.S.H.L.V.E.A.L.Y.L.V.C.G}|PEPTIDE2{G.I.V.E.Q.C.C.T.S.I.C.S.L.Y.Q.L.E.N.Y.C.N}$PEPTIDE1,PEPTIDE2,2:R3-7:R3|PEPTIDE2,PEPTIDE2,6:R3-11:R3|PEPTIDE1,PEPTIDE2,14:R3-20:R3$$$V2.0","PEPTIDE1{H.[Aib].E.G.T.F.T.S.D.V.S.S.Y.L.E.G.Q.A.A.K.E.F.I.A.W.L.V.R.G.R.G}|PEPTIDE2{C.[gGlu].G.G}$PEPTIDE1,PEPTIDE2,9:R3-1:R3|PEPTIDE1,PEPTIDE2,20:R3-4:R2$$$V2.0","PEPTIDE1{F}|PEPTIDE2{[dI].[Trp_Ome].[Asp_OMe].[Cys_Bn].[meG].[Phe_3Cl].[dD].T.[dI].T.[dK].[aG].[3Pal].[xiIle].[meD].[Ala_tBu]}|PEPTIDE3{L.[Pro_4Me3OH].S.[NMe2Abz].Q.[3Pal].[xiIle].D.[Hyp].[Ala_tBu].[dI].[Trp_Ome].[Asp_OMe].N.[meG].[Phe_34diCl].[Phe_34diCl]}$PEPTIDE1,PEPTIDE2,1:R2-9:R3|PEPTIDE2,PEPTIDE2,1:R1-16:R2|PEPTIDE2,PEPTIDE3,1:R3-11:R3|PEPTIDE3,PEPTIDE3,1:R1-17:R2$$$V2.0"]}],C=[{name:"Linear",biln:["meI-hHis-Aca-N-T-dE-Thr_PO3H2-Aca-[D-Tyr_Et]-[Tyr_ab-dehydroMe]-dV-E-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-[D-Chg]-dV-[Phe_ab-dehydro]-N-[D-Orn]-[D-aThr]--Phe_4Me","Lys_Boc-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-[D-Chg]-dV-Thr_PO3H2-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-[D-Chg]-dV-Thr_PO3H2-N-[D-Orn]-[D-aThr]--Phe_4Me","meI-hHis-Aca-N-T-dK-Thr_PO3H2-Aca-[D-Tyr_Et]-[Tyr_ab-dehydroMe]-dV-Chg-N-[D-Orn]-[D-aThr]--Phe_4Me"],helm:["PEPTIDE1{[meI].[hHis].[Aca].N.T.[dE].[Thr_PO3H2].[Aca].[D-Tyr_Et].[Tyr_ab-dehydroMe].[dV].E.N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$","PEPTIDE1{[meI].[hHis].[Aca].[Cys_SEt].T.[dK].[Thr_PO3H2].[Aca].[Tyr_PO3H2].[D-Chg].[dV].[Phe_ab-dehydro].N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$","PEPTIDE1{[Lys_Boc].[hHis].[Aca].[Cys_SEt].T.[dK].[Thr_PO3H2].[Aca].[Tyr_PO3H2].[D-Chg].[dV].[Thr_PO3H2].N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$","PEPTIDE1{[meI].[hHis].[Aca].[Cys_SEt].T.[dK].[Thr_PO3H2].[Aca].[Tyr_PO3H2].[D-Chg].[dV].[Thr_PO3H2].N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$","PEPTIDE1{[meI].[hHis].[Aca].N.T.[dK].[Thr_PO3H2].[Aca].[D-Tyr_Et].[Tyr_ab-dehydroMe].[dV].[Chg].N.[D-Orn].[D-aThr].*.[Phe_4Me]}$$$$"]},{name:"Cyclic",biln:["C-C(3,3)-S-W-P-A-R-C(2,3)-L-H-Q-D-L-C(1,3)-NH2.C(1,3)(2,2)(3,1)","D-T-H-F-P-I-C(4,3)-I-F-C(1,3)-C(2,3)-G-C(1,3)-C(3,3)-H-R-S-K-C(2,3)-G-M-C(3,3)-C(4,3)-K-T","L-C(1,3)-G-S-H-L-V-E-A-L-Y-L-V-C(3,3)-G.G-I-V-E-Q-C(2,3)-C(1,3)-T-S-I-C(2,3)-S-L-Y-Q-L-E-N-Y-C(3,3)-N","H-Aib-E-G-T-F-T-S-D(1,3)-V-S-S-Y-L-E-G-Q-A-A-K(2,3)-E-F-I-A-W-L-V-R-G-R-G.C(1,3)-gGlu-G-G(2,2)","F(1,2).dI(2,1)(3,3)-Trp_Ome-Asp_OMe-Cys_Bn-meG-Phe_3Cl-dD-T-dI(1,3)-T-dK-aG-3Pal-xiIle-meD-Ala_tBu(2,2).L(4,1)-Pro_4Me3OH-S-NMe2Abz-Q-3Pal-xiIle-D-Hyp-Ala_tBu-dI(3,3)-Trp_Ome-Asp_OMe-N-meG-Phe_34diCl-Phe_34diCl(4,2)"],helm:["PEPTIDE1{C.C.S.W.P.A.R.C.L.H.Q.D.L.C.[NH2]}|PEPTIDE2{C}$PEPTIDE1,PEPTIDE2,14:R3-1:R3|PEPTIDE1,PEPTIDE2,8:R3-1:R2|PEPTIDE1,PEPTIDE2,2:R3-1:R1$$$V2.0","PEPTIDE1{D.T.H.F.P.I.C.I.F.C.C.G.C.C.H.R.S.K.C.G.M.C.C.K.T}$PEPTIDE1,PEPTIDE1,10:R3-13:R3|PEPTIDE1,PEPTIDE1,11:R3-19:R3|PEPTIDE1,PEPTIDE1,14:R3-22:R3|PEPTIDE1,PEPTIDE1,7:R3-23:R3$$$V2.0","PEPTIDE1{L.C.G.S.H.L.V.E.A.L.Y.L.V.C.G}|PEPTIDE2{G.I.V.E.Q.C.C.T.S.I.C.S.L.Y.Q.L.E.N.Y.C.N}$PEPTIDE1,PEPTIDE2,2:R3-7:R3|PEPTIDE2,PEPTIDE2,6:R3-11:R3|PEPTIDE1,PEPTIDE2,14:R3-20:R3$$$V2.0","PEPTIDE1{H.[Aib].E.G.T.F.T.S.D.V.S.S.Y.L.E.G.Q.A.A.K.E.F.I.A.W.L.V.R.G.R.G}|PEPTIDE2{C.[gGlu].G.G}$PEPTIDE1,PEPTIDE2,9:R3-1:R3|PEPTIDE1,PEPTIDE2,20:R3-4:R2$$$V2.0","PEPTIDE1{F}|PEPTIDE2{[dI].[Trp_Ome].[Asp_OMe].[Cys_Bn].[meG].[Phe_3Cl].[dD].T.[dI].T.[dK].[aG].[3Pal].[xiIle].[meD].[Ala_tBu]}|PEPTIDE3{L.[Pro_4Me3OH].S.[NMe2Abz].Q.[3Pal].[xiIle].D.[Hyp].[Ala_tBu].[dI].[Trp_Ome].[Asp_OMe].N.[meG].[Phe_34diCl].[Phe_34diCl]}$PEPTIDE1,PEPTIDE2,1:R2-9:R3|PEPTIDE2,PEPTIDE2,1:R1-16:R2|PEPTIDE2,PEPTIDE3,1:R3-11:R3|PEPTIDE3,PEPTIDE3,1:R1-17:R2$$$V2.0"]}];async function A(t){const n=e.Column.fromList(e.TYPE.STRING,"col1",t);if(await l.functions.call("Bio:detectMacromolecule",{col:n}),n.semType===e.SEMTYPE.MACROMOLECULE){const e=`Negative test detected semType='${n.semType}', units='${n.meta.units}'.`;throw new Error(e)}}async function T(n,i,o,s,r,a,u,h=null){const d=e.Column.fromList(e.TYPE.STRING,"seq",n),m=await l.functions.call("Bio:detectMacromolecule",{col:d});m&&(d.semType=m),(0,t.E3)(d.semType,e.SEMTYPE.MACROMOLECULE),(0,t.E3)(d.meta.units,o),(0,t.E3)(d.getTag(c.gp.aligned),s),(0,t.E3)(d.getTag(c.gp.alphabet),r),h&&(0,t.E3)(d.getTag(c.gp.separator),h);const p=i.getSeqHandler(d);(0,t.E3)(p.getAlphabetSize(),a),(0,t.E3)(p.getAlphabetIsMultichar(),u),p.isHelm()||((0,t.E3)(p.aligned,s),(0,t.E3)(p.alphabet,r))}async function E(e,t,n){const i=await e(),o=[];for(const s of i.columns.names())if(s in t){const i=t[s];try{await m(e,s,n,i.units,i.aligned,i.alphabet,i.alphabetSize,i.alphabetIsMultichar,i.separator)}catch(e){const t=e.toString();o.push(`Positive col '${s}' failed: ${t}`)}}else try{await d(e,s)}catch(e){const t=e.toString();o.push(`Negative col '${s}' failed: ${t}`)}if(o.length>0)throw new Error(o.join("\n"))}(0,t.L1)("detectors",()=>{let n;(0,t.gM)(async()=>{n=await(0,u.Q)()});const i={negEmpty:{csv:"id,col1\n1,\n2,\n3,\n4,\n5,",neg:["col1"]},negNum1:{csv:"col1\n1\n2\n3",neg:["col1"]},negNum2:{csv:"col1\n4\n5\n6\n7",neg:["col1"]},negNum3:{csv:"col1\n8\n9\n10\n11\n12",neg:["col1"]},negSmiles:{csv:"col1\nCCCCN1C(=O)CN=C(c2cc(F)ccc12)C3CCCCC3\nC1CCCCC1\nCCCCCC",neg:["col1"]},negSmilesWithSquareBrackets:{csv:"col1\nCl.c1ccc2nc3ccccc3cc2c1\nOc1cccc2cc3ccccc3cc12\n[SeH]c1ccc2ccccc2c1",neg:["col1"]},negFastaUnSingleChar:{csv:"col1\nAlanine\nCysteine\nAspartic acid\nGlutamic acid\nPhenylalanine",neg:["col1"]},fastaMsaSameLength:{csv:"seq\nFWPHEYFWPHEYYV\nYNRQWYVYNRQWYV\nMKPSEYVMKPSEYV",pos:{seq:new h(c.Hi.FASTA,"SEQ.MSA",c.YI.PT,20,!1,void 0)}},fastaExtSameLength:{csv:"seq\nFW[Ac]PHEYFWPH\nYN[Re]VYNRQWYV\n[Me]EYVMPS[Et]",pos:{seq:new h(c.Hi.FASTA,"SEQ",c.YI.UN,16,!0,void 0)}},fastaMsaExtSameLength:{csv:"seq\nFW[Ac]PHEY[Re]WPH\nYN[Re]VYNR[Ac]WYV\n[Me]EYVMPSFW[Me]H",pos:{seq:new h(c.Hi.FASTA,"SEQ.MSA",c.YI.UN,14,!0,void 0)}},sepSameLength:{csv:"seq\nAca-A-A-A-A-A-A-A-A-A-A-A-A-A-C-G-NH2\nAca-A-A-A-A-A-A-A-A-A-A-A-A-A-C-G-NH2\nAca-A-A-A-A-A-A-A-A-A-A-A-A-A-C-G-NH2",pos:{seq:new h(c.Hi.SEPARATOR,"SEQ.MSA",c.YI.UN,5,!0,"-")}},sepMsaSameLength:{csv:"seq\nAca-A-A-A-A-A-A-A-A-A-A-A-A-A-Aca-G-NH2\nAca-A-Aca-A-A-A-meI-A-A-A-A-A-Aca-G-NH2\nAca-A-A-A-A-A-A-A-A-A-A-A-A-A-Aca-G-NH2",pos:{seq:new h(c.Hi.SEPARATOR,"SEQ",c.YI.UN,5,!0,"-")}},helmSameLength:{csv:"seq\nPEPTIDE1{Ac(1).A.A.A.A.A.A.A.A.A.A.A.A.A.C(1).G.NH2}$$$$\nPEPTIDE1{Ab(1).Y.V.K.H.P.F.W.R.W.Y.A.A.A.C(1).G.NH2}$$$$\nPEPTIDE1{Ad(1).S.W.Y.C.K.H.P.M.W.A.A.A.A.C(1)-G-NH2}$$$$",pos:{seq:new h(c.Hi.HELM,null,null,19,void 0,void 0)}},fastaNonDigitAlphabet:{csv:'flagC\n"NMe-pyridazineH"\n"Pyrrolo[2,3-c]pyridazineH"',neg:["flagC"]}};for(const[o,s]of Object.entries(i))(0,t.t6)(`csvData2-${o}`,async()=>{const t=(r=o,async()=>{const t=i[r].csv,n=e.DataFrame.fromCsv(t);return await l.data.detectSemanticTypes(n),n});var r;for(const e of s.neg??[])await d(t,e);for(const[e,i]of Object.entries(s.pos??{}))await m(t,e,n,i.units,i.aligned,i.alphabet,i.alphabetSize,i.alphabetIsMultichar,i.separator)});const o=new class{csvFastaDna1="seq\nACGTCACGTC\nCAGTGTCAGTGT\nTTCAACTTCAAC";fastaRna1="seq\nACGUCACGUC\nCAGUGUCAGUGU\nUUCAACUUCAAC";fastaPt1="seq\nFWPHEY\nYNRQWYV\nMKPSEYV";fastaUn="seq\n[meI][hHis][Aca]NT[dE][Thr_PO3H2][Aca]DN\n[meI][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca][Tyr_PO3H2][Aca]\n[Lys_Boc][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca][Tyr_PO3H2][Aca]";sepDna="seq\nA*C*G*T*C*A*C*G*T*C\nC*A*G*T*G*T*C*A*G*T*G*T\nT*T*C*A*A*C*T*T*C*A*A*C";sepRna="seq\nA*C*G*U*C*A*C*G*U*C\nC*A*G*U*G*U*C*A*G*U*G*U\nU*U*C*A*A*C*U*U*C*A*A*C";sepPt="seq\nF-W-P-H-E-Y-F-W-P-H-E-Y\nY-N-R-Q-W-Y-V-Y-N-R-Q-W-Y-V\nM-K-P-S-E-Y-V-M-K-P-S-E-Y-V";sepUn1="seq\nabc-dfgg-abc1-cfr3-rty-wert-cfr3-rty-wert\nrut12-her2-rty-wert-abc-abc1-dfgg-abc-abc1-dfgg\nrut12-rty-her2-abc-cfr3-wert-rut12-cfr3-wert-rut12";sepUn2="seq\nabc/dfgg/abc1/cfr3/rty/wert/abc/dfgg/abc1/cfr3/rty/wert\nrut12/her2/rty/wert//abc/abc1/dfgg/rut12/her2/rty/wert//abc/abc1/dfgg\nrut12/rty/her2/abc/cfr3//wert/rut12/rut12/rty/her2/abc/cfr3//wert/rut12";sepMsaDna1="seq\nA-C--G-T--C-T-A-C--G-T--C-T\nC-A-C--T--G-T-C-A-C--T--G-T\nA-C-C-G-T-A-C-T-A-C-C-G-T-A-C-T";sepMsaUnWEmpty="seq\nm1-M-m3-mon4-mon5-N-T-MON8-N9-m1-M-m3-mon4-mon5-N-T-MON8-N9\nm1-mon2-m3-mon4-mon5-Num--MON8-N9-m1-mon2-m3-mon4-mon5-Num--MON8-N9\n\nmon1-M-mon3-mon4-mon5---MON8-N9-mon1-M-mon3-mon4-mon5---MON8-N9";sepComplex="seq\nAca-F-K(AEEA-AEEA-R-Ac)-L-mF-V-Y-mNle-D-W-N-mF-Aca-G-NH2\nAca-F-K(AEEA-ARRA-W-Ac)-L-mF-V-Y-mNle-D-W-N-mF-Aca-G-NH2\nAca-F-K(AEEA-AEEA-Ac)-L-mF-V-Y-mNle-D-W-N-mF-Aca-G-NH2";fastaMsaDna1="seq\nAC-GT-CTAC-GT-CT\nCAC-T-GTCAC-T-GT\nACCGTACTACCGTACT";fastaMsaPt1="seq\nFWR-WYV-KHPFWR-WYV-KHP\nYNR-WYV-KHPYNR-WYV-KHP\nMWRSWY-CKHPMWRSWY-CKHP"},s={fastaPtCsv:"System:AppData/Bio/samples/FASTA_PT.csv",msaComplex:"System:AppData/Bio/samples/MSA.csv",fastaCsv:"System:AppData/Bio/samples/FASTA.csv",helmCsv:"System:AppData/Bio/samples/HELM.csv",peptidesComplex:"System:AppData/Bio/tests/peptides_complex_msa.csv",peptidesSimple:"System:AppData/Bio/tests/peptides_simple_msa.csv",testDemogCsv:"System:AppData/Bio/tests/testDemog.csv",testHelmCsv:"System:AppData/Bio/tests/testHelm.csv",testIdCsv:"System:AppData/Bio/tests/testId.csv",testSmilesCsv:"System:AppData/Bio/tests/testSmiles.csv",testSmiles2Csv:"System:AppData/Bio/tests/testSmiles2.csv",testSmilesShort:"System:AppData/Bio/tests/testSmilesShort.csv",testActivityCliffsCsv:"System:AppData/Bio/tests/testActivityCliffs.csv",testCerealCsv:"System:AppData/Bio/tests/testCereal.csv",testUnichemSources:"System:AppData/Bio/tests/testUnichemSources.csv",testDmvOffices:"System:AppData/Bio/tests/testDmvOffices.csv",testAlertCollection:"System:AppData/Bio/tests/testAlertCollection.csv",testSpgi100:"System:AppData/Bio/tests/testSpgi100.csv",testSpgi:"System:AppData/Bio/tests/SPGI-derived.csv",testUrl:"System:AppData/Bio/tests/testUrl.csv",fasta_negative_words:"System:AppData/Bio/tests/fasta_negative_words.csv"},r={};function a(e,t=p){return async()=>(e in r||(r[e]=(async()=>await t(s[e]))().catch(t=>{throw delete r[e],t})),r[e])}async function p(t){const n=await l.dapi.files.readAsText(t);return e.DataFrame.fromCsv(n)}const g=t=>async()=>{const n=o[t],i=e.DataFrame.fromCsv(n);return await l.data.detectSemanticTypes(i),i};(0,t.t6)("NegativeStartEnd",async()=>{await A(["START","END"])}),(0,t.t6)("NegativeStartEndIntermediate",async()=>{await A(["START","END","INTERMEDIATE"])}),(0,t.t6)("FastaDna1",async()=>{await m(g("csvFastaDna1"),"seq",n,c.Hi.FASTA,"SEQ",c.YI.DNA,4,!1)}),(0,t.t6)("FastaRna1",async()=>{await m(g("fastaRna1"),"seq",n,c.Hi.FASTA,"SEQ",c.YI.RNA,4,!1)}),(0,t.t6)("FastaPt1",async()=>{await m(g("fastaPt1"),"seq",n,c.Hi.FASTA,"SEQ",c.YI.PT,20,!1)}),(0,t.t6)("FastaPtGaps",()=>T(["FW-PH-EYY","FYNRQWYV-","FKP-Q-SEYV"],n,c.Hi.FASTA,"SEQ",c.YI.PT,20,!1)),(0,t.t6)("FastaPtGapsMsa",()=>T(["FW-PH-EYY","FYNRQWYV-","FKP-Q-SEY"],n,c.Hi.FASTA,"SEQ.MSA",c.YI.PT,20,!1)),(0,t.t6)("FastaUn",async()=>{await m(g("fastaUn"),"seq",n,c.Hi.FASTA,"SEQ.MSA",c.YI.UN,12,!0)}),(0,t.t6)("FastaMsaDna1",async()=>{await m(g("fastaMsaDna1"),"seq",n,c.Hi.FASTA,"SEQ.MSA",c.YI.DNA,4,!1)}),(0,t.t6)("FastaMsaPt1",async()=>{await m(g("fastaMsaPt1"),"seq",n,c.Hi.FASTA,"SEQ.MSA",c.YI.PT,20,!1)}),(0,t.t6)("SepDna",async()=>{await m(g("sepDna"),"seq",n,c.Hi.SEPARATOR,"SEQ",c.YI.DNA,4,!1,"*")}),(0,t.t6)("SepRna",async()=>{await m(g("sepRna"),"seq",n,c.Hi.SEPARATOR,"SEQ",c.YI.RNA,4,!1,"*")}),(0,t.t6)("SepPt",async()=>{await m(g("sepPt"),"seq",n,c.Hi.SEPARATOR,"SEQ",c.YI.PT,20,!1,"-")}),(0,t.t6)("SepUn1",async()=>{await m(g("sepUn1"),"seq",n,c.Hi.SEPARATOR,"SEQ",c.YI.UN,8,!0,"-")}),(0,t.t6)("SepUn2",async()=>{await m(g("sepUn2"),"seq",n,c.Hi.SEPARATOR,"SEQ",c.YI.UN,9,!0,"/")}),(0,t.t6)("SepMsaN1",async()=>{await m(g("sepMsaDna1"),"seq",n,c.Hi.SEPARATOR,"SEQ.MSA",c.YI.DNA,4,!1,"-")}),(0,t.t6)("SepMsaUnWEmpty",async()=>{await m(g("sepMsaUnWEmpty"),"seq",n,c.Hi.SEPARATOR,"SEQ.MSA",c.YI.UN,14,!0)}),(0,t.t6)("SepComplex",async()=>{await m(g("sepComplex"),"seq",n,c.Hi.SEPARATOR,"SEQ",c.YI.UN,17,!0)}),(0,t.t6)("samplesFastaCsv",async()=>{await E(a("fastaCsv"),{Sequence:new h(c.Hi.FASTA,"SEQ",c.YI.PT,20,!1)},n)});for(const e of w)(0,t.t6)(e.name,async()=>{await f(e.seqs,n,e.negative)});(0,t.t6)("samplesPeptidesComplex",async()=>{await E(a("peptidesComplex"),{},n)}),(0,t.t6)("samplesMsaComplex",async()=>{await E(a("msaComplex"),{MSA:new h(c.Hi.SEPARATOR,"SEQ.MSA",c.YI.UN,161,!0,"/")},n)}),(0,t.t6)("samplesIdCsv",async()=>{await E(a("testIdCsv"),{},n)}),(0,t.t6)("samplesSarSmallCsv",async()=>{await E(a("testSmilesCsv"),{},n)}),(0,t.t6)("samplesHelmCsv",async()=>{await E(a("helmCsv"),{HELM:new h(c.Hi.HELM,null,null,160,!0)},n)}),(0,t.t6)("samplesTestHelmCsv",async()=>{await E(a("testHelmCsv"),{"HELM string":new h(c.Hi.HELM,null,null,7,!0)},n)}),(0,t.t6)("samplesTestDemogCsv",async()=>{await E(a("testDemogCsv"),{},n)}),(0,t.t6)("samplesTestSmiles2Csv",async()=>{await E(a("testSmiles2Csv"),{},n)}),(0,t.t6)("samplesTestSmilesShort",async()=>{await E(a("testSmilesShort"),{},n)}),(0,t.t6)("samplesTestActivityCliffsNegativeSmiles",async()=>{await E(a("testActivityCliffsCsv"),{},n)}),(0,t.t6)("samplesFastaPtCsv",async()=>{await E(a("fastaPtCsv"),{sequence:new h(c.Hi.FASTA,"SEQ",c.YI.PT,20,!1)},n)}),(0,t.t6)("samplesTestCerealCsv",async()=>{await E(a("testCerealCsv"),{},n)}),(0,t.t6)("samplesTestUnichemSources",async()=>{await E(a("testUnichemSources"),{},n)}),(0,t.t6)("samplesTestDmvOffices",async()=>{await E(a("testDmvOffices"),{},n)}),(0,t.t6)("samplesTestAlertCollection",async()=>{await E(a("testAlertCollection"),{},n)}),(0,t.t6)("samplesTestSpgi",async()=>{await E(a("testSpgi"),{},n)}),(0,t.t6)("samplesTestSpgi100",async()=>{await E(a("testSpgi100"),{},n)}),(0,t.t6)("samplesTestUrl",async()=>{await E(a("testUrl"),{},n)}),(0,t.t6)("samplesFastaNegativeWords",async()=>{await E(a("fasta_negative_words"),{},n)})}),(0,t.L1)("detectors.weak-and-likely",()=>{let n;(0,t.gM)(async()=>{n=await(0,u.Q)()});const i={fastaDnaWeak1:"id,colName\n1,TTTTTTTTTT\n2,TTTTTTTTTT\n3,TTTTTTTTTT\n4,TTTTTTTTTT",fastaDnaWeak1LikelyName:"id,seq\n1,TTTTTTT\n2,TTTTTTT\n3,TTTTTTT\n4,TTTTTTT",fastaRnaWeak1:"id,colName\n1,UUUUUUUUUU\n2,UUUUUUUUUU\n3,UUUUUUUUUU\n4,UUUUUUUUUU",fastaRnaWeak1LikelyName:"id,seq\n1,UUUUUUU\n2,UUUUUUU\n3,UUUUUUU\n4,UUUUUUU",fastaPtWeak1:"id,colName\n1,SLSLSPGKSLSLSPGK\n2,SLSLSPGKSLSLSPGK\n3,SLSLSPGKSLSLSPGK\n4,SLSLSPGKSLSLSPGK",fastaPtWeak1LikelyName:"id,seq\n1,SLSLSPGKSLSLSPGK\n2,SLSLSPGKSLSLSPGK\n3,SLSLSPGKSLSLSPGK\n4,SLSLSPGKSLSLSPGK",fastaUn1:"id,colName\n1,word\n2,other\n3,some\n4,another",fastaUn1LikelyName:"id,seq\n1,word\n2,other\n3,some\n4,another",fastaUn2LikelyName:'protein\nBoombastic\nMegafantastic\n"just-a-random-thought,oy!"',fastaUnMsa1LikelyName:"id,seq\n1,word\n2,male\n3,bare\n4,core"},o=t=>async()=>{const n=i[t],o=e.DataFrame.fromCsv(n);return await l.data.detectSemanticTypes(o),o};(0,t.t6)("fastaDnaWeak1",async()=>{await d(o("fastaDnaWeak1"),"colName")}),(0,t.t6)("fastaDnaWeak1LikelyName",async()=>{await m(o("fastaDnaWeak1LikelyName"),"seq",n,c.Hi.FASTA,"SEQ.MSA",c.YI.DNA,4,!1)}),(0,t.t6)("fastaRnaWeak1",async()=>{await d(o("fastaRnaWeak1"),"colName")}),(0,t.t6)("fastaRnaWeak1LikelyName",async()=>{await m(o("fastaRnaWeak1LikelyName"),"seq",n,c.Hi.FASTA,"SEQ.MSA",c.YI.RNA,4,!1)}),(0,t.t6)("fastaPtWeak1",async()=>{await d(o("fastaPtWeak1"),"colName")}),(0,t.t6)("fastaPtWeak1LikelyName",async()=>{await m(o("fastaPtWeak1LikelyName"),"seq",n,c.Hi.FASTA,"SEQ.MSA",c.YI.PT,20,!1)}),(0,t.t6)("fastaUn1",async()=>{await d(o("fastaUn1"),"colName")}),(0,t.t6)("fastaUn1LikelyName",async()=>{await d(o("fastaUn1LikelyName"),"seq")}),(0,t.t6)("fastaUn2LikelyName",async()=>{await d(o("fastaUn2LikelyName"),"protein")}),(0,t.t6)("fastaUnMsa1LikelyName",async()=>{await d(o("fastaUnMsa1LikelyName"),"seq")})}),(0,t.L1)("detectorsBenchmark",()=>{let n,i;async function o(o,r,a,l,u,h){return await async function(o){const d=await(async()=>{const t=function(t,n,i,o,s){let r;switch(t){case c.Hi.FASTA:r=e=>{let t="";for(let n=0;n<e.length;n++){const i=e[n];t+=1==i.length?i:`[${i}]`}return t};break;case c.Hi.SEPARATOR:r=(e,t)=>e.join(t);break;default:throw new Error(`Not supported notation '${t}'.`)}const a=(e,t)=>{const n=new Array(t);for(let i=0;i<t;i++)n[i]=e[Math.floor(Math.random()*e.length)];return r(n,s)},l=Array(o);for(let e=0;e<o;e++)l[e]=a(n,i);return e.Column.fromStrings("seq",l)}(r,[...(0,c.Qf)(a)],l,u,h),n=i.prepare({col:t});return s(n),n})(),m=Date.now(),p=s(d),g=Date.now();(function(e,i){const o=n.getSeqHandler(e);(0,t.E3)(e.semType===i.semType,!0),(0,t.E3)(o.notation===i.notation,!0),(0,t.E3)(o.alphabet===i.alphabet,!0),(0,t.E3)(o.separator===i.separator,!0)})(p,{semType:e.SEMTYPE.MACROMOLECULE,notation:r,alphabet:a,separator:h});const f=g-m;if(f>o){const e=`ET ${f} ms is more than max allowed ${o} ms.`;throw console.error(e),new Error(e)}return console.log(`ET ${f} ms is OK.`),f}(o)}function s(e){e.callSync();const t=e.getOutputParamValue(),n=e.inputs.col;return t&&(n.semType=t),n}(0,t.gM)(async()=>{n=await(0,u.Q)();const t=e.Func.find({package:"Bio",name:"detectMacromolecule"});i=t[0];const o=e.Column.fromStrings("seq",["ACGT","ACGT","ACGT"]);await i.prepare({col:o}).call()}),(0,t.t6)("fastaDnaShorts50Few50",async()=>{await o(20,c.Hi.FASTA,c.YI.DNA,50,50)}),(0,t.t6)("fastaDnaShorts50Many1E6",async()=>{await o(20,c.Hi.FASTA,c.YI.DNA,50,1e6)}),(0,t.t6)("fastaDnaLong1e6Few50",async()=>{await o(20,c.Hi.FASTA,c.YI.DNA,1e6,50)}),(0,t.t6)("separatorDnaShorts50Few50",async()=>{await o(20,c.Hi.SEPARATOR,c.YI.DNA,50,50,"/")}),(0,t.t6)("separatorDnaShorts50Many1E6",async()=>{await o(20,c.Hi.SEPARATOR,c.YI.DNA,50,1e6,"/")}),(0,t.t6)("separatorDnaLong1e6Few50",async()=>{await o(20,c.Hi.SEPARATOR,c.YI.DNA,1e6,50,"/")})});var S=o(608),M=o(1619);async function x(n,i){const o=e.DataFrame.fromCsv(n);await l.data.detectSemanticTypes(o);const s=e.DataFrame.fromCsv(i),r=o.getCol("seq");(0,t.E3)(r.semType,e.SEMTYPE.MACROMOLECULE);const a=s.getCol("seq"),c=await(0,S.eE)(o,r,!0);(0,t.J6)(c.toList(),a.toList())}(0,t.L1)("MSA",async()=>{let n;async function i(i,o,s,r,a,u){const h=e.DataFrame.fromCsv(i);await l.data.detectSemanticTypes(h);const d=e.DataFrame.fromCsv(o).getCol("seq"),m=h.getCol("seq");(0,t.E3)(m.semType,e.SEMTYPE.MACROMOLECULE),(0,t.E3)(m.meta.units,s),a&&(0,t.E3)(m.getTag(c.gp.alphabet),a);const p=await(0,M.D)({col:m,engine:u?"PepSeA":void 0,engineParams:u?{method:u}:void 0},n);(0,t.E3)(p.semType,e.SEMTYPE.MACROMOLECULE),(0,t.E3)(p.meta.units,r),(0,t.E3)(p.getTag(c.gp.aligned),"SEQ.MSA"),a&&(0,t.E3)(p.getTag(c.gp.alphabet),a),(0,t.J6)(p.toList(),d.toList())}(0,t.gM)(async()=>{n=await(0,u.Q)()}),(0,t.t6)("isCorrect",async()=>{await x("seq\nFWRWYVKHP\nYNRWYVKHP\nMWRSWYCKHP","seq\nFWR-WYVKHP\nYNR-WYVKHP\nMWRSWYCKHP")}),(0,t.t6)("isCorrectLong",async()=>{await x("seq\nFWRWYVKHPFWRWYVKHPFWRWYVKHPFWRWYVKHPFWRWYVKHPFWRWYVKHPFWRWYVKHPFWRWYVKHP\nYNRWYVKHPYNRWYVKHPYNRWYVKHPYNRWYVKHPYNRWYVKHPYNRWYVKHPYNRWYVKHPYNRWYVKHP\nMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHP","seq\nFWR-WYVKHPFWR-WYVKHPFWR-WYVKHPFWR-WYVKHPFWR-WYVKHPFWR-WYVKHPFWR-WYVKHPFWR-WYVKHP\nYNR-WYVKHPYNR-WYVKHPYNR-WYVKHPYNR-WYVKHPYNR-WYVKHPYNR-WYVKHPYNR-WYVKHPYNR-WYVKHP\nMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHPMWRSWYCKHP")}),(0,t.t6)("isCorrectHelm",async()=>{await i("seq\n PEPTIDE1{meI.hHis.Aca.N.T.dE.Thr_PO3H2}$$$$\n PEPTIDE1{meI.Aca.N.T.dE.Thr_PO3H2}$$$$\n PEPTIDE1{hHis.Aca.N.T.dE.Thr_PO3H2}$$$$","seq\n meI.hHis.Aca.N.T.dE.Thr_PO3H2\n .meI.Aca.N.T.dE.Thr_PO3H2\n .hHis.Aca.N.T.dE.Thr_PO3H2",c.Hi.HELM,c.Hi.SEPARATOR,void 0,"mafft")},{timeout:8e4,skipReason:"Fails in docker"}),(0,t.t6)("isCorrectHelmLong",async()=>{await i("seq\n PEPTIDE1{meI.hHis.Aca.N.T.dE.Thr_PO3H2.Aca.D-Tyr_Et.dV.E.N.D-Orn.D-aThr.Phe_4Me.Thr_PO3H2}$$$$\n PEPTIDE1{meI.hHis.Aca.Cys_SEt.T.dK.Tyr_PO3H2.D-Chg.dV.Phe_ab-dehydro.N.D-Orn.D-aThr.Phe_4Me}$$$$\n PEPTIDE1{Lys_Boc.hHis.Aca.Cys_SEt.T.dK.Tyr_PO3H2.D-Chg.dV.Thr_PO3H2.N.D-Orn.D-aThr.Phe_4Me}$$$$","seq\n meI.hHis.Aca.N.T.dE.Thr_PO3H2.Aca.D-Tyr_Et.dV.E.N.D-Orn.D-aThr.Phe_4Me.Thr_PO3H2\n meI.hHis.Aca.Cys_SEt.T.dK..Tyr_PO3H2.D-Chg.dV.Phe_ab-dehydro.N.D-Orn.D-aThr.Phe_4Me.\n Lys_Boc.hHis.Aca.Cys_SEt.T.dK..Tyr_PO3H2.D-Chg.dV.Thr_PO3H2.N.D-Orn.D-aThr.Phe_4Me.",c.Hi.HELM,c.Hi.SEPARATOR,void 0,"mafft")},{timeout:8e4,skipReason:"Fails in docker"}),(0,t.t6)("isCorrectSeparator",async()=>{await i("seq\n F-W-P-H-E-Y\n Y-N-R-Q-W-Y-V\n M-K-P-S-E-Y-V","seq\n FWPHEY-\n YNRQWYV\n MKPSEYV",c.Hi.SEPARATOR,c.Hi.FASTA,c.YI.PT)}),(0,t.t6)("isCorrectSeparatorLong",async()=>{await i("seq\n M-I-E-V-F-L-F-G-I-V-L-G-L-I-P-I-T-L-A-G-L-F-V-T-A-Y-L-Q-Y-R-R-G-D-Q-L-D-L\n M-M-E-L-V-L-K-T-I-I-G-P-I-V-V-G-V-V-L-R-I-V-D-K-W-L-N-K-D-K\n M-D-R-T-D-E-V-S-N-H-T-H-D-K-P-T-L-T-W-F-E-E-I-F-E-E-Y-H-S-P-F-H-N","seq\n MIEV-FLFGIVLGLIPITLAGLFVTAYLQYRRGDQLDL\n MMEL-VLKTII-GPIVVGVVLRIVDKWLNKDK------\n MDRTDEVSNHTHDKPTLTWFEEIFEEYHSPFHN-----",c.Hi.SEPARATOR,c.Hi.FASTA,c.YI.PT)})});var P=o(1991),L=o.n(P),I=o(7278),_=o(4971);function N(e){return(t=e)&&void 0!==t.onRendered&&void 0!==t.invalidate&&void 0!==t.awaitRendered?e:null;var t}var R=o(6642);async function $(t){const n=await async function(e){return await Ge.files.readAsText(e)}(t),i=e.DataFrame.fromCsv(n);return i.name=t.replace(".csv",""),i}async function O(e,n=5e3){await(0,t.cb)(0),await(0,t.PE)(e.onAfterDrawContent,()=>{},()=>{e.invalidate()},n);const i=e.columns.length;for(let t=0;t<i;++t){const n=e.columns.byIndex(t);if(n){const t=e.cell(n.name,0),[i,o,s]=(0,R.BG)(t),r=N(s.rendererBack);r&&await r.awaitRendered()}}}var H=o(4139),D=o(4356);async function F(e,n){const i=(0,c.J9)(e);console.debug(`Bio: tests: splitters: src=${JSON.stringify(e)}, res=${JSON.stringify(i)} .`),(0,t.J6)(L().count(0).take(i.length).map(e=>i.getOriginal(e)).toArray(),n)}async function k(e,n){const i=(0,I.qp)(e);console.debug(`Bio: tests: splitters: src=${JSON.stringify(e)}, res=${JSON.stringify(i)} .`),(0,t.J6)(L().count(0).take(i.length).map(e=>i.getOriginal(e)).toArray(),n)}(0,t.L1)("splitters",async()=>{(0,t.gM)(async()=>{}),(0,t.Pl)(async()=>{});const e=["M[MeI]YKETLL[MeF]PKTDFPMRGGL[MeA]",["M","MeI","Y","K","E","T","L","L","MeF","P","K","T","D","F","P","M","R","G","G","L","MeA"]],n=["[meI][Pip][dK][Thr_PO3H2][L-hArg(Et,Et)][D-Tyr_Et][Tyr_ab-dehydroMe][dV]EN[D-Orn][D-aThr][Phe_4Me]",["meI","Pip","dK","Thr_PO3H2","L-hArg(Et,Et)","D-Tyr_Et","Tyr_ab-dehydroMe","dV","E","N","D-Orn","D-aThr","Phe_4Me"]],i=["PEPTIDE1{meI.hHis.Aca.N.T.dE.Thr_PO3H2.Aca.D-Tyr_Et.Tyr_ab-dehydroMe.dV.E.N.D-Orn.D-aThr.Phe_4Me}$$$",["meI","hHis","Aca","N","T","dE","Thr_PO3H2","Aca","D-Tyr_Et","Tyr_ab-dehydroMe","dV","E","N","D-Orn","D-aThr","Phe_4Me"]],o=["PEPTIDE1{meI.hHis.Aca.N.T.dK.Thr_PO3H2.Aca.D-Tyr_Et.D-Dap.dV.E.N.pnG.Phe_4Me}$$$",["meI","hHis","Aca","N","T","dK","Thr_PO3H2","Aca","D-Tyr_Et","D-Dap","dV","E","N","pnG","Phe_4Me"]],s=["PEPTIDE1{[meI].[hHis].[Aca].N.T.[dK].[Thr_PO3H2].[Aca].[D-Tyr_Et].[D-Dap].[dV].E.N.[pnG].[Phe_4Me]}$$$",["meI","hHis","Aca","N","T","dK","Thr_PO3H2","Aca","D-Tyr_Et","D-Dap","dV","E","N","pnG","Phe_4Me"]],r=["RNA1{R(U)P.R(T)P.R(G)P.R(C)P.R(A)}$$$$",["R","U","P","R","T","P","R","G","P","R","C","P","R","A"]],a=["RNA1{P.R(U)P.R(T)}$$$$",["P","R","U","P","R","T"]],l=["RNA1{P.R(U).P.R(T)}$$$$",["P","R","U","P","R","T"]];(0,t.t6)("fastaMulti",async()=>{await F(e[0],e[1])}),(0,t.t6)("fastaFromHelm",async()=>{await F(n[0],n[1])}),(0,t.t6)("helm1",async()=>{await k(i[0],i[1])}),(0,t.t6)("helm2",async()=>{await k(o[0],o[1])}),(0,t.t6)("helm3-multichar",async()=>{await k(s[0],s[1])}),(0,t.t6)("testHelm1",async()=>{await k(r[0],r[1])}),(0,t.t6)("testHelm2",async()=>{await k(a[0],a[1])}),(0,t.t6)("testHelm3",async()=>{await k(l[0],l[1])})}),(0,t.L1)("splitters",()=>{let n,i,o;(0,t.gM)(async()=>{n=await(0,u.Q)(),i=await(0,_.pj)(),o=await(0,D.u)(),await i.loadMonomerLibForTests()}),(0,t.Pl)(async()=>{await(0,D.E)(o),await i.loadMonomerLib(!0)}),(0,t.t6)("splitToMonomers",async()=>{const e=await l.dapi.files.readCsv("System:AppData/Bio/samples/MSA.csv"),n=e.getCol("MSA"),i=await l.functions.call("Bio:detectMacromolecule",{col:n});i&&(n.semType=i),n.setTag(c.gp.aligned,H.gN);const o=await l.functions.call("Bio:splitToMonomersTopMenu",{table:e,sequence:n});(0,t.E3)(o.columns.names().includes("17"),!0),await l.data.detectSemanticTypes(o);const s=l.shell.addTableView(o);await O(s.grid),(0,t.E3)(s.grid.dataFrame.id,e.id)}),(0,t.t6)("getHelmMonomers",async()=>{const t=e.DataFrame.fromCsv("HELM,Activity\nPEPTIDE1{hHis.N.T}$$$,5.30751\nPEPTIDE1{hHis.Aca.Cys_SEt}$$$,5.72388\n");await l.data.detectSemanticTypes(t);const n=["hHis","Aca","Cys_SEt","N","T"],i=t.getCol("HELM"),o=await l.functions.call("Bio:getHelmMonomers",{sequence:i}),s=n.filter(e=>!o.includes(e)),r=o.filter(e=>!n.includes(e));if(s.length>0||r.length){const e=[];throw s.length>0&&e.push(`Missed monomers ${JSON.stringify(s)}.`),r.length>0&&e.push(`Unexpected monomers ${JSON.stringify(r)}.`),new Error(e.join(" "))}})});var G=o(8604);(0,t.L1)("monomerLibraries",()=>{let e,i=null;(0,t.gM)(async()=>{e=await(0,_.pj)(),i=(0,D.u)()}),(0,t.Pl)(async()=>{await(0,D.E)(i)}),(0,t.t6)("default",async()=>{await(0,D.E)({exclude:[],explicit:[],duplicateMonomerPreferences:{}}),await e.loadMonomerLib(!0);const n=e.getMonomerLib();(0,t.E3)(n.getPolymerTypes().length>0,!0)}),(0,t.t6)("forTests",async()=>{await e.loadMonomerLibForTests(),function(e,t){const i=t,o=e.getSummaryObj();for(const e in i)i[e]||delete i[e];for(const e in o)o[e]||delete o[e];if(0==Object.keys(i).length&&0!=Object.keys(o).length)throw new Error("Expected empty monomer lib, actual is not.");if(0!=Object.keys(i).length&&0==Object.keys(o).length)throw new Error("Expected non-empty monomer lib, actual is empty.");try{(0,n.Xk)(o,i),(0,n.Xk)(i,o)}catch(e){throw new Error(`Expected monomer lib ${JSON.stringify(i)} does not match actual ${JSON.stringify(o)}.`)}}(e.getMonomerLib(),G.V)}),(0,t.t6)("empty",async()=>{const n=await(0,D.u)();let i=await e.getAvaliableLibraryNames();0===i.length&&(await e.refreshValidLibraryLists(),i=await e.getAvaliableLibraryNames()),n.exclude=i,n.explicit=[],await(0,D.E)(n),await e.loadMonomerLib(!0);const o=e.getMonomerLib().getPolymerTypes();(0,t.E3)(0===o.length,!0)}),(0,t.t6)("override",async()=>{const n={symbol:"over1",name:"Test override monomer 1",molfile:"",author:"Test Author",id:0,rgroups:[],smiles:"",polymerType:"PEPTIDE",monomerType:"Backbone",createDate:null},i=e.getMonomerLib(),o=i.getMonomer(n.polymerType,n.symbol);(0,t.E3)(null==o,!0,`Unexpectedly found monomer '${n.symbol}' `);const s=i.override({[n.polymerType]:{[n.symbol]:n}},"test").getMonomer(n.polymerType,n.symbol);s&&(s.lib=void 0),(0,t.Xk)(s,n)})});var B=o(7389),V=o(1757),U=o.n(V),q=o(1858),W=o(6873),Y=o(5433);async function j(n,i){const o=n(),s=e.DataFrame.fromColumns(o);await l.data.detectSemanticTypes(s);const r=Date.now(),a=(s.columns.byName("MSA"),l.shell.addTableView(s));await O(a.grid),(0,t.E3)(a.grid.dataFrame.id,s.id);const c=Date.now()-r;console.log(`Performance test: ${i}: ${c}ms`)}(0,t.L1)("renderers",()=>{let n;(0,t.gM)(async()=>{n=await(0,u.Q)()}),(0,t.t6)("long sequence performance ",async()=>{await j(()=>(0,W.dW)(1e4),"Long sequences")}),(0,t.t6)("many sequence performance",async()=>{await j(W.fD,"Many sequences")}),(0,t.t6)("rendererMacromoleculeFasta",async()=>{await async function(){const n=await l.dapi.files.readAsText("System:AppData/Bio/samples/FASTA.csv"),i=e.DataFrame.fromCsv(n),o=i.getCol("Sequence"),s=await l.functions.call("Bio:detectMacromolecule",{col:o});s&&(o.semType=s);const r=l.shell.addTableView(i);await l.data.detectSemanticTypes(i),await O(r.grid),(0,t.E3)(r.grid.dataFrame.id,i.id);const a=o.getTag(e.TAGS.CELL_RENDERER);(0,t.E3)(a,"sequence")}()}),(0,t.t6)("rendererMacromoleculeSeparator",async()=>{await async function(){const n=await l.dapi.files.readAsText("System:AppData/Bio/samples/SEPARATOR_PT.csv"),i=e.DataFrame.fromCsv(n),o=i.getCol("sequence"),s=await l.functions.call("Bio:detectMacromolecule",{col:o});s&&(o.semType=s);const r=l.shell.addTableView(i);await l.data.detectSemanticTypes(i),await O(r.grid),(0,t.E3)(r.grid.dataFrame.id,i.id);const a=o.getTag(e.TAGS.CELL_RENDERER);(0,t.E3)(a,"sequence")}()}),(0,t.t6)("rendererMacromoleculeDifference",async()=>{await async function(){const n=e.Column.fromStrings("SequencesDiff",["meI/hHis/Aca/N/T/dK/Thr_PO3H2/Aca#D-Tyr_Et/Tyr_ab-dehydroMe/meN/E/N/dV"]);n.meta.units=c.Hi.SEPARATOR,n.setTag(c.gp.separator,"/"),n.setTag(c.gp.aligned,"SEQ"),n.setTag(c.gp.alphabet,"UN"),n.setTag(c.gp.alphabetIsMultichar,"true"),n.semType=H.uF.MACROMOLECULE_DIFFERENCE;const i=e.DataFrame.fromColumns([n]),o=l.shell.addTableView(i);await l.data.detectSemanticTypes(i),await O(o.grid),(0,t.E3)(o.grid.dataFrame.id,i.id);const s=n.getTag(e.TAGS.CELL_RENDERER);(0,t.E3)(s,H.uF.MACROMOLECULE_DIFFERENCE)}()}),(0,t.t6)("afterMsa",async()=>{await async function(){const i=await l.dapi.files.readAsText("System:AppData/Bio/samples/FASTA.fasta"),o=(await l.functions.call("Bio:importFasta",{fileContent:i}))[0],s=o.getCol("sequence"),r=await l.functions.call("Bio:detectMacromolecule",{col:s});r&&(s.semType=r);const a=l.shell.addTableView(o);await l.data.detectSemanticTypes(o),console.log("Bio: tests/renderers/afterMsa, table view"),await O(a.grid),(0,t.E3)(a.grid.dataFrame.id,o.id),console.log(`Bio: tests/renderers/afterMsa, src before test semType="${s.semType}", units="${s.meta.units}", cell.renderer="${s.getTag(e.TAGS.CELL_RENDERER)}"`),(0,t.E3)(s.semType,e.SEMTYPE.MACROMOLECULE),(0,t.E3)(s.meta.units,c.Hi.FASTA),(0,t.E3)(s.getTag(c.gp.aligned),"SEQ"),(0,t.E3)(s.getTag(c.gp.alphabet),c.YI.PT),(0,t.E3)(s.getTag(e.TAGS.CELL_RENDERER),"sequence");const u=await(0,M.D)({col:s},n);await O(a.grid),(0,t.E3)(a.grid.dataFrame.id,o.id),(0,t.E3)(u.semType,e.SEMTYPE.MACROMOLECULE),(0,t.E3)(u.meta.units,c.Hi.FASTA),(0,t.E3)(u.getTag(c.gp.aligned),"SEQ.MSA"),(0,t.E3)(u.getTag(c.gp.alphabet),c.YI.PT),(0,t.E3)(u.getTag(e.TAGS.CELL_RENDERER),"sequence"),n.getSeqHandler(u)}()}),(0,t.t6)("afterConvert",async()=>{await async function(){const i=await l.dapi.files.readAsText("System:AppData/Bio/samples/FASTA_PT.csv"),o=e.DataFrame.fromCsv(i),s=o.getCol("sequence"),r=await l.functions.call("Bio:detectMacromolecule",{col:s});r&&(s.semType=r);const a=l.shell.addTableView(o);await l.data.detectSemanticTypes(o);const u=await(0,Y.r)(s,n,c.Hi.SEPARATOR,"/");await O(a.grid),(0,t.E3)(a.grid.dataFrame.id,o.id);const h=u.getTag(e.TAGS.CELL_RENDERER);(0,t.E3)(h,"sequence"),n.getSeqHandler(u)}()}),(0,t.t6)("afterConvertToHelm",async()=>{await async function(){const i=await l.dapi.files.readCsv("System:AppData/Bio/samples/FASTA_PT.csv"),o=l.shell.addTableView(i);await O(o.grid),await i.meta.detectSemanticTypes(),await l.data.detectSemanticTypes(i);const s=i.getCol("sequence"),r=n.getSeqHandler(s).convert(c.Hi.HELM);i.columns.add(r),await O(o.grid),(0,t.E3)(r.getTag(e.TAGS.CELL_RENDERER),"helm")}()}),(0,t.t6)("selectRendererBySemType",async()=>{await async function(){const n=e.Column.fromStrings("SequencesDiff",["meI/hHis/Aca/N/T/dK/Thr_PO3H2/Aca#D-Tyr_Et/Tyr_ab-dehydroMe/meN/E/N/dV"]);n.meta.units=c.Hi.SEPARATOR,n.setTag(c.gp.separator,"/"),n.setTag(c.gp.aligned,"SEQ"),n.setTag(c.gp.alphabet,"UN"),n.setTag(c.gp.alphabetIsMultichar,"true"),n.semType=H.uF.MACROMOLECULE_DIFFERENCE;const i=e.DataFrame.fromColumns([n]);l.shell.addTableView(i),await(0,t.cb)(100);const o=n.getTag(e.TAGS.CELL_RENDERER);if("MacromoleculeDifference"!==o)throw new Error(`Units 'separator', separator '/' and semType 'MacromoleculeDifference' have been manually set on column but after df was added as table, view renderer has set to '${o}' instead of correct 'MacromoleculeDifference'.`)}()}),(0,t.t6)("scatterPlotTooltip",async()=>{await async function(){const n=e.DataFrame.fromCsv(i);n.currentRowIdx=0;const o=l.shell.addTableView(n);await n.meta.detectSemanticTypes(),await l.data.detectSemanticTypes(n);const s=n.plot.scatter({x:"x",y:"y"});o.dockManager.dock(s,e.DOCK_TYPE.RIGHT,null),await Promise.all([(0,t.PE)(s.onAfterDrawScene,()=>{},()=>{s.invalidateCanvas()},1e3),O(o.grid,500)]);const r=s.root.getBoundingClientRect(),a=s.worldToScreen(1,0),c=new MouseEvent("mousemove",{cancelable:!0,bubbles:!0,view:window,button:0,clientX:r.left+a.x,clientY:r.top+a.y}),u=U()(s.root).find("canvas").get()[0];await(0,t.PE)(e.debounce((0,q.fromEvent)(u,"mousemove"),200),()=>{Ge.logger.debug(`Test: event, currentRowIdx=${n.currentRowIdx}`),(0,t.E3)(U()(B.tooltip.root).find("div table.d4-row-tooltip-table tr td canvas").length,1),(0,t.E3)(s.hitTest(a.x,a.y),1)},()=>{u.dispatchEvent(c)},500),await O(o.grid,500)}()});const i="seq,x,y\nACGGTGTCGT,0,0\nCGGTATCCCT,1,0\nCTCGGCATGC,2,0\n"});var K=o(819);(0,t.L1)("renderers: monomerPlacer",()=>{let n,i;(0,t.gM)(async()=>{n=await(0,_.pj)(),i=await(0,D.u)(),await n.loadMonomerLibForTests()}),(0,t.Pl)(async()=>{await(0,D.E)(i),await n.loadMonomerLib(!0)});const o={splitter:{csv:"id,seq\nid1,m1-M-m3-mon4-mon5-N-T-MON8-N9\nid2,m1-mon2-m3-mon4-mon5-Num-MON8-N9\nid3,mon1-M-mon3-mon4-mon5-MON8-N9\n",testList:[{src:{row:0,x:-1},tgt:{pos:null}},{src:{row:1,x:0},tgt:{pos:null}},{src:{row:1,x:5},tgt:{pos:0}},{src:{row:1,x:6},tgt:{pos:0}},{src:{row:1,x:26},tgt:{pos:1}},{src:{row:1,x:160},tgt:{pos:6}},{src:{row:1,x:190},tgt:{pos:7}},{src:{row:2,x:140},tgt:{pos:5}},{src:{row:2,x:145},tgt:{pos:5}}]},splitterMsa:{csv:"id,seq\nid1,m1-M-m3-mon4-mon5-N-T-MON8-N9\nid2,m1-mon2-m3-mon4-mon5-Num--MON8-N9\nid3,\nid4,mon1-M-mon3-mon4-mon5---MON8-N9\n",testList:[{src:{row:0,x:-1},tgt:{pos:null}},{src:{row:1,x:0},tgt:{pos:null}},{src:{row:1,x:1},tgt:{pos:null}},{src:{row:1,x:4},tgt:{pos:null}},{src:{row:1,x:5},tgt:{pos:0}},{src:{row:1,x:37},tgt:{pos:0}},{src:{row:1,x:38},tgt:{pos:1}},{src:{row:1,x:170},tgt:{pos:5}},{src:{row:1,x:200},tgt:{pos:5}},{src:{row:2,x:20},tgt:{pos:null}},{src:{row:3,x:170},tgt:{pos:5}},{src:{row:3,x:200},tgt:{pos:5}},{src:{row:3,x:297},tgt:{pos:null}}]},fastaMsa:{csv:"id,seq\nid1,QQYNIYPLT\nid2,QQWSSFPYT\nid3,\nid3,QHIRE--LT\n",testList:[{src:{row:1,x:-1},tgt:{pos:null}},{src:{row:1,x:0},tgt:{pos:null}},{src:{row:1,x:1},tgt:{pos:null}},{src:{row:1,x:19},tgt:{pos:0}},{src:{row:1,x:170},tgt:{pos:8}},{src:{row:1,x:171},tgt:{pos:8}},{src:{row:2,x:5},tgt:{pos:null}},{src:{row:3,x:170},tgt:{pos:8}},{src:{row:3,x:181},tgt:{pos:null}}]}};for(const[n,i]of Object.entries(o))(0,t.t6)(`getPosition-${n}`,async()=>{const t=e.DataFrame.fromCsv(i.csv);await l.data.detectSemanticTypes(t);const n=t.getCol("seq"),o=new K.Jy(null,n,Ge.logger,3,()=>({font:"12px monospace",fontCharWidth:7,separatorWidth:12,monomerToShort:c.zS}));await o.init();const s=i.testList;for(let e=0;e<n.length;++e)o.getCellMonomerLengths(e,1e4);const r=[];for(const[e,t]of L().enumerate(s)){const t={pos:o.getPosition(e.src.row,e.src.x,1e4)};e.tgt.pos!=t.pos&&r.push(`Test src ${JSON.stringify(e.src)} expected tgt ${JSON.stringify(e.tgt)}, but get ${JSON.stringify({res:t})}`)}if(r.length>0)throw new Error("Test failed error(s):\n"+r.join(", \n"))});const s=[10,20,30,40,50,60],r={left:{x:3,tgt:null},c0left:{x:10,tgt:0},c0mid:{x:12,tgt:0},c0right:{x:19,tgt:0},c1left:{x:20,tgt:1},c2right:{x:39,tgt:2},c4left:{x:50,tgt:4},c4right:{x:59,tgt:4},max:{x:60,tgt:null},right:{x:65,tgt:null}};for(const[e,n]of Object.entries(r))(0,t.t6)("hitBounds-"+e,async()=>{const e=(0,K.Bb)(s,n.x);(0,t.E3)(e,n.tgt)});const a={mono1:{src:{csv:"seq\nm1/m2/m3/m4/m5/m6/m7/m8/m9\nn1/m2/n3/m4/n5/m6/n7/m8/n9\nm1/n2/m3/n4/m5/n6/m7/n8/m9\n"},tgt:{lengths:[5,31,57,83,109,135,161,187,213,239]}},monoWithGaps:{src:{csv:"seq\nm1/m2/m3/m4/m5/m6//m8/m9\nn1/m2/n3/m4/n5/m6//m8/n9\nm1/n2/m3/n4/m5/n6/m7/n8/m9\n"},tgt:{lengths:[5,31,57,83,109,135,161,187,213,239]}},monoWithGapColumn:{src:{csv:"seq\nm1/m2/m3/m4/m5/m6//m8/m9\nn1/m2/n3/m4/n5/m6//m8/n9\nm1/n2/m3/n4/m5///n8/m9\n"},tgt:{lengths:[5,31,57,83,109,135,161,180,206,232]}}};for(const[n,i]of Object.entries(a))(0,t.t6)(`getCellMonomerLengths-${n}`,async()=>{const n=e.DataFrame.fromCsv(i.src.csv);await l.data.detectSemanticTypes(n);const o=n.getCol("seq"),s=new K.Jy(null,o,Ge.logger,3,()=>({fontCharWidth:7,font:"12px monospace",separatorWidth:12,monomerToShort:c.zS}));await s.init();const r=s.getCellMonomerLengths(0,1e3)[1];(0,t.J6)(r,i.tgt.lengths)})}),(0,t.L1)("converters",()=>{let n,i;(0,t.gM)(async()=>{n=await(0,u.Q)()}),function(e){e.fastaPt="fastaPt",e.separatorPt="separatorPt",e.helmPt="helmPt",e.fastaDna="fastaDna",e.separatorDna="separatorDna",e.helmDna="helmDna",e.fastaRna="fastaRna",e.separatorRna="separatorRna",e.helmRna="helmRna",e.fastaGaps="fastaGaps",e.separatorGaps="separatorGaps",e.helmGaps="helmGaps",e.fastaUn="fastaUn",e.separatorUn="separatorUn",e.helmUn="helmUn",e.helmLoneDeoxyribose="helmLoneDeoxyribose",e.helmLoneRibose="helmLoneRibose",e.helmLonePhosphorus="helmLonePhosphorus",e.fastaLoneDeoxyribose="fastaLoneDeoxyribose",e.fastaLoneRibose="fastaLoneRibose",e.fastaLonePhosphorus="fastaLonePhosphorus"}(i||(i={}));const o={[i.fastaPt]:"seq\nFWPHEYFWPHEY\nYNRQWYVYNRQWYV\nMKPSEYVMKPSEYV",[i.separatorPt]:"seq\nF-W-P-H-E-Y-F-W-P-H-E-Y\nY-N-R-Q-W-Y-V-Y-N-R-Q-W-Y-V\nM-K-P-S-E-Y-V-M-K-P-S-E-Y-V",[i.helmPt]:"seq\nPEPTIDE1{F.W.P.H.E.Y.F.W.P.H.E.Y}$$$$\nPEPTIDE1{Y.N.R.Q.W.Y.V.Y.N.R.Q.W.Y.V}$$$$\nPEPTIDE1{M.K.P.S.E.Y.V.M.K.P.S.E.Y.V}$$$$",[i.fastaDna]:"seq\nACGTCACGTC\nCAGTGTCAGTGT\nTTCAACTTCAAC",[i.separatorDna]:"seq\nA/C/G/T/C/A/C/G/T/C\nC/A/G/T/G/T/C/A/G/T/G/T\nT/T/C/A/A/C/T/T/C/A/A/C",[i.helmDna]:"seq\nRNA1{d(A)p.d(C)p.d(G)p.d(T)p.d(C)p.d(A)p.d(C)p.d(G)p.d(T)p.d(C)p}$$$$\nRNA1{d(C)p.d(A)p.d(G)p.d(T)p.d(G)p.d(T)p.d(C)p.d(A)p.d(G)p.d(T)p.d(G)p.d(T)p}$$$$\nRNA1{d(T)p.d(T)p.d(C)p.d(A)p.d(A)p.d(C)p.d(T)p.d(T)p.d(C)p.d(A)p.d(A)p.d(C)p}$$$$",[i.fastaRna]:"seq\nACGUCACGUC\nCAGUGUCAGUGU\nUUCAACUUCAAC",[i.separatorRna]:"seq\nA*C*G*U*C*A*C*G*U*C\nC*A*G*U*G*U*C*A*G*U*G*U\nU*U*C*A*A*C*U*U*C*A*A*C",[i.helmRna]:"seq\nRNA1{r(A)p.r(C)p.r(G)p.r(U)p.r(C)p.r(A)p.r(C)p.r(G)p.r(U)p.r(C)p}$$$$\nRNA1{r(C)p.r(A)p.r(G)p.r(U)p.r(G)p.r(U)p.r(C)p.r(A)p.r(G)p.r(U)p.r(G)p.r(U)p}$$$$\nRNA1{r(U)p.r(U)p.r(C)p.r(A)p.r(A)p.r(C)p.r(U)p.r(U)p.r(C)p.r(A)p.r(A)p.r(C)p}$$$$",[i.fastaGaps]:"seq\nFW-PH-EYYFW-PH-EYY\nFYNRQWYV-FYNRQWYV-\nFKP-Q-SEYVFKP-Q-SEYV",[i.separatorGaps]:"seq\nF/W//P/H//E/Y/Y/F/W//P/H//E/Y/Y\nF/Y/N/R/Q/W/Y/V//F/Y/N/R/Q/W/Y/V/\nF/K/P//Q//S/E/Y/V/F/K/P//Q//S/E/Y/V",[i.helmGaps]:"seq\nPEPTIDE1{F.W.*.P.H.*.E.Y.Y.F.W.*.P.H.*.E.Y.Y}$$$$\nPEPTIDE1{F.Y.N.R.Q.W.Y.V.*.F.Y.N.R.Q.W.Y.V.*}$$$$\nPEPTIDE1{F.K.P.*.Q.*.S.E.Y.V.F.K.P.*.Q.*.S.E.Y.V}$$$$",[i.fastaUn]:"seq\n[meI][hHis][Aca]NT[dE][Thr_PO3H2][Aca]D[meI][hHis][Aca]NT[dE][Thr_PO3H2][Aca]D\n[meI][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca][Tyr_PO3H2][meI][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca][Tyr_PO3H2]\n[Lys_Boc][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca][Tyr_PO3H2][Lys_Boc][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca]",[i.separatorUn]:"seq\nmeI-hHis-Aca-N-T-dE-Thr_PO3H2-Aca-D-meI-hHis-Aca-N-T-dE-Thr_PO3H2-Aca-D\nmeI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-meI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2\nLys_Boc-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-Lys_Boc-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca",[i.helmUn]:"seq\nPEPTIDE1{meI.hHis.Aca.N.T.dE.Thr_PO3H2.Aca.D.meI.hHis.Aca.N.T.dE.Thr_PO3H2.Aca.D}$$$$\nPEPTIDE1{meI.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.Tyr_PO3H2.meI.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.Tyr_PO3H2}$$$$\nPEPTIDE1{Lys_Boc.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.Tyr_PO3H2.Lys_Boc.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca}$$$$",[i.helmLoneDeoxyribose]:"seq\nRNA1{d(A).d(C).d(G).d(T).d(C).d(A).d(C).d(G).d(T).d(C)}$$$$\nRNA1{d(C).d(A).d(G).d(T).d(G).d(T)p.d(C).d(A).d(G).d(T).d(G).d(T)p}$$$$\nRNA1{d(T).d(T).d(C).d(A).d(A).d(C)p.d(T).d(T).d(C).d(A).d(A).d(C)p}$$$$",[i.helmLoneRibose]:"seq\nRNA1{r(A).r(C).r(G).r(U).r(C).r(A).r(C).r(G).r(U).r(C)}$$$$\nRNA1{r(C).r(A).r(G).r(U).r(G).r(U)p.r(C).r(A).r(G).r(U).r(G).r(U)p}$$$$\nRNA1{r(U).r(U).r(C).r(A).r(A).r(C)p.r(U).r(U).r(C).r(A).r(A).r(C)p}$$$$",[i.helmLonePhosphorus]:"seq\nRNA1{p.p.r(A)p.r(C)p.r(G)p.r(U)p.r(C)p.r(A)p.r(C)p.r(G)p.r(U)p.r(C)p}$$$$\nRNA1{p.p.r(C)p.r(A)p.p.r(G)p.r(U)p.r(G)p.r(U)p.r(C)p.r(A)p.p.r(G)p.r(U)p.r(G)p.r(U)p}$$$$\nRNA1{p.r(U)p.r(U)p.r(C)p.r(A)p.r(A)p.r(C)p.r(U)p.r(U)p.r(C)p.r(A)p.r(A)p.r(C)p.p.p}$$$$"},s=new Set(Object.values(c.gp));async function r(t){const n=o[t],i=e.DataFrame.fromCsv(n);return await l.data.detectSemanticTypes(i),i}function a(e,i){if(e===c.Hi.SEPARATOR&&!i)throw new Error(`Argument 'separator' is mandatory for target notation '${e.toString()}'.`);return function(o){const s=n.getSeqHandler(o).convert(e,i);return(0,t.E3)(s.meta.units,e),s}}async function h(e,i,o){const a=(await r(e)).getCol("seq"),l=i(a),u=(await r(o)).getCol("seq");(0,t.J6)(l.toList(),u.toList());const h=n.getSeqHandler(a),d=n.getSeqHandler(l);for(const[e,n]of Object.entries(u.tags)){if(!s.has(e)||h.notation===c.Hi.HELM&&[c.gp.alphabet,c.gp.alphabetIsMultichar].includes(e)||d.notation===c.Hi.HELM&&[c.gp.alphabet,c.gp.alphabetIsMultichar].includes(e))continue;const i=l.getTag(e);(0,t.E3)(i,n,`Tag '${e}' expected value '${n}' is not equal to actual '${i}'.`)}}(0,t.t6)("testFastaPtToSeparator",async()=>{await h(i.fastaPt,a(c.Hi.SEPARATOR,"-"),i.separatorPt)}),(0,t.t6)("testFastaDnaToSeparator",async()=>{await h(i.fastaDna,a(c.Hi.SEPARATOR,"/"),i.separatorDna)}),(0,t.t6)("testFastaRnaToSeparator",async()=>{await h(i.fastaRna,a(c.Hi.SEPARATOR,"*"),i.separatorRna)}),(0,t.t6)("testFastaGapsToSeparator",async()=>{await h(i.fastaGaps,a(c.Hi.SEPARATOR,"/"),i.separatorGaps)}),(0,t.t6)("testFastaUnToSeparator",async()=>{await h(i.fastaUn,a(c.Hi.SEPARATOR,"-"),i.separatorUn)}),(0,t.t6)("testFastaPtToHelm",async()=>{await h(i.fastaPt,a(c.Hi.HELM),i.helmPt)}),(0,t.t6)("testFastaDnaToHelm",async()=>{await h(i.fastaDna,a(c.Hi.HELM),i.helmDna)}),(0,t.t6)("testFastaRnaToHelm",async()=>{await h(i.fastaRna,a(c.Hi.HELM),i.helmRna)}),(0,t.t6)("testFastaGapsToHelm",async()=>{await h(i.fastaGaps,a(c.Hi.HELM),i.helmGaps)}),(0,t.t6)("testSeparatorPtToFasta",async()=>{await h(i.separatorPt,a(c.Hi.FASTA),i.fastaPt)}),(0,t.t6)("testSeparatorDnaToFasta",async()=>{await h(i.separatorDna,a(c.Hi.FASTA),i.fastaDna)}),(0,t.t6)("testSeparatorRnaToFasta",async()=>{await h(i.separatorRna,a(c.Hi.FASTA),i.fastaRna)}),(0,t.t6)("testSeparatorGapsToFasta",async()=>{await h(i.separatorGaps,a(c.Hi.FASTA),i.fastaGaps)}),(0,t.t6)("testSeparatorUnToFasta",async()=>{await h(i.separatorUn,a(c.Hi.FASTA),i.fastaUn)}),(0,t.t6)("testSeparatorPtToHelm",async()=>{await h(i.separatorPt,a(c.Hi.HELM),i.helmPt)}),(0,t.t6)("testSeparatorDnaToHelm",async()=>{await h(i.separatorDna,a(c.Hi.HELM),i.helmDna)}),(0,t.t6)("testSeparatorRnaToHelm",async()=>{await h(i.separatorRna,a(c.Hi.HELM),i.helmRna)}),(0,t.t6)("testSeparatorGapsToHelm",async()=>{await h(i.separatorGaps,a(c.Hi.HELM),i.helmGaps)}),(0,t.t6)("testHelmDnaToFasta",async()=>{await h(i.helmDna,a(c.Hi.FASTA),i.fastaDna)}),(0,t.t6)("testHelmRnaToFasta",async()=>{await h(i.helmRna,a(c.Hi.FASTA),i.fastaRna)}),(0,t.t6)("testHelmPtToFasta",async()=>{await h(i.helmPt,a(c.Hi.FASTA),i.fastaPt)}),(0,t.t6)("testHelmUnToFasta",async()=>{await h(i.helmUn,a(c.Hi.FASTA),i.fastaUn)}),(0,t.t6)("testHelmDnaToSeparator",async()=>{await h(i.helmDna,a(c.Hi.SEPARATOR,"/"),i.separatorDna)}),(0,t.t6)("testHelmRnaToSeparator",async()=>{await h(i.helmRna,a(c.Hi.SEPARATOR,"*"),i.separatorRna)}),(0,t.t6)("testHelmPtToSeparator",async()=>{await h(i.helmPt,a(c.Hi.SEPARATOR,"-"),i.separatorPt)}),(0,t.t6)("testHelmUnToSeparator",async()=>{await h(i.helmUn,a(c.Hi.SEPARATOR,"-"),i.separatorUn)}),(0,t.t6)("testHelmLoneRibose",async()=>{await h(i.helmLoneRibose,a(c.Hi.FASTA),i.fastaRna)}),(0,t.t6)("testHelmLoneDeoxyribose",async()=>{await h(i.helmLoneDeoxyribose,a(c.Hi.SEPARATOR,"/"),i.separatorDna)}),(0,t.t6)("testHelmLonePhosphorus",async()=>{await h(i.helmLonePhosphorus,a(c.Hi.FASTA),i.fastaRna)});for(const e of v)(0,t.t6)(`testBilnToHelm_${e.name}`,async()=>{await y(e.biln,e.helm,n)});for(const e of C)(0,t.t6)(`testHelmToBiln_${e.name}`,async()=>{await b(e.helm,e.biln,n)})});var z=o(3516);(0,t.L1)("fastaFileHandler",()=>{const n=["description:1","description:2","description:3","description:4"],i=(e.Column.fromStrings("description",n),["MDYKETLLMPKTDFPMRGGLPNKEPQIQEKW","MIEVFLFGIVLGLIPITLAGLFVTAYLQYRRGDQLDL","MMELVLKTIIGPIVVGVVLRIVDKWLNKDK","MDRTDEVSNHTHDKPTLTWFEEIFEEYHSPFHN"]);function o(e){const o=new z.m(e),s=o.descriptionsArray,r=o.sequencesArray;(0,t.J6)([s,r],[n,i])}(0,t.t6)("testNormalFormatting",async()=>{o(">description:1\nMDYKETLLMPKTDFPMRGGLPNKEPQIQEKW\n\n>description:2\nMIEVFLFGIVLGLIPITLAGLFVTAYLQYRRGDQLDL\n\n>description:3\nMMELVLKTIIGPIVVGVVLRIVDKWLNKDK\n\n>description:4\nMDRTDEVSNHTHDKPTLTWFEEIFEEYHSPFHN\n")}),(0,t.t6)("testExtraSpaces",async()=>{o(">description:1\n MDYKETLLMPKTDFPMRGGLPNKEPQIQEKW\n\n>description:2\nMI EVF LFGIVLGLI PITLAGLFVTAY LQYRRGDQLDL\n\n>description:3\nM MELVLKTI IGPI VVGVVLR IVDKWLNKDK\n\n>description:4\nMDR TDEVSNHTHDKP TLTWFEEIFEEYHSPFHN\n ")}),(0,t.t6)("testExtraNewlines",async()=>{o(">description:1\n\nMDYKETLLMPKTDFPMRGGLPNKEPQIQEKW\n\n>description:2\nMIEVF\nLFGIVLGLI\nPITLAGLFVTA\nYLQYRRGDQLDL\n\n>description:3\nM\nME\n\nLVLKTIIG\n\nPIVVGVVLRI\nVDKWLNKDK\n\n\n>description:4\n\nMDRT\n\nDEVSNHTHDKP\n\nTLTWFEEIFEE\n\n\n\nYHSPFHN\n")})});var Z=o(3890);(0,t.L1)("fastaExport",()=>{let n,i;(0,t.gM)(async()=>{n=await(0,u.Q)()}),function(e){e.single="single",e.multi="multi"}(i||(i={}));const o={[i.single]:{src:"MDYKETLLMPKTDFPMRGGLP",tgt:["MDYKETLLMP","KTDFPMRGGL","P"]},[i.multi]:{src:"M[MeI]YKETLL[MeF]PKTDFPMRGGL[MeA]",tgt:["M[MeI]YKETLL[MeF]P","KTDFPMRGGL","[MeA]"]}};let s;!function(e){e.test1="test1",e.test2="test2"}(s||(s={}));const r={[s.test1]:{srcCsv:"id,seq\n1,MDYKETLLMP\n2,KTDFPMRGGL\n3,P",idCols:["id"],seqCol:"seq",lineWidth:10,tgtFasta:">1\nMDYKETLLMP\n>2\nKTDFPMRGGL\n>3\nP\n"},[s.test2]:{srcCsv:"id,id2,seq\n1,seqA,M[MeI]YKETLL[MeF]P\n2,seqB,KTDFPMRGGL\n3,seqC,[MeA]\n",idCols:["id2","id"],seqCol:"seq",lineWidth:5,tgtFasta:">seqA|1\nM[MeI]YKE\nTLL[MeF]P\n>seqB|2\nKTDFP\nMRGGL\n>seqC|3\n[MeA]\n"}};function a(i,s=10){const r=o[i].src,a=e.Column.fromStrings("src",[r]);a.semType=e.SEMTYPE.MACROMOLECULE,a.meta.units=c.Hi.FASTA;const l=n.getSeqHandler(a).getSplitted(0),u=(0,Z.aS)(l,s),h=o[i].tgt;(0,t.J6)(u,h)}async function l(i){const o=e.DataFrame.fromCsv(i.srcCsv),s=o.getCol(i.seqCol);s.semType=e.SEMTYPE.MACROMOLECULE,s.meta.units=c.Hi.FASTA;const r=i.idCols.map(e=>o.getCol(e)),a=n.getSeqHandler(s),l=(0,Z.wz)(r,a,i.lineWidth);(0,t.E3)(l,i.tgtFasta)}(0,t.t6)("wrapSequenceSingle",async()=>{a(i.single,10)}),(0,t.t6)("wrapSequenceMulti",async()=>{a(i.multi,10)}),(0,t.t6)("saveAsFastaTest1",async()=>{l(r[s.test1])}),(0,t.t6)("saveAsFastaTest2",async()=>{l(r[s.test2])})});var X=o(4152),Q=o(439);const J=Q._S;(0,t.L1)("bio",()=>{let n;(0,t.gM)(async()=>{n=await(0,u.Q)()});const o="seq\nACGTCT\nCAGTGT\nTTCAAC";(0,t.t6)("testGetStatsHelm1",async()=>{const n=e.DataFrame.fromCsv("seq\nPEPTIDE1{meI}$$$$").getCol("seq");n.semType=e.SEMTYPE.MACROMOLECULE,n.meta.units=c.Hi.HELM;const i=(0,I.vZ)(n,1,c.qp);(0,t.Xk)(i.freq,{meI:1}),(0,t.E3)(i.sameLength,!0)}),(0,t.t6)("testGetStatsN1",async()=>{await function(n){const i=e.DataFrame.fromCsv(n).col("seq");i.semType=e.SEMTYPE.MACROMOLECULE,i.meta.units=c.Hi.FASTA;const o=(0,I.vZ)(i,5,c.J9);(0,t.Xk)(o.freq,{A:4,C:5,G:3,T:6}),(0,t.E3)(o.sameLength,!0)}(o)}),(0,t.t6)("testGetAlphabetSimilarity",async()=>{await async function(){const e={A:2041,C:3015,G:3015,T:2048,[J]:1e3},n=new Set(Object.keys(a.Q.Names)),i=(0,c.nq)(e,n);(0,t.E3)(i>.6,!0)}()}),(0,t.t6)("testPickupPaletteN1",async()=>{await async function(i){const o=e.DataFrame.fromCsv(i).col("seq");o.semType=e.SEMTYPE.MACROMOLECULE,o.meta.units=c.Hi.FASTA;const s=(0,c.SM)(o,n);(0,t.E3)(s instanceof a.A,!0)}(o)}),(0,t.t6)("testPickupPaletteN1e",async()=>{await async function(){const i=e.DataFrame.fromCsv("seq\nACGTAT\nCAGTTG\nTTCG2C").col("seq");i.semType=e.SEMTYPE.MACROMOLECULE,i.meta.units=c.Hi.FASTA;const o=(0,c.SM)(i,n);(0,t.E3)(o instanceof a.A,!0)}()}),(0,t.t6)("testPickupPaletteAA1",async()=>{await async function(){const o=e.DataFrame.fromCsv("seq\nFWPHEYV\nYNRQWYV\nMKPSEYV").col("seq");o.semType=e.SEMTYPE.MACROMOLECULE,o.meta.units=c.Hi.FASTA;const s=(0,c.SM)(o,n);(0,t.E3)(s instanceof i.X,!0)}()}),(0,t.t6)("testPickupPaletteX",async()=>{await async function(){const i=e.DataFrame.fromCsv("seq\nXZJ{}2\n5Z4733\n3Z6></\n675687").col("seq");i.semType=e.SEMTYPE.MACROMOLECULE,i.meta.units=c.Hi.FASTA;const o=(0,c.SM)(i,n);(0,t.E3)(o instanceof X.$u,!0)}()})}),(0,t.L1)("WebLogo.monomerToShort",()=>{(0,t.t6)("longMonomerSingle",async()=>{(0,t.E3)((0,c.zS)("S",5),"S")}),(0,t.t6)("longMonomerShort",async()=>{(0,t.E3)((0,c.zS)("Short",5),"Short")}),(0,t.t6)("longMonomerLong56",async()=>{(0,t.E3)((0,c.zS)("Long56",6),"Long56")}),(0,t.t6)("longMonomerComplexFirstPartShort",async()=>{(0,t.E3)((0,c.zS)("Long-long",5),"Long…")}),(0,t.t6)("longMonomerComplexFirstPartLong56",async()=>{(0,t.E3)((0,c.zS)("Long56-long",6),"Long5…")}),(0,t.t6)("monomerToShort",async()=>{const e=[["AbC","AbC"],["AbCd","Ab…"],["ABc","ABc"],["ABcd","AB…"],["A_b","A_b"],["A_bc","A…"],["Ab_c","Ab…"],["A1_b","A1…"],["Abc_d","Ab…"],["Abcd_e","Ab…"],["A-b","A-b"],["A-bc","A…"],["Ab-c","Ab…"],["A1-b","A1…"],["Abc-d","Ab…"],["Abcd-e","Ab…"],["A","A"],["Ab","Ab"],["Abc","Abc"],["Ab…","Ab…"],["Abcd","Ab…"],["Abcde","Ab…"]],n=e.map(e=>e[0]),i=e.map(e=>e[1]),o=n.map(e=>(0,c.zS)(e,3));(0,t.J6)(o,i)})});var ee=o(250);const te=Q._S;function ne(e,n){(0,t.E3)(e.name,n.name),(0,t.J6)(e.getMonomers(),n.getMonomers());for(const i of e.getMonomers())(0,t.E3)(e.getFreq(i).rowCount,n.getFreq(i).rowCount)}(0,t.L1)("WebLogo.positions",()=>{let n;(0,t.gM)(async()=>{n=await(0,u.Q)()});const i="seq\nATC-G-TTGC--\nATC-G-TTGC--\n-TC-G-TTGC--\n-TC-GCTTGC--\n-TC-GCTTGC--";(0,t.t6)("allPositions",async()=>{const n=e.DataFrame.fromCsv(i),o=l.shell.addTableView(n),s=n.getCol("seq");s.semType=e.SEMTYPE.MACROMOLECULE,s.meta.units=c.Hi.FASTA,s.setTag(c.gp.alphabet,c.YI.DNA),s.setTag(c.gp.aligned,"SEQ.MSA");const r=await n.plot.fromType("WebLogo");await(0,t.PE)(r.onLayoutCalculated,()=>{},()=>{o.dockManager.dock(r.root,e.DOCK_TYPE.DOWN)},500,"Layout calculate timeout");const a=r.positions,u=[new ee.Ue(0,"1",{A:new ee.Tc(2),[te]:new ee.Tc(3)}),new ee.Ue(1,"2",{T:new ee.Tc(5)}),new ee.Ue(2,"3",{C:new ee.Tc(5)}),new ee.Ue(3,"4",{[te]:new ee.Tc(5)}),new ee.Ue(4,"5",{G:new ee.Tc(5)}),new ee.Ue(5,"6",{[te]:new ee.Tc(3),C:new ee.Tc(2)}),new ee.Ue(6,"7",{T:new ee.Tc(5)}),new ee.Ue(7,"8",{T:new ee.Tc(5)}),new ee.Ue(8,"9",{G:new ee.Tc(5)}),new ee.Ue(9,"10",{C:new ee.Tc(5)}),new ee.Ue(10,"11",{[te]:new ee.Tc(5)}),new ee.Ue(11,"12",{[te]:new ee.Tc(5)})];(0,t.E3)(a.length,u.length);for(let e=0;e<a.length;e++){(0,t.E3)(a[e].name,u[e].name);for(const n of a[e].getMonomers())(0,t.E3)(a[e].getFreq(n).rowCount,u[e].getFreq(n).rowCount)}await r.awaitRendered()}),(0,t.t6)("positions with shrinkEmptyTail option true (filtered)",async()=>{const n=e.DataFrame.fromCsv("seq\n-TC-G-TTGC--\n-TC-GCTTGC--\n-T--C-GT-\n-T--C-GT-\n-T--C-GT-\n-T--CCGT-"),i=l.shell.addTableView(n),o=n.getCol("seq");o.semType=e.SEMTYPE.MACROMOLECULE,o.meta.units=c.Hi.FASTA,o.setTag(c.gp.alphabet,c.YI.DNA),o.setTag(c.gp.aligned,"SEQ"),n.filter.init(e=>e>2),n.filter.fireChanged();const s=await n.plot.fromType("WebLogo",{shrinkEmptyTail:!0});await(0,t.PE)(s.onLayoutCalculated,()=>{},()=>{i.dockManager.dock(s.root,e.DOCK_TYPE.DOWN)},500);const r=s.positions,a=[new ee.Ue(0,"1",{[te]:new ee.Tc(3)}),new ee.Ue(1,"2",{T:new ee.Tc(3)}),new ee.Ue(2,"3",{[te]:new ee.Tc(3)}),new ee.Ue(3,"4",{[te]:new ee.Tc(3)}),new ee.Ue(4,"5",{C:new ee.Tc(3)}),new ee.Ue(5,"6",{[te]:new ee.Tc(2),C:new ee.Tc(1)}),new ee.Ue(6,"7",{G:new ee.Tc(3)}),new ee.Ue(7,"8",{T:new ee.Tc(3)}),new ee.Ue(8,"9",{[te]:new ee.Tc(3)})];(0,t.E3)(r.length,a.length);for(let e=0;e<r.length;e++){(0,t.E3)(r[e].name,a[e].name);for(const n of r[e].getMonomers())(0,t.E3)(r[e].getFreq(n).rowCount,a[e].getFreq(n).rowCount)}await s.awaitRendered()}),(0,t.t6)("positions with skipEmptyPositions option",async()=>{const n=e.DataFrame.fromCsv(i),o=l.shell.addTableView(n),s=n.getCol("seq");s.semType=e.SEMTYPE.MACROMOLECULE,s.meta.units=c.Hi.FASTA,s.setTag(c.gp.alphabet,c.YI.DNA),s.setTag(c.gp.aligned,"SEQ.MSA");const r=await n.plot.fromType("WebLogo",{skipEmptyPositions:!0});await(0,t.PE)(r.onLayoutCalculated,()=>{},()=>{o.dockManager.dock(r.root,e.DOCK_TYPE.DOWN)},500);const a=r.positions,u=[new ee.Ue(0,"1",{A:new ee.Tc(2),[te]:new ee.Tc(3)}),new ee.Ue(1,"2",{T:new ee.Tc(5)}),new ee.Ue(2,"3",{C:new ee.Tc(5)}),new ee.Ue(4,"5",{G:new ee.Tc(5)}),new ee.Ue(5,"6",{[te]:new ee.Tc(3),C:new ee.Tc(2)}),new ee.Ue(6,"7",{T:new ee.Tc(5)}),new ee.Ue(7,"8",{T:new ee.Tc(5)}),new ee.Ue(8,"9",{G:new ee.Tc(5)}),new ee.Ue(9,"10",{C:new ee.Tc(5)})];(0,t.E3)(a.length,u.length);for(let e=0;e<a.length;e++)ne(a[e],u[e]);await r.awaitRendered()}),(0,t.t6)("count sequences for monomer at position",async()=>{const o=function(t,n,i){const o=e.DataFrame.fromCsv(t),s=o.getCol("seq");return s.semType=e.SEMTYPE.MACROMOLECULE,s.meta.units=n,s.setTag(c.gp.alphabet,i),s.setTag(c.gp.aligned,"SEQ.MSA"),o}(i,c.Hi.FASTA,c.YI.DNA),s=o.getCol("seq"),r=l.shell.addTableView(o),a=await o.plot.fromType("WebLogo",{startPositionName:"3",endPositionName:"7",skipEmptyPositions:!0});await(0,t.PE)(a.onLayoutCalculated,()=>{},()=>{r.dockManager.dock(a.root,e.DOCK_TYPE.DOWN)},500);const u=a.positions,h=[new ee.Ue(2,"3",{C:new ee.Tc(5)}),new ee.Ue(4,"5",{G:new ee.Tc(5)}),new ee.Ue(5,"6",{[te]:new ee.Tc(3),C:new ee.Tc(2)}),new ee.Ue(6,"7",{T:new ee.Tc(5)})];(0,t.E3)(u.length,h.length);for(let e=0;e<u.length;e++)ne(u[e],h[e]);const d=u[1],m=n.getSeqHandler(s),p=(0,ee.eN)(o,m,o.filter,"G",d);(0,t.E3)(p,5),await a.awaitRendered()}),(0,t.t6)("empty",async()=>{const n=e.DataFrame.fromColumns([(()=>{const t=e.Column.fromStrings("seq",[]);return t.semType=e.SEMTYPE.MACROMOLECULE,t.meta.units=c.Hi.FASTA,t.setTag(c.gp.alphabet,c.YI.DNA),t})()]),i=l.shell.addTableView(n),o=await n.plot.fromType("WebLogo");await(0,t.PE)(o.onLayoutCalculated,()=>{},()=>{i.dockManager.dock(o.root,e.DOCK_TYPE.DOWN)},500),o.positions,await o.awaitRendered()})}),(0,t.L1)("WebLogo.project",()=>{(0,t.t6)("fasta",async()=>{const n="Tests.Bio.WebLogo-project.fasta",i=await Ge.files.readCsv("tests/filter_FASTA.csv"),o=i.name,s=i.getCol("fasta");await l.data.detectSemanticTypes(i);const r=l.shell.addTableView(i),a=await i.plot.fromType("WebLogo",{sequenceColumnName:s.name});r.dockManager.dock(a),await a.awaitRendered(),await O(r.grid),await async function(t,n,i,o){const s=e.Project.create(),r=i.saveLayout();s.name=t,s.addChild(n),s.addChild(r),await l.dapi.layouts.save(i.saveLayout()),await l.dapi.tables.uploadDataFrame(o),await l.dapi.tables.save(n),await l.dapi.projects.save(s)}(n,i.getTableInfo(),r,i),l.shell.closeAll(),await(0,t.cb)(500),await l.dapi.projects.open(n);const c=l.shell.getTableView(o),u=L()(c.viewers).toArray();(0,t.E3)(u.length,2),(0,t.E3)(u.filter(e=>"Grid"===e.type).length,1);const h=u.find(e=>"WebLogo"===e.type);(0,t.E3)(!!h,!0),await O(r.grid),await h.awaitRendered()},{skipReason:"depends on 1.18"})}),(0,t.L1)("WebLogo.layout",()=>{(0,t.t6)("fasta",async()=>{const e=await Ge.files.readCsv("tests/filter_FASTA.csv"),n=e.getCol("fasta");await l.data.detectSemanticTypes(e);const i=l.shell.addTableView(e),o=await e.plot.fromType("WebLogo",{sequenceColumnName:n.name});i.dockManager.dock(o),await(0,t.cb)(2*ee.VN.render),await o.awaitRendered(),await O(i.grid);const s=i.saveLayout();s.toJson(),i.loadLayout(s),await(0,t.cb)(2*ee.VN.render),await o.awaitRendered(),await O(i.grid);const r=L()(i.viewers).toArray();(0,t.E3)(r.length,2),(0,t.E3)(r.filter(e=>"Grid"===e.type).length,1),(0,t.E3)(r.filter(e=>"WebLogo"===e.type).length,1)})});var ie=o(966);function oe(e,t){let n=null;for(const i of e.viewers)i.type===t&&(n=i);return n}(0,t.L1)("checkInputColumn",()=>{let n;(0,t.gM)(async()=>{n=await(0,u.Q)()});const i="seq\nseq1,\nseq2,\nseq3,\nseq4";(0,t.t6)("testMsaPos",async()=>{const o=e.DataFrame.fromCsv(i).getCol("seq");o.semType=e.SEMTYPE.MACROMOLECULE,o.meta.units=c.Hi.FASTA,o.setTag(c.gp.alphabet,c.YI.DNA),o.setTag(c.gp.aligned,"SEQ");const[s,r]=(0,ie.l)(o,"Test",n,[c.Hi.FASTA],[c.YI.DNA,c.YI.RNA,c.YI.PT]);(0,t.E3)(s,!0)}),(0,t.t6)("testMsaNegHelm",async()=>{const o=e.DataFrame.fromCsv(i).getCol("seq");o.semType=e.SEMTYPE.MACROMOLECULE,o.meta.units=c.Hi.HELM,o.setTag(c.gp.alphabetIsMultichar,"true");const[s,r]=(0,ie.l)(o,"Test",n,[c.Hi.FASTA],[c.YI.DNA,c.YI.RNA,c.YI.PT]);(0,t.E3)(s,!1)}),(0,t.t6)("testMsaNegUN",async()=>{const o=e.DataFrame.fromCsv(i).getCol("seq");o.semType=e.SEMTYPE.MACROMOLECULE,o.meta.units=c.Hi.FASTA,o.setTag(c.gp.alphabet,"UN"),o.setTag(c.gp.alphabetSize,"11"),o.setTag(c.gp.alphabetIsMultichar,"true"),o.setTag(c.gp.aligned,"SEQ");const[s,r]=(0,ie.l)(o,"Test",n,[c.Hi.FASTA],[c.YI.DNA,c.YI.RNA,c.YI.PT]);(0,t.E3)(s,!1)}),(0,t.t6)("testGetActionFunctionMeta",async()=>{e.Func.find({package:"Bio",name:"multipleSequenceAlignmentDialog"})[0].inputs.find(e=>"sequence"==e.name)})}),(0,t.L1)("similarity/diversity",async()=>{(0,t.t6)("similaritySearchViewer",async()=>{await async function(){const n=await Ge.files.readAsText("tests/sample_MSA_data.csv"),i=e.DataFrame.fromCsv(n);await l.data.detectSemanticTypes(i);const o=l.shell.addTableView(i),s=o.dataFrame.getCol("MSA");(0,t.E3)(s.semType,e.SEMTYPE.MACROMOLECULE);const r=await o.dataFrame.plot.fromType("Sequence Similarity Search");let a=!1;if(r.computeCompleted.subscribe(e=>{e&&(a=!0)}),o.dockManager.dock(r,e.DOCK_TYPE.RIGHT,null,"Similarity"),await r.renderPromise,await(0,t.bk)(()=>void 0!==oe(o,"Sequence Similarity Search"),"Sequence Similarity Search viewer has not been created",100),!r.initialized)throw new Error("The viewer is not initialized.");if(!r.targetColumn)throw new Error("The viewer has not molecule column (onTableAttached).");if(!r.beforeRender())throw new Error("The viewer is not able to render.");if(!r.computeRequested)throw new Error("The viewer has not compute requested even.");if(!a)throw new Error("The viewer has not compute completed.");const c=r;await(0,t.bk)(()=>0!==c.root.getElementsByClassName("d4-grid").length,"Sequence Similarity Search viewer grid has not been created",100);(0,t.E3)(c.fingerprint,"Morgan"),(0,t.E3)(c.distanceMetric,"Hamming"),(0,t.E3)(c.scores.get(0),e.FLOAT_NULL),(0,t.E3)(c.idxs.get(0),0),(0,t.E3)(c.molCol.get(0),"D-Tyr_Et/Tyr_ab-dehydroMe/dV/E/N/D-Orn/D-aThr//Phe_4Me"),(0,t.E3)(c.scores.get(1).toFixed(2),"0.10"),(0,t.E3)(c.idxs.get(1),7),(0,t.E3)(c.molCol.get(1),"/D-Tyr_Et/meQ/dV/E/N/dV///Phe_4Me"),o.dataFrame.currentRowIdx=1,await(0,t.bk)(()=>1===c.targetMoleculeIdx,"Target molecule has not been changed",5e3),await(0,t.bk)(()=>"meI/hHis/Aca/Cys_SEt/T/dK/Thr_PO3H2/Aca/Tyr_PO3H2/D-Chg/dV/Phe_ab-dehydro/N/D-Orn/D-aThr//Phe_4Me"===c.molCol.get(0),"Incorrect first similar molecule",5e3)}()}),(0,t.t6)("diversitySearchViewer",async()=>{await async function(){const n=await Ge.files.readAsText("tests/sample_MSA_data.csv"),i=e.DataFrame.fromCsv(n),o=l.shell.addTableView(i);await l.data.detectSemanticTypes(i);const s=o.dataFrame.getCol("MSA");(0,t.E3)(s.semType,e.SEMTYPE.MACROMOLECULE);const r=await o.dataFrame.plot.fromType("Sequence Diversity Search");let a=!1;if(r.computeCompleted.subscribe(e=>{e&&(a=!0)}),o.dockManager.dock(r,e.DOCK_TYPE.DOWN,null,"Diversity"),await r.renderPromise,await(0,t.bk)(()=>void 0!==oe(o,"Sequence Diversity Search"),"Sequence Diversity Search viewer has not been created",100),!r.initialized)throw new Error("The viewer is not initialized.");if(!r.targetColumn)throw new Error("The viewer has not molecule column (onTableAttached).");if(!r.beforeRender())throw new Error("The viewer is not able to render.");if(!r.computeRequested)throw new Error("The viewer has not compute requested even.");if(!a)throw new Error("The viewer has not compute completed.");const c=r;await(0,t.bk)(()=>0!==c.root.getElementsByClassName("d4-grid").length,"Sequence Diversity Search viewer grid has not been created",100),(0,t.E3)(c.fingerprint,"Morgan"),(0,t.E3)(c.distanceMetric,"Hamming"),(0,t.E3)(c.initialized,!0),(0,t.E3)(c.renderMolIds.length>0,!0)}()})});var se=o(1687),re=o(4574);(0,t.L1)("bio-substructure-filters",async()=>{let n,i,o;async function s(e,t){if(!t.columns.names().includes(e))throw new Error(`The column '${e}' not found. Available in data frame are ${JSON.stringify(t.columns.names())}`);const i=new se._i(n,Ge.logger);return i.attach(t),i.applyState({columnName:e}),i.column=t.col(e),i.columnName=e,i}(0,t.gM)(async()=>{n=await(0,u.Q)(),i=await(0,_.pj)(),o=await(0,D.u)(),await i.loadMonomerLibForTests()}),(0,t.Pl)(async()=>{await(0,D.E)(o),await i.loadMonomerLib(!0)}),(0,t.t6)("fasta",async()=>{const e=await $("tests/filter_FASTA.csv");await l.data.detectSemanticTypes(e);const i=new se._i(n,Ge.logger);i.attach(e),await i.awaitRendered();try{(0,t.E3)(!!i.bioFilter,!0),(0,t.E3)(i.bioFilter.type,"FastaBioFilter");const n=i.bioFilter;await(0,t.PE)(e.onRowsFiltered,()=>{},()=>{n.props=new re.n("MD",void 0,Ge.logger)},5e3,"testEvent onRowsFiltered"),(0,t.E3)(i.dataFrame.filter.trueCount,3),(0,t.E3)(i.dataFrame?.filter.toBinaryString(),"10010000100000")}finally{i.detach()}await i.awaitRendered()}),(0,t.t6)("separator",async()=>{const e=await $("tests/filter_MSA.csv"),i=new se._i(n,Ge.logger);await l.data.detectSemanticTypes(e),i.attach(e),await i.awaitRendered();try{(0,t.E3)(!!i.bioFilter,!0),(0,t.E3)(i.bioFilter.type,"SeparatorBioFilter");const n=i.bioFilter;await(0,t.PE)(e.onRowsFiltered,()=>{},()=>{n.props=new se.AR("meI",void 0,Ge.logger)},5e3,"testEvent onRowsFiltered"),(0,t.E3)(i.dataFrame.filter.trueCount,7),(0,t.E3)(i.dataFrame.filter.get(2),!1),await(0,t.PE)(e.onRowsFiltered,()=>{},()=>{n.props=new se.AR("/meI",void 0,Ge.logger)},5e3,"testEvent onRowsFiltered"),(0,t.E3)(i.dataFrame.filter.trueCount,0),await(0,t.PE)(e.onRowsFiltered,()=>{},()=>{n.props=new se.AR("meI-hHis","-",Ge.logger)},5e3,"testEvent onRowsFiltered"),(0,t.E3)(i.dataFrame.filter.trueCount,7),(0,t.E3)(i.dataFrame.filter.get(2),!1)}finally{i.detach()}await i.awaitRendered()}),(0,t.t6)("helm-dialog",async()=>{if(e.Func.find({package:"Helm",name:"getHelmHelper"}).length){const e="Bio tests: substructureFilters/helm-dialog",i=await $("tests/filter_HELM.csv"),o=l.shell.addTableView(i);await l.data.detectSemanticTypes(i),await i.meta.detectSemanticTypes(),Ge.logger.debug(`${e}, filter attaching.`);const s=new se._i(n,Ge.logger);s.attach(i);const r=B.dialog("Test filters").add(s.root).show();await s.awaitRendered();try{const n=s.bioFilter;(0,t.E3)(null!==s.bioFilter,!0,"bioFilter is not created"),Ge.logger.debug(`${e}, filter 1 change awaiting...`),await(0,t.PE)(i.onRowsFiltered,()=>{},()=>{n.props=new re.n("PEPTIDE1{A.C}$$$$V2.0",void 0,Ge.logger)},2e4),Ge.logger.debug(`${e}, filter 1 changed.`),(0,t.E3)(s.dataFrame.filter.trueCount,1),(0,t.E3)(s.dataFrame.filter.toBinaryString(),"0001"),Ge.logger.debug(`${e}, filter 2 change awaiting...`),await(0,t.PE)(i.onRowsFiltered,()=>{},()=>{n.props=new re.n("PEPTIDE1{C}$$$$V2.0",void 0,Ge.logger)},2e4),setTimeout(()=>o.grid.invalidate(),500),await O(o.grid),await(0,t.cb)(1e3),Ge.logger.debug(`${e}, filter 2 changed.`),(0,t.E3)(s.dataFrame.filter.trueCount,2),(0,t.E3)(s.dataFrame.filter.toBinaryString(),"1001")}finally{r.close()}await s.awaitRendered(),await(0,t.cb)(3e3)}},{}),(0,t.t6)("helm-view",async()=>{if(e.Func.find({package:"Helm",name:"getHelmHelper"}).length){const e=await $("tests/filter_HELM.csv");e.getCol("HELM string"),await l.data.detectSemanticTypes(e);const t=l.shell.addTableView(e);t.getFiltersGroup(),await O(t.grid)}}),(0,t.t6)("sync-fasta",async()=>{const e=await Ge.files.readCsv("tests/filter_FASTA.csv");await l.data.detectSemanticTypes(e);const n=await s("fasta",e),i=await s("fasta",e);await Promise.all([n.awaitRendered(),i.awaitRendered()]);try{(0,t.E3)(!!n.bioFilter,!0),(0,t.E3)(!!i.bioFilter,!0),(0,t.E3)(n.bioFilter.type,"FastaBioFilter"),(0,t.E3)(i.bioFilter.type,"FastaBioFilter");const o=n.bioFilter,s=i.bioFilter;await(0,t.PE)(e.onRowsFiltered,()=>{},()=>{o.props=new re.n("MD",void 0,Ge.logger)},1e4,"await onRowsFiltered"),(0,t.E3)(e.filter.trueCount,3),await n.awaitRendered(),(0,t.E3)(s.props.substructure,"MD")}finally{n.detach(),i.detach()}await Promise.all([n.awaitRendered(),i.awaitRendered()])}),(0,t.t6)("sync-msa",async()=>{const e=await Ge.files.readCsv("tests/filter_MSA.csv");await l.data.detectSemanticTypes(e);const n="hHis-Aca",i=await s("MSA",e),o=await s("MSA",e);await Promise.all([i.awaitRendered(),o.awaitRendered()]);try{(0,t.E3)(!!i.bioFilter,!0),(0,t.E3)(!!o.bioFilter,!0),(0,t.E3)(i.bioFilter.type,"SeparatorBioFilter"),(0,t.E3)(o.bioFilter.type,"SeparatorBioFilter");const s=i.bioFilter,r=o.bioFilter;await(0,t.PE)(e.onRowsFiltered,()=>{},()=>{s.props=new se.AR(n,"-",Ge.logger)},1e4,"await onRowsFiltered"),(0,t.E3)(e.filter.trueCount,8),(0,t.E3)(r.props.substructure,n),(0,t.E3)(r.props.separator,"-")}finally{i.detach(),o.detach()}await Promise.all([i.awaitRendered(),o.awaitRendered()])}),(0,t.t6)("sync-helm",async()=>{if(e.Func.find({package:"Helm",name:"getHelmHelper"}).length){const e=await Ge.files.readCsv("tests/filter_HELM.csv");await l.data.detectSemanticTypes(e);const n=l.shell.addTableView(e),i="PEPTIDE1{A.C}$$$$V2.0",o=1,r=await s("HELM string",e),a=await s("HELM string",e),c=B.dialog("Test filters").add(r.root).add(a.root).show();await Promise.all([r.awaitRendered(),a.awaitRendered()]);try{(0,t.E3)(!!r.bioFilter,!0),(0,t.E3)(!!a.bioFilter,!0),(0,t.E3)(r.bioFilter.type,"HelmBioFilter"),(0,t.E3)(a.bioFilter.type,"HelmBioFilter");const s=r.bioFilter,l=a.bioFilter;await(0,t.PE)(e.onRowsFiltered,()=>{},()=>{s.props=new re.n(i,void 0,Ge.logger)},6e4,"await onRowsFiltered"),await O(n.grid),Ge.logger.debug("Bio tests: substructureFilters/sync-helm, before changed event"),await(0,t.cb)(2*r.debounceTime),Ge.logger.debug("Bio tests: substructureFilters/sync-helm, after changed event"),(0,t.E3)(e.filter.trueCount,o),await r.awaitRendered(),(0,t.E3)(l.props.substructure,i)}finally{r.detach(),a.detach(),c.close()}await Promise.all([r.awaitRendered(),a.awaitRendered()]),await O(n.grid),await(0,t.cb)(3e3)}}),(0,t.t6)("two-columns-fasta",async()=>{const n=e.DataFrame.fromCsv("id,seq1,seq2,trueSeq1,trueSeq2\n0,CGGCTACGGC,ATTGCATTCG,0,1,\n1,CGGCTGCCGC,ATAGCATTCG,1,1,\n2,CGGCTGCGCC,AATGCATACG,1,0,\n3,CGGCTGCATT,TTTGCATTCG,1,1,\n4,CGGCTGCATT,AAAGCATACG,1,0,\n");await l.data.detectSemanticTypes(n);const i=l.shell.addTableView(n),o="seq1",s="CGGCTG",r=n.getCol("trueSeq1").toList(),a="seq2",c="GCATT",u=n.getCol("trueSeq2").toList(),h=[{type:"Bio:bioSubstructureFilter",columnName:o},{type:"Bio:bioSubstructureFilter",columnName:a}],d=await n.plot.fromType(e.VIEWER.FILTERS,{filters:h});i.dockManager.dock(d,e.DOCK_TYPE.LEFT),await(0,t.cb)(100),await O(i.grid);const m=d.filters[0],p=d.filters[1];(0,t.E3)(m.column.name,o),(0,t.E3)(p.column.name,a);const g=m.bioFilter,f=p.bioFilter;await(0,t.PE)(n.onRowsFiltered,()=>{},()=>{g.props=new re.n(s,void 0,Ge.logger)},1e3),await(0,t.PE)(n.onRowsFiltered,()=>{},()=>{f.props=new re.n("",void 0,Ge.logger)},1e3,"testEvent onRowsFiltered on seq1"),(0,t.E3)(n.filter.trueCount,r.filter(e=>1===e).length),(0,t.E3)(n.filter.toBinaryString(),r.map(e=>e.toString()).join("")),await(0,t.PE)(n.onRowsFiltered,()=>{},()=>{g.props=new re.n("",void 0,Ge.logger)},1e3),await(0,t.PE)(n.onRowsFiltered,()=>{},()=>{f.props=new re.n(c,void 0,Ge.logger)},1e3,"testEvent onRowsFiltered on seq2"),(0,t.E3)(n.filter.trueCount,u.filter(e=>1===e).length),(0,t.E3)(n.filter.toBinaryString(),u.map(e=>e.toString()).join("")),await(0,t.PE)(n.onRowsFiltered,()=>{},()=>{g.props=new re.n("",void 0,Ge.logger)},1e3),await(0,t.PE)(n.onRowsFiltered,()=>{},()=>{f.props=new re.n("",void 0,Ge.logger)},1e3,"testEvent onRowsFiltered on neither"),(0,t.E3)(n.filter.trueCount,n.rowCount),await(0,t.PE)(n.onRowsFiltered,()=>{},()=>{g.props=new re.n(s,void 0,Ge.logger)},5e3),await(0,t.PE)(n.onRowsFiltered,()=>{},()=>{f.props=new re.n(c,void 0,Ge.logger)},5e3,"testEvent onRowsFiltered on both");const y=L().count(0).take(n.rowCount).map(e=>r[e]*u[e]).toArray();(0,t.E3)(n.filter.trueCount,y.filter(e=>1===e).length),(0,t.E3)(n.filter.toBinaryString(),y.map(e=>e.toString()).join("")),await Promise.all([m.awaitRendered(),p.awaitRendered(),O(i.grid)])},{skipReason:"Inconsistent behavior of test"}),(0,t.t6)("reset-fasta",async()=>{const n=await $("tests/filter_FASTA.csv"),i=l.shell.addTableView(n);await l.data.detectSemanticTypes(n),await n.meta.detectSemanticTypes();const o="MD",s=await n.plot.fromType(e.VIEWER.FILTERS,{filters:[{type:"Bio:bioSubstructureFilter",columnName:"fasta"}]});i.dockManager.dock(s,e.DOCK_TYPE.LEFT),await(0,t.cb)(100),await O(i.grid);const r=s.filters[0];await(0,t.bk)(()=>null!==r.bioFilter,"FastaBioFilter hasn't been created",1e3);const a=r.bioFilter;await(0,t.PE)(n.onRowsFiltered,()=>{},()=>{a.props=new re.n(o,void 0,Ge.logger)},1e3,"testEvent onRowsFiltered"),(0,t.E3)(n.filter.trueCount,3),(0,t.E3)(a.props.substructure,o),(0,t.E3)(a.substructureInput.value,o),U()(s.root).find('i[name="icon-arrow-rotate-left"]')[0].click(),await(0,t.cb)(100),await O(i.grid),(0,t.E3)(a.props.substructure,""),(0,t.E3)(a.substructureInput.value,"")}),(0,t.t6)("reopen",async()=>{const n=await Ge.files.readCsv("tests/filter_FASTA.csv"),i=l.shell.addTableView(n);await l.data.detectSemanticTypes(n),await n.meta.detectSemanticTypes();const o=[{type:"Bio:bioSubstructureFilter",columnName:"fasta"}],s=await n.plot.fromType(e.VIEWER.FILTERS,{filters:o});i.dockManager.dock(s,e.DOCK_TYPE.LEFT),await(0,t.cb)(100),await O(i.grid),s.close(),await O(i.grid);const r=await n.plot.fromType(e.VIEWER.FILTERS,{filters:o});i.dockManager.dock(r,e.DOCK_TYPE.LEFT),await(0,t.cb)(100),await O(i.grid)},{})});var ae=o(8152);class le{errorList=[];warningList=[];infoList=[];debugList=[];error(e,t,n){this.errorList.push({message:e,params:t,stackTrace:n})}warning(e,t){this.warningList.push({message:e,params:t})}info(e,t){this.infoList.push({message:e,params:t})}debug(e,t){this.debugList.push({message:e,params:t})}}var ce=o(9192);(0,t.L1)("PepSeA",()=>{(0,t.t6)("Basic alignment",async()=>{const n=e.DataFrame.fromCsv('HELM,MSA\n"PEPTIDE1{F.L.R.G.W.[MeF].Y.S.N.N.C}$$$$","F.L.R.G.W.MeF.Y..S.N.N.C"\n"PEPTIDE1{F.L.R.G.Y.[MeF].Y.W.N.C}$$$$","F.L.R.G.Y.MeF.Y.W...N.C"\n"PEPTIDE1{F.G.Y.[MeF].Y.W.S.D.N.C}$$$$","F...G.Y.MeF.Y.W.S.D.N.C"\n"PEPTIDE1{F.L.R.G.Y.[MeF].Y.W.S.N.D.C}$$$$","F.L.R.G.Y.MeF.Y.W.S.N.D.C"\n"PEPTIDE1{F.V.R.G.Y.[MeF].Y.W.S.N.C}$$$$","F.V.R.G.Y.MeF.Y.W.S..N.C"\n'),i=await(0,ae.GD)(n,n.getCol("HELM"),"msa(HELM)"),o=n.getCol("MSA");for(let e=0;e<i.length;++e)(0,t.E3)(i.get(e)==o.get(e),!0)},{timeout:6e4,skipReason:"Fails in docker"}),(0,t.t6)("stderr",async()=>{const n=new le,i=e.DataFrame.fromCsv('HELM,MSA\n"PEPTIDE1{F.L.Mis.G.W.[MeF].Y.S.N.N.C}$$$$","F.L.Mis.G.W.MeF.Y..S.N.N.C"\n"PEPTIDE1{F.L.Mis.G.Y.[MeF].Y.W.N.C}$$$$","F.L.Mis.G.Y.MeF.Y...W.N.C"\n"PEPTIDE1{F.G.Y.[MeF].Y.W.S.D.N.C}$$$$","F...G.Y.MeF.Y.W.S.D.N.C"\n'),o=await(0,ae.GD)(i,i.getCol("HELM"),"msa(HELM)",void 0,void 0,void 0,void 0,n),s=i.getCol("MSA");(0,t.J6)(o.toList(),s.toList()),(0,t.E3)(n.warningList[0].message,"Mis not found in Monomer Map\nMeF not found in Monomer Map\n")},{timeout:6e4,skipReason:"Fails in docker"}),(0,t.t6)("error",async()=>{const n=new le;try{const t=e.DataFrame.fromCsv('HELM\n"PEPTIDE1{[NH2].*.A.Q.T.T.Y.K.N.Y.R.R.N.L.L.*.[COOH]}$$$$"\n"PEPTIDE1{[NH2].M.A.N.T.T.Y.K.N.Y.R.N.N.L.L.*.[COOH]}$$$$"\n"PEPTIDE1{[NH2].*.A.N.T.T.Y.K.C.Y.R.R.N.L.L.*.[COOH]}$$$$"\n"PEPTIDE1{[NH2].*.A.N.T.T.Y.K.F.Y.R.R.N.L.L.*.[COOH]}$$$$"\n');await(0,ae.GD)(t,t.getCol("HELM"),"msa(HELM)",void 0,void 0,void 0,void 0,n)}catch(e){const[t,i]=(0,ce.AP)(e);n.error(t,void 0,i)}(0,t.E3)(n.errorList[0].message,"PepSeA error: The pair (*,M) couldn't be found in the substitution matrix")},{skipReason:"Fails in docker"})});const ue="seq\nACGTCACGTC\nCAGTGTCAGTGT\nTTCAACTTCAAC",he="seq\nAC-GT-CTAC-GT-CT\nCAC-T-GTCAC-T-GT\nACCGTACTACCGTACT",de="seq\nabc-dfgg-abc1-cfr3-rty-wert-abc-dfgg-abc1-cfr3-rty-wert\nrut12-her2-rty-wert-abc-abc1-dfgg-rut12-her2-rty-wert-abc-abc1-dfgg\nrut12-rty-her2-abc-cfr3-wert-rut12-rut12-rty-her2-abc-cfr3-wert-rut12";var me;(0,t.L1)("SeqHandler",()=>{let n;async function i(t){const i=e.DataFrame.fromCsv(t);await l.data.detectSemanticTypes(i);const o=n.getSeqHandler(i.getCol("seq"));return[i,o]}(0,t.gM)(async()=>{n=await(0,u.Q)()}),(0,t.t6)("Seq-Fasta",async()=>{const[e,n]=await i(ue);(0,t.E3)(n.notation,c.Hi.FASTA),(0,t.E3)(n.isMsa(),!1)}),(0,t.t6)("Seq-Fasta-MSA",async()=>{const[e,n]=await i(he);(0,t.E3)(n.notation,c.Hi.FASTA),(0,t.E3)(n.isMsa(),!0)}),(0,t.t6)("Seq-Fasta-units",async()=>{const[e,n]=await i(ue);(0,t.E3)(n.notation,c.Hi.FASTA),(0,t.E3)(n.isMsa(),!1)}),(0,t.t6)("Seq-Fasta-MSA-units",async()=>{const[e,n]=await i(he);(0,t.E3)(n.notation,c.Hi.FASTA),(0,t.E3)(n.isMsa(),!0)}),(0,t.t6)("Seq-Helm",async()=>{const[e,n]=await i("seq\nPEPTIDE1{meI.hHis.Aca.N.T.dE.Thr_PO3H2.Aca.D-Tyr_Et.Tyr_ab-dehydroMe.dV.E.N.D-Orn.D-aThr.Phe_4Me}$$$$\nPEPTIDE1{meI.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.Tyr_PO3H2.D-Chg.dV.Phe_ab-dehydro.N.D-Orn.D-aThr.Phe_4Me}$$$$\nPEPTIDE1{Lys_Boc.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.Tyr_PO3H2.D-Chg.dV.Thr_PO3H2.N.D-Orn.D-aThr.Phe_4Me}$$$$\nPEPTIDE1{meI.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.Tyr_PO3H2.D-Chg.dV.Thr_PO3H2.N.D-Orn.D-aThr.Phe_4Me}$$$$");(0,t.E3)(n.notation,c.Hi.HELM),(0,t.E3)(n.isHelm(),!0)}),(0,t.t6)("Seq-UN",async()=>{const[e,n]=await i(de);(0,t.E3)(n.notation,c.Hi.SEPARATOR),(0,t.E3)(n.separator,"-"),(0,t.E3)(n.alphabet,c.YI.UN)}),(0,t.t6)("Seq-UN-auto",async()=>{const[e,n]=await i(de);(0,t.E3)(n.notation,c.Hi.SEPARATOR),(0,t.E3)(n.separator,"-"),(0,t.E3)(n.alphabet,c.YI.UN)}),(0,t.t6)("column-version",async()=>{const i=e.DataFrame.fromCsv(ue);await l.data.detectSemanticTypes(i);const o=i.getCol("seq"),s=n.getSeqHandler(o),r=o.version,a=n.getSeqHandler(o),c=o.version;(0,t.E3)(r,c,"Unexpected column version changed"),(0,t.E3)(s,a,"Unexpected SeqHandler object changed"),i.rows.addNew(["TACCCCTTCAAC"]);const u=n.getSeqHandler(o),h=o.version;(0,t.E3)(c<h,!0,"Stalled column version on add row"),(0,t.E3)(a!==u,!0,"Stalled SeqHandler object on add row"),o.set(1,"CAGTGTCCCCGT");const d=n.getSeqHandler(o),m=o.version;(0,t.E3)(h<m,!0,"Stalled column version on change data"),(0,t.E3)(u!==d,!0,"Stalled SeqHandler object on change data"),o.setTag("testTag","testValue");const p=n.getSeqHandler(o),g=o.version;(0,t.E3)(m<g,!0,"Stalled column version on set tag"),(0,t.E3)(d!==p,!0,"Stalled SeqHandler object on set tag")})}),function(e){e.fasta="fasta",e.fastaMsa="fastaMsa",e.separator="separator",e.separatorMsa="separatorMsa",e.helm="helm"}(me||(me={})),(0,t.L1)("SeqHandler: splitted",()=>{let n;(0,t.gM)(async()=>{n=await(0,u.Q)()}),Q.b9[c.Hi.FASTA],Q.b9[c.Hi.HELM];const i=Q.b9[c.Hi.SEPARATOR],o={[me.fasta]:{src:{csv:"seq\nACGTCACGTC\nCAGTGTCAGTGT\nTTCAACTTCAAC"},tgt:{notation:c.Hi.FASTA,splitted:[["A","C","G","T","C","A","C","G","T","C"],["C","A","G","T","G","T","C","A","G","T","G","T"],["T","T","C","A","A","C","T","T","C","A","A","C"]]}},[me.fastaMsa]:{src:{csv:"seq\nAC-GT-CTAC-GT-CT\nCAC-T-GTCAC-T-GT\nACCGTACTACCGTACT"},tgt:{notation:c.Hi.FASTA,splitted:[["A","C","-","G","T","-","C","T","A","C","-","G","T","-","C","T"],["C","A","C","-","T","-","G","T","C","A","C","-","T","-","G","T"],["A","C","C","G","T","A","C","T","A","C","C","G","T","A","C","T"]]}},[me.separator]:{src:{csv:"seq\nabc-dfgg-abc1-cfr3-rty-wert-abc-dfgg-abc1-cfr3-rty-wert\nrut12-her2-rty-wert-abc-abc1-dfgg-rut12-her2-rty-wert-abc\nrut12-rty-her2-abc-cfr3-wert-rut12-rut12-rty-her2-abc-cfr3"},tgt:{notation:c.Hi.SEPARATOR,separator:"-",splitted:[["abc","dfgg","abc1","cfr3","rty","wert","abc","dfgg","abc1","cfr3","rty","wert"],["rut12","her2","rty","wert","abc","abc1","dfgg","rut12","her2","rty","wert","abc"],["rut12","rty","her2","abc","cfr3","wert","rut12","rut12","rty","her2","abc","cfr3"]]}},[me.separatorMsa]:{src:{csv:'seq\nrut0-dfgg-abc1-cfr3-rty-wert-abc-dfgg-abc1-cfr3-rty-wert\nrut1-her2-rty--abc1-dfgg-rut12-her2-rty--abc1-dfgg\nrut2-rty-her2---wert-rut12-rty-her2---wert\n"rut3-rty-her2-""-""-""-""-wert-rut12-rty-her2-""-""-""-""-wert"\n"""-""-rut4-her2-wert-rut12-rty-her2-wert"\n"rut5-rty-her2-wert-rut12-rty-her2-wert-""-"""'},tgt:{notation:c.Hi.SEPARATOR,separator:"-",splitted:[["rut0","dfgg","abc1","cfr3","rty","wert","abc","dfgg","abc1","cfr3","rty","wert"],["rut1","her2","rty",i,"abc1","dfgg","rut12","her2","rty",i,"abc1","dfgg"],["rut2","rty","her2",i,i,"wert","rut12","rty","her2",i,i,"wert"],["rut3","rty","her2",i,i,"wert","rut12","rty","her2",i,i,"wert"],[i,"rut4","her2","wert","rut12","rty","her2","wert"],["rut5","rty","her2","wert","rut12","rty","her2","wert",i]]}},[me.helm]:{src:{csv:"seq\nPEPTIDE1{meI.hHis.Aca.N.T.dE.Thr_PO3H2.Aca.D-Tyr_Et.Thr_PO3H2.Aca.D-Tyr_Et}$$$$\nPEPTIDE1{meI.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.dK.Thr_PO3H2.Aca}$$$$\nPEPTIDE1{Lys_Boc.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.dK.Thr_PO3H2.Aca}$$$$\nPEPTIDE1{meI.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.T.dK.Thr_PO3H2}$$$$,\nPEPTIDE1{meI.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.T.dK}|PEPTIDE2{Thr_PO3H2}$$$$"},tgt:{notation:c.Hi.HELM,splitted:[["meI","hHis","Aca","N","T","dE","Thr_PO3H2","Aca","D-Tyr_Et","Thr_PO3H2","Aca","D-Tyr_Et"],["meI","hHis","Aca","Cys_SEt","T","dK","Thr_PO3H2","Aca","dK","Thr_PO3H2","Aca"],["Lys_Boc","hHis","Aca","Cys_SEt","T","dK","Thr_PO3H2","Aca","dK","Thr_PO3H2","Aca"],["meI","hHis","Aca","Cys_SEt","T","dK","Thr_PO3H2","T","dK","Thr_PO3H2"],["meI","hHis","Aca","Cys_SEt","T","dK","Thr_PO3H2","T","dK","Thr_PO3H2"]]}}};for(const[i,s]of Object.entries(o))(0,t.t6)(`${i}`,async()=>{const i=e.DataFrame.fromCsv(s.src.csv).getCol("seq"),o=await l.functions.call("Bio:detectMacromolecule",{col:i});o&&(i.semType=o),(0,t.E3)(i.semType,e.SEMTYPE.MACROMOLECULE);const r=n.getSeqHandler(i);(0,t.E3)(r.notation,s.tgt.notation),(0,t.E3)(r.separator===s.tgt.separator,!0);const a=L().count(0).take(r.length).map(e=>{const t=r.getSplitted(e);return L().count(0).take(t.length).map(e=>t.getOriginal(e)).toArray()}).toArray();(0,t.J6)(a,s.tgt.splitted)})}),(0,t.L1)("SeqHandler: getRegion",()=>{let n;(0,t.gM)(async()=>{n=await(0,u.Q)()});const i={fastaDna:{srcCsv:"seq\nATTCGT\nACTGCTC\nATTCCGTA",startIdx:2,endIdx:4,tgtCsv:"seq\nTCG\nTGC\nTCC",units:c.Hi.FASTA,alphabet:c.YI.DNA,positionNames:{tag:"a, b, c, d, e, f, g, h",start:"c",end:"e"}},separatorPt:{srcCsv:"seq\nM-D-Y-K-E-T-L\nM-I-E-V-F-L-F-G-I\nM-M-",startIdx:5,endIdx:null,tgtCsv:"seq\nT-L--\nL-F-G-I\n---",units:c.Hi.SEPARATOR,alphabet:c.YI.PT,positionNames:{tag:"1, 1A, 1B, 2, 3, 4, 4A, 4A, 4C",start:"4",end:null}},helm:{srcCsv:"seq\nPEPTIDE1{[meI].[hHis].[Aca].N.T.[dE].[Thr_PO3H2].[Aca].[D-Tyr_Et].[Tyr_ab-dehydroMe].[dV].E.N.[D-Orn]}$$$$\nPEPTIDE1{[meI].[hHis].[Aca].[Cys_SEt].T.[dK].[Thr_PO3H2].[Aca].[Tyr_PO3H2].[D-Chg].[dV].[Phe_ab-dehydro]}$$$$\nPEPTIDE1{[Lys_Boc].[hHis].[Aca].[Cys_SEt].T}$$$$",startIdx:3,endIdx:6,tgtCsv:"seq\nPEPTIDE1{N.T.[dE].[Thr_PO3H2]}$$$$\nPEPTIDE1{[Cys_SEt].T.[dK].[Thr_PO3H2]}$$$$\nPEPTIDE1{[Cys_SEt].T.*.*}$$$$",units:c.Hi.HELM,alphabet:c.YI.UN,positionNames:{tag:null,start:"4",end:"7"}}};for(const[o,s]of Object.entries(i))(0,t.t6)(`${o}-idx`,async()=>{const i=e.DataFrame.fromCsv(s.srcCsv).getCol("seq"),o=await l.functions.call("Bio:detectMacromolecule",{col:i});o&&(i.semType=o);const r=n.getSeqHandler(i).getRegion(s.startIdx,s.endIdx,"regSeq"),a=e.DataFrame.fromCsv(s.tgtCsv).getCol("seq");(0,t.E3)(i.meta.units,s.units),(0,t.E3)(r.meta.units,s.units),(0,t.E3)(i.getTag(c.gp.alphabet),s.alphabet),(0,t.E3)(r.getTag(c.gp.alphabet),s.alphabet),(0,t.J6)(r.toList(),a.toList())}),s.positionNames&&(0,t.t6)(`${o}-positionNames`,async()=>{const n=e.DataFrame.fromCsv(s.srcCsv).getCol("seq");s.positionNames.tag&&n.setTag(c.gp.positionNames,s.positionNames.tag);const i=await l.functions.call("Bio:detectMacromolecule",{col:n});i&&(n.semType=i);const o=await l.functions.call("Bio:getRegion",{sequence:n,start:s.positionNames.start,end:s.positionNames.end}),r=e.DataFrame.fromCsv(s.tgtCsv).getCol("seq");(0,t.E3)(n.meta.units,s.units),(0,t.E3)(o.meta.units,s.units),(0,t.E3)(n.getTag(c.gp.alphabet),s.alphabet),(0,t.E3)(o.getTag(c.gp.alphabet),s.alphabet),(0,t.J6)(o.toList(),r.toList())})}),(0,t.L1)("SeqHandler: getHelm",()=>{let n,i,o;(0,t.gM)(async()=>{n=await(0,u.Q)(),i=await(0,_.pj)(),o=await(0,D.u)(),await i.loadMonomerLibForTests()}),(0,t.Pl)(async()=>{await(0,D.E)(o),await i.loadMonomerLib(!0)});const s={fasta:{src:{seq:"MDYKETMDYKET",notation:c.Hi.FASTA},tgt:{helm:"PEPTIDE1{M.D.Y.K.E.T.M.D.Y.K.E.T}$$$$"}},separator:{src:{seq:"M-D-Y-K-E-T-M-D-Y-K-E-T",notation:c.Hi.SEPARATOR,separator:"-"},tgt:{helm:"PEPTIDE1{M.D.Y.K.E.T.M.D.Y.K.E.T}$$$$"}},helm:{src:{seq:"PEPTIDE1{M.D.Y.K.E.T}$$$$",notation:c.Hi.HELM},tgt:{helm:"PEPTIDE1{M.D.Y.K.E.T}$$$$"}},"helm-cyclic":{src:{seq:"PEPTIDE1{M.D.Y.K.E.T}$PEPTIDE1,PEPTIDE1,6:R2-1:R1$$$V2.0",notation:c.Hi.HELM},tgt:{helm:"PEPTIDE1{M.D.Y.K.E.T}$PEPTIDE1,PEPTIDE1,6:R2-1:R1$$$V2.0"}}};for(const[e,n]of Object.entries(s))(0,t.t6)(e,async()=>{await r(n.src.seq,n.src.notation,n.src.separator,n.tgt.helm)});async function r(i,o,s,r){const a=e.Column.fromStrings("seq",[i]),c=e.DataFrame.fromColumns([a]);await l.data.detectSemanticTypes(c);const u=n.getSeqHandler(a),h=(await u.getValue(0)).helm;(0,t.E3)(h,r)}});var pe=o(2582);(0,t.L1)("helm",()=>{const e={"single-linear":{src:{helm:"PEPTIDE1{R.F.Y.[GGaz].T.[meI]}$$$$"},tgt:{simplePolymers:[6],connections:[],bondedRGroups:[1,2,2,2,2,1]}},"single-cyclized-C-2-2":{src:{helm:"PEPTIDE1{R.F.C.Y.G.H.[GGaz].C.T.[meI]}$PEPTIDE1,PEPTIDE1,3:R3-8:R3$$$"},tgt:{simplePolymers:[10],connections:[[["PEPTIDE1",3,"R3"],["PEPTIDE1",8,"R3"]]],bondedRGroups:[1,2,3,2,2,2,2,3,2,1]}},"single-cyclized-C-1-1":{src:{helm:"PEPTIDE1{F.C.Y.G.H.[GGaz].C.[meI]}$PEPTIDE1,PEPTIDE1,2:R3-7:R3$$$"},tgt:{simplePolymers:[8],connections:[[["PEPTIDE1",2,"R3"],["PEPTIDE1",7,"R3"]]],bondedRGroups:[1,3,2,2,2,1,3,1]}},"single-cyclized-C-0-0":{src:{helm:"PEPTIDE1{C.Y.G.H.[GGaz].C}$PEPTIDE1,PEPTIDE1,1:R3-6:R3$$$"},tgt:{simplePolymers:[6],connections:[[["PEPTIDE1",1,"R3"],["PEPTIDE1",6,"R3"]]],bondedRGroups:[2,2,2,2,2,2]}},"two-separated-5-1":{src:{helm:"PEPTIDE1{R.F.Y.[GGaz].T}|PEPTIDE2{[meI]}$$$$"},tgt:{simplePolymers:[5,1],connections:[],bondedRGroups:[1,2,2,2,1,0]}},"two-separated-1-5":{src:{helm:"PEPTIDE1{[meI]}|PEPTIDE2{R.F.Y.[GGaz].T}$$$$"},tgt:{simplePolymers:[1,5],connections:[],bondedRGroups:[0,1,2,2,2,1]}},"two-separated-4-2":{src:{helm:"PEPTIDE1{R.F.Y.[GGaz]}|PEPTIDE2{T.[meI]}$$$$"},tgt:{simplePolymers:[4,2],connections:[],bondedRGroups:[1,2,2,1,1,1]}},"two-connected-1":{src:{helm:"PEPTIDE1{R.F.Y.[GGaz].T}|PEPTIDE2{[meI]}$PEPTIDE1,PEPTIDE2,5:R2-1:R1$$$"},tgt:{simplePolymers:[5,1],connections:[[["PEPTIDE1",5,"R2"],["PEPTIDE2",1,"R1"]]],bondedRGroups:[1,2,2,2,2,1]}},"two-connected-2":{src:{helm:"PEPTIDE1{R.F.Y.[GGaz]}|PEPTIDE2{T.[meI]}$PEPTIDE1,PEPTIDE2,4:R2-1:R1$$$"},tgt:{simplePolymers:[4,2],connections:[[["PEPTIDE1",4,"R2"],["PEPTIDE2",1,"R1"]]],bondedRGroups:[1,2,2,2,2,1]}},"two-cyclized-1-9":{src:{helm:"PEPTIDE1{[meI]}|PEPTIDE2{R.F.[GGaz].T.G.H.F.Y.P}$PEPTIDE2,PEPTIDE2,3:R3-9:R2|PEPTIDE2,PEPTIDE1,3:R4-1:R1$$$V2.0"},tgt:{simplePolymers:[1,9],connections:[[["PEPTIDE2",3,"R3"],["PEPTIDE2",9,"R2"]],[["PEPTIDE2",3,"R4"],["PEPTIDE1",1,"R1"]]],bondedRGroups:[1,1,2,4,2,2,2,2,2,1]}}};for(const[n,{src:i,tgt:o}]of Object.entries(e))(0,t.t6)(n,async()=>{const e=new pe.f(i.helm),n=e.simplePolymers.map(e=>e.monomers.length),s=n.reduce((e,t)=>e+t,0);(0,t.J6)(n,o.simplePolymers);const r=e.connectionList.getConnectionData().map(e=>[[e[0].polymerId,e[0].bond.monomerIdx+1,`R${e[0].bond.rGroupId}`],[e[1].polymerId,e[1].bond.monomerIdx+1,`R${e[1].bond.rGroupId}`]]);(0,t.J6)(r,o.connections);const a=L().count(0).take(e.bondedRGroupsMap.length).map(t=>e.bondedRGroupsMap[t].length).toArray();(0,t.E3)(s,a.length)})});var ge=o(6077),fe=o(6717);const ye=new e.FileSource("System:AppData/Bio"),be={symbol:"allyl_mon",name:"monomer with Allyl R group",molfile:"\n RDKit 2D\n\n 9 8 0 0 0 0 0 0 0 0999 V2000\n 1.4434 -2.1667 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0\n 1.4434 -0.6667 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n 0.1443 0.0833 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n -1.1547 -0.6667 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n -2.4537 0.0833 0.0000 S 0 0 0 0 0 0 0 0 0 0 0 0\n -3.7528 -0.6667 0.0000 R# 0 0 0 0 0 0 0 0 0 0 0 0\n 0.1443 1.5833 0.0000 N 0 0 0 0 0 0 0 0 0 0 0 0\n 1.4434 2.3333 0.0000 R# 0 0 0 0 0 0 0 0 0 0 0 0\n 2.7424 0.0833 0.0000 R# 0 0 0 0 0 0 0 0 0 0 0 0\n 1 2 2 0\n 2 3 1 0\n 3 4 1 6\n 4 5 1 0\n 5 6 1 0\n 3 7 1 0\n 7 8 1 0\n 2 9 1 0\nM RGP 3 6 3 8 1 9 2\nM END\n",smiles:"O=C([C@H](CS[*:3])N[*:1])[*:2]",polymerType:"PEPTIDE",monomerType:"Backbone",naturalAnalog:"C",id:16,rgroups:[{alternateId:"R1-H",capGroupName:"H",capGroupSmiles:"[H][*:1]",label:"R1"},{alternateId:"R2-OH",capGroupName:"OH",capGroupSmiles:"O[*:2]",label:"R2"},{alternateId:"R3-Allyl",capGroupName:"Allyl",capGroupSmiles:"C=C[*:3]",label:"R3"}],author:"Admin",createDate:"2026-02-18T14:48:41.723Z",meta:{}},we={symbol:"SomeComplex",name:"Some complex monomer with complex R group",molfile:"\n RDKit 2D\n\n 10 9 0 0 0 0 0 0 0 0999 V2000\n -1.4289 -0.3750 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n -2.7280 0.3750 0.0000 S 0 0 0 0 0 0 0 0 0 0 0 0\n -4.0270 -0.3750 0.0000 R# 0 0 0 0 0 0 0 0 0 0 0 0\n -0.1299 0.3750 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n -0.1299 1.8750 0.0000 N 0 0 0 0 0 0 0 0 0 0 0 0\n 1.1691 2.6250 0.0000 R# 0 0 0 0 0 0 0 0 0 0 0 0\n 1.1691 -0.3750 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n 1.1691 -1.8750 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0\n 2.4682 -2.6250 0.0000 R# 0 0 0 0 0 0 0 0 0 0 0 0\n 2.4682 0.3750 0.0000 R# 0 0 0 0 0 0 0 0 0 0 0 0\n 1 2 1 0\n 2 3 1 0\n 4 1 1 6\n 4 5 1 0\n 5 6 1 0\n 4 7 1 0\n 7 8 1 0\n 8 9 1 0\n 7 10 1 0\nM RGP 4 3 3 6 1 9 4 10 2\nM END\n",smiles:"[*:4]OC([C@H](CS[*:3])N[*:1])[*:2]",polymerType:"PEPTIDE",monomerType:"Backbone",naturalAnalog:"C",id:16,rgroups:[{alternateId:"R1-H",capGroupName:"H",capGroupSmiles:"[H][*:1]",label:"R1"},{alternateId:"R2-OH",capGroupName:"OH",capGroupSmiles:"O[*:2]",label:"R2"},{alternateId:"R3-Something",capGroupName:"Something",capGroupSmiles:"C=CC([*:3])=C",label:"R3"},{alternateId:"R4-SomethingElse",capGroupName:"SomethingElse",capGroupSmiles:"ClCCCC=CC([*:4])=CCC",label:"R4"}],author:"Admin",createDate:"2026-02-18T14:48:41.723Z",meta:{}},ve={"peptides-fasta":{inPath:"tests/to-atomic-level-peptides-fasta-input.csv",outPath:"tests/to-atomic-level-peptides-fasta-output.csv"},"dna-fasta":{inPath:"tests/to-atomic-level-dna-fasta-input.csv",outPath:"tests/to-atomic-level-dna-fasta-output.csv"},"msa-separator":{inPath:"tests/to-atomic-level-msa-separator-input.csv",outPath:"tests/to-atomic-level-msa-separator-output.csv"},"msa-fasta":{inPath:"tests/to-atomic-level-msa-fasta-input.csv",outPath:"tests/to-atomic-level-msa-fasta-output.csv"}},Ce="molfile(sequence)";function Ae(e){return e.replaceAll("\r\n","\n").replace(/\n$/,"").split("\n").map(e=>e.trimEnd()).join("\n")}(0,t.L1)("toAtomicLevel",async()=>{const n={},i={};let o,s,r,a,h,d;async function m(e,n){const i=e.getCol("sequence");await l.functions.call("Bio:toAtomicLevel",{table:e,seqCol:i,nonlinear:!1});const o=e.getCol(Ce),s=n.getCol(Ce),r=L()(o.values()).map(e=>Ae(e)).toArray(),a=L()(s.values()).map(e=>Ae(e)).toArray();(0,t.J6)(r,a)}(0,t.gM)(async()=>{h=await(0,fe.j)(),r=await(0,u.Q)(),o=await(0,_.pj)(),s=await(0,D.u)(),await o.loadMonomerLibForTests(),a=o.getMonomerLib();for(const[t,o]of Object.entries(ve))o.inPath,n[t]=e.DataFrame.fromCsv((await ye.readAsText(o.inPath)).replace(/\n$/,"")),n[t].name=o.inPath.split("/").pop(),await l.data.detectSemanticTypes(n[t]),i[t]=e.DataFrame.fromCsv((await ye.readAsText(o.outPath)).replace(/\n$/,""))}),(0,t.Pl)(async()=>{await(0,D.E)(s),await o.loadMonomerLib(!0)});for(const[e,o]of Object.entries(ve))(0,t.t6)(`${e}`,async()=>{await m(n[e],i[e])});!function(e){e.fastaDna="fastaDna",e.fastaRna="fastaRna",e.fastaPt="fastaPt",e.fastaUn="fastaUn",e.separatorDna="separatorDna",e.separatorRna="separatorRna",e.separatorPt="separatorPt",e.separatorUn="separatorUn",e.helm="helm"}(d||(d={}));const p={[d.fastaDna]:"seq\nACGTCACGTC\nCAGTGTCAGTGT\nTTCAACTTCAAC",[d.fastaRna]:"seq\nACGUCACGUC\nCAGUGUCAGUGU\nUUCAACUUCAAC",[d.fastaPt]:"seq\nFWPHEYFWPHEY\nYNRQWYVYNRQWYV\nMKPSEYVMKPSEYV",[d.fastaUn]:"seq\n[meI][hHis][Aca]NT[dE][Thr_PO3H2][Aca]D[meI][hHis][Aca]NT[dE][Thr_PO3H2][Aca]D\n[meI][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca][Tyr_PO3H2][meI][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca][Tyr_PO3H2]\n[Lys_Boc][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca][Tyr_PO3H2][Lys_Boc][hHis][Aca][Cys_SEt]T[dK][Thr_PO3H2][Aca][Tyr_PO3H2]",[d.separatorDna]:"seq\nA/C/G/T/C/A/C/G/T/C\nC/A/G/T/G/T/C/A/G/T/G/T\nT/T/C/A/A/C/T/T/C/A/A/C",[d.separatorRna]:"seq\nA*C*G*U*C*A*C*G*U*C\nC*A*G*U*G*U*C*A*G*U*G*U\nU*U*C*A*A*C*U*U*C*A*A*C",[d.separatorPt]:"seq\nF-W-P-H-E-Y-F-W-P-H-E-Y\nY-N-R-Q-W-Y-V-Y-N-R-Q-W-Y-V\nM-K-P-S-E-Y-V-M-K-P-S-E-Y-V",[d.separatorUn]:"seq\nmeI-hHis-Aca-N-T-dE-Thr_PO3H2-Aca-D-meI-hHis-Aca-N-T-dE-Thr_PO3H2-Aca-D\nmeI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-meI-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2\nLys_Boc-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2-Lys_Boc-hHis-Aca-Cys_SEt-T-dK-Thr_PO3H2-Aca-Tyr_PO3H2",[d.helm]:"seq\nPEPTIDE1{meI.D-gGlu.Aca.N.T.dE.Thr_PO3H2.Aca.D.Thr_PO3H2.Aca.D}$$$\nPEPTIDE1{meI.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.Tyr_PO3H2.Thr_PO3H2.Aca.Tyr_PO3H2}$$$\nPEPTIDE1{Lys_Boc.hHis.Aca.Cys_SEt.T.dK.Thr_PO3H2.Aca.Tyr_PO3H2.Thr_PO3H2.Aca.Tyr_PO3H2}$$$"};async function g(t){const n=p[t],i=e.DataFrame.fromCsv(n.replace(/\n$/,""));return await l.data.detectSemanticTypes(i),i}async function f(e,n){let i=null;const s=o.getMonomerLib();s._monomers.PEPTIDE[be.symbol]=be,s._monomers.PEPTIDE[we.symbol]=we;try{const i=await r.getHelmToMolfileConverter(s),o=r.helmToAtomicLevelSingle(e,i,!0,!0),a=l.chem.convert(o.molfile,l.chem.Notation.Unknown,l.chem.Notation.Smiles);(0,t.E3)(a,n)}catch(e){i=e}if(delete s._monomers.PEPTIDE[be.symbol],delete s._monomers.PEPTIDE[we.symbol],i)throw i}async function y(e,t="seq",n){const i=e.getCol(t),o=await(0,ge.C4)(e,i,a,r,h);return o.warnings.length>0&&Ge.logger.warning(`_toAtomicLevel() warnings ${o.warnings.join("\n")}`),o.molCol}(0,t.t6)("fastaDna",async()=>{await y(await g(d.fastaDna),"seq")}),(0,t.t6)("fastaRna",async()=>{await y(await g(d.fastaRna),"seq")}),(0,t.t6)("fastaPt",async()=>{await y(await g(d.fastaPt),"seq")}),(0,t.t6)("fastaUn",async()=>{await y(await g(d.fastaUn),"seq")}),(0,t.t6)("separatorDna",async()=>{await y(await g(d.separatorDna),"seq")}),(0,t.t6)("separatorDna",async()=>{await y(await g(d.separatorRna),"seq")}),(0,t.t6)("separatorPt",async()=>{await y(await g(d.separatorPt),"seq")}),(0,t.t6)("separatorUn",async()=>{await y(await g(d.separatorUn),"seq")}),(0,t.t6)("helm",async()=>{await y(await g(d.helm),"seq")}),(0,t.t6)("ptFasta2",async()=>{const n=await Ge.files.readAsText("tests/to-atomic-level-pt-fasta-2.mol"),i=e.DataFrame.fromCsv("seq\nAR"),o=i.getCol("seq");o.semType=e.SEMTYPE.MACROMOLECULE,o.meta.units=c.Hi.FASTA,o.setTag(c.gp.alphabet,c.YI.PT),r.getSeqHandler(o);const s=await y(i,"seq");(0,t.E3)(Ae(s.get(0)),Ae(n))}),(0,t.t6)("SingleHelmMonomerWithAllylGroups",async()=>{const e=`PEPTIDE1{[${be.symbol}]}$$$$V2.0`;await f(e,"C=CSC[C@H](N)C(=O)O")}),(0,t.t6)("SingleHelmMonomerWithComplexRGroups",async()=>{const e=`PEPTIDE1{[${we.symbol}]}$$$$V2.0`;await f(e,"C=CC(=C)SC[C@H](N)C(O)OC(C=CCCCCl)=CCC")}),(0,t.t6)("HelmPolymerWithComplexRGroups",async()=>{const e=`PEPTIDE1{[dI].[Trp_Ome].[Asp_OMe].[D-Cit].[meG].[Phe_4NH2].[Phe_34diCl].[meY].[Pro_4Me3OH].[Met_O].[NMe2Abz].[Tyr_Ph4OH].[3Pal].[xiIle].[Tyr_35diI].[Ala_tBu]}|PEPTIDE2{[${be.symbol}].[${we.symbol}]}$PEPTIDE1,PEPTIDE1,16:R2-1:R1|PEPTIDE1,PEPTIDE2,1:R3-1:R1$$$V2.0`;await f(e,"C=CSC[C@H](NCC[C@@H](C)[C@H]1NC(=O)[C@H](C(C)(C)C)NC(=O)[C@H](Cc2cc(I)c(O)c(I)c2)NC(=O)[C@H](C(C)CC)NC(=O)[C@H](Cc2cccnc2)NC(=O)[C@H](Cc2ccc(Oc3ccc(O)cc3)cc2)NC(=O)c2ccccc2N(C)C(=O)[C@H](CCS(C)=O)NC(=O)[C@@H]2C(O)C(C)CN2C(=O)[C@H](Cc2ccc(O)cc2)N(C)C(=O)[C@H](Cc2ccc(Cl)c(Cl)c2)NC(=O)[C@H](Cc2ccc(N)cc2)NC(=O)CN(C)C(=O)[C@@H](CCCNC(N)=O)NC(=O)[C@H](CC(=O)OC)NC(=O)[C@H](Cc2cn(OC)c3ccccc23)NC1=O)C(=O)N[C@@H](CSC(=C)C=C)C(O)OC(C=CCCCCl)=CCC")})}),(0,t.L1)("toAtomicLevelHelmRna",async()=>{let n,i,o,s,r;async function a(n){const i=`seq\n${n}`,a=e.DataFrame.fromCsv(i);await l.data.detectSemanticTypes(a);const c=a.getCol("seq");(0,t.E3)(c.semType,e.SEMTYPE.MACROMOLECULE);const u=await(0,ge.C4)(a,c,s,o,r);if(!u.molCol)throw new Error(`_toAtomicLevel returned no molCol for HELM '${n}'. Warnings: ${(u.warnings??[]).join(" / ")}`);const h=u.molCol.get(0);if(!h)throw new Error(`_toAtomicLevel produced an empty molfile for HELM '${n}'`);let d;try{d=l.chem.convert(h,l.chem.Notation.Unknown,l.chem.Notation.Smiles)}catch(e){throw new Error(`SMILES conversion threw for HELM '${n}': ${e?.message??e}\n--- MOLFILE START ---\n${h}\n--- MOLFILE END ---`)}if("MALFORMED_INPUT_VALUE"===d||/^MALFORMED/.test(d))throw new Error(`RDKit could not parse molfile produced for HELM '${n}'.\n--- MOLFILE START ---\n${h}\n--- MOLFILE END ---`);return{molfile:h,smiles:d}}function c(e,t){const n=r.get_mol(e);if(!n||!n.is_valid())throw new Error(`RDKit refused the produced molfile:\n${e}`);try{return t(n)}finally{n.delete()}}function h(e,t){const n=r.get_qmol(t);try{const t=e.get_substruct_match(n);return!!t&&"{}"!==t}finally{n.delete()}}function d(e,t){const n=r.get_qmol(t);try{const t=e.get_substruct_matches(n);if(!t||"{}"===t)return 0;const i=JSON.parse(t);return Array.isArray(i)?i.length:i&&"object"==typeof i&&Array.isArray(i.atoms)&&i.atoms.length>0?1:0}finally{n.delete()}}function m(e,t){return d(e,`[#${t}]`)}(0,t.gM)(async()=>{r=await(0,fe.j)(),o=await(0,u.Q)(),n=await(0,_.pj)(),i=await(0,D.u)(),await n.loadMonomerLibForTests(),s=n.getMonomerLib()}),(0,t.Pl)(async()=>{await(0,D.E)(i),await n.loadMonomerLib(!0)});const p="[#6][OX2][PX4](=[OX1])([OX2,SX2,OX1H,SX1H,OX1-,SX1-])[OX2][#6]",g="[#6][OX2][PX4](=[OX1])([SX2,SX1H,SX1-])[OX2][#6]",f="[CX4][PX4]",y="[#6;R]1[#6;R][#6;R][#6;R][O;R]1",b="n1cnc2c1ncnc2N",w="[CH3]c1cn([!#1])c(=O)nc1N",v="[F][CX4;R]",C="[NX3]C(=O)[CH3]",A="[#6;R2]",T="[#7;R]1[#6;R](=[OX1])[#7;R][#6;R][#6;R]1";function E(e){const t=h(e,"[#6]1[#6][#6][#6][#6]1"),n=d(e,"[#6;R2]");return t&&n>=4}function S(e,t){const n=new Set,i=r.get_qmol(t);try{const t=e.get_substruct_matches(i);if(!t||"{}"===t)return n;const o=JSON.parse(t),s=Array.isArray(o)?o:[o];for(const e of s)for(const t of e?.atoms??[])n.add(t)}finally{i.delete()}return n}(0,t.t6)("rna-canonical",async()=>{const{molfile:e}=await a("RNA1{r(A)p.r(C)p.r(G)p}$$$$");c(e,e=>{const n=d(e,y);(0,t.E3)(n>=3,!0,`expected ≥ 3 furanose rings, got ${n}`);const i=d(e,p);(0,t.E3)(i>=2,!0,`expected ≥ 2 inter-nucleotide phosphodiester linkers, got ${i}`);const o=d(e,f);(0,t.E3)(o,0,`expected 0 direct C-P bonds (chain must use C-O-P-O-C), got ${o}`);const s=d(e,b);(0,t.E3)(s>=1,!0,`expected ≥ 1 purine ring, got ${s}`),(0,t.E3)(m(e,15),3,"expected 3 phosphorus atoms")})}),(0,t.t6)("rna-modified-base",async()=>{const{molfile:e}=await a("RNA1{r(C)p.r(A)p}$$$$"),{molfile:n}=await a("RNA1{r([m5C])p.r(A)p}$$$$");c(e,e=>{(0,t.E3)(d(e,w),0,"plain r(C) must not contain 5-methylcytosine")}),c(n,e=>{(0,t.E3)(d(e,w),1,"r([m5C]) must contain exactly one 5-methylcytosine ring")})}),(0,t.t6)("rna-modified-phosphate",async()=>{const{molfile:e}=await a("RNA1{r(A)p.r(C)p}$$$$"),{molfile:n}=await a("RNA1{r(A)[Rsp].r(C)p}$$$$");c(e,e=>{(0,t.E3)(m(e,16),0,"plain RNA must contain no sulfur"),(0,t.E3)(m(e,15),2,"expected 2 phosphates in plain"),(0,t.E3)(d(e,p)>=1,!0,"plain inter-nucleotide diester must be present")}),c(n,e=>{(0,t.E3)(h(e,"[PX4]=S")||h(e,"[PX4][SX2,SX1H,SX1-]"),!0,"sulfur must be bonded to a phosphorus atom"),(0,t.E3)(d(e,g),1,"expected exactly one phosphorothioate diester linker"),(0,t.E3)(m(e,15),2,"expected 2 phosphates in modified"),(0,t.E3)(d(e,f),0,"expected zero direct C-P bonds")})}),(0,t.t6)("rna-modified-sugar",async()=>{const{molfile:e}=await a("RNA1{r(A)p.r(C)p}$$$$"),{molfile:n}=await a("RNA1{[fl2r](A)p.r(C)p}$$$$");c(e,e=>{(0,t.E3)(m(e,9),0,"plain RNA must contain no fluorine")}),c(n,e=>{(0,t.E3)(m(e,9),1,"fl2r contributes exactly one fluorine"),(0,t.E3)(d(e,v)>=1,!0,"fluorine must be on a furanose ring carbon (2'-F)"),(0,t.E3)(d(e,y)>=2,!0,"expected ≥ 2 furanose rings")})}),(0,t.t6)("rna-no-trailing-phosphate",async()=>{const{molfile:e}=await a("RNA1{r(A)p.r(C)p}$$$$"),{molfile:n}=await a("RNA1{r(A)p.r(C)}$$$$"),i=c(e,e=>m(e,15)),o=c(n,e=>m(e,15));(0,t.E3)(i,2,"with trailing P: 2 phosphates (1 linker + 1 trail)"),(0,t.E3)(o,1,"no trailing P: 1 phosphate (the linker only)"),c(n,e=>{(0,t.E3)(d(e,p),1,"inter-nucleotide diester must still be present"),(0,t.E3)(d(e,f),0,"no direct C-P bond"),(0,t.E3)(d(e,y),2,"both furanose rings present")})}),(0,t.t6)("rna-no-trailing-phosphate-with-modifications",async()=>{const{molfile:e}=await a("RNA1{[fl2r]([m5C])[Rsp].r(A)}$$$$");c(e,e=>{(0,t.E3)(m(e,9),1,"expected exactly 1 fluorine"),(0,t.E3)(d(e,v),1,"2'-F must be on a furanose ring carbon"),(0,t.E3)(m(e,15),1,"expected exactly 1 phosphorus (Rsp)"),(0,t.E3)(m(e,16),1,"expected exactly 1 sulfur (Rsp)"),(0,t.E3)(d(e,g),1,"Rsp linker must remain a phosphorothioate diester"),(0,t.E3)(d(e,w),1,"expected one 5-methylcytosine base")})}),(0,t.t6)("rna-all-modifications",async()=>{const{molfile:e}=await a("RNA1{[fl2r]([m5C])[Rsp].r(A)p}$$$$");c(e,e=>{(0,t.E3)(d(e,v),1,"fl2r: 2'-F on furanose"),(0,t.E3)(d(e,w),1,"m5C: 5-methylcytosine"),(0,t.E3)(d(e,g),1,"Rsp: phosphorothioate diester"),(0,t.E3)(m(e,15),2,"two phosphates (Rsp + trailing p)"),(0,t.E3)(m(e,16),1,"exactly one sulfur (from Rsp)")})}),(0,t.t6)("rna-helm-3p-terminal-galnac",async()=>{const{molfile:e}=await a("RNA1{r(T)[GalNAc]}$$$$V2.0");c(e,e=>{(0,t.E3)(m(e,15),0,"GalNAc terminus: no P expected"),(0,t.E3)(d(e,C)>=1,!0,"expected N-acetyl group from GalNAc"),(0,t.E3)(h(e,"[#6]1[#6][#6][#6][#6][O]1"),!0,"expected a pyranose (6-membered) ring from GalNAc")})}),(0,t.t6)("rna-helm-5p-terminal-chol",async()=>{const{molfile:e}=await a("RNA1{[Chol].r(T)}$$$$V2.0");c(e,e=>{(0,t.E3)(E(e),!0,"Chol terminus must produce the steroid (gonane) ring system"),(0,t.E3)(d(e,y),1,"expected exactly 1 furanose ring (from r(T))")})}),(0,t.t6)("rna-helm-5p-terminal-chol-with-trailing-phosphate",async()=>{const{molfile:e}=await a("RNA1{[Chol].r(T)p}$$$$V2.0");c(e,e=>{(0,t.E3)(E(e),!0,"expected steroid ring system from Chol"),(0,t.E3)(m(e,15),1,"expected exactly 1 phosphorus"),(0,t.E3)(d(e,y),1,"expected 1 furanose")})}),(0,t.t6)("rna-helm-both-terminals",async()=>{const{molfile:e}=await a("RNA1{[Chol].r(T)[GalNAc]}$$$$V2.0");c(e,e=>{(0,t.E3)(m(e,15),0,"expected zero phosphates"),(0,t.E3)(E(e),!0,"expected steroid (Chol) ring system"),(0,t.E3)(d(e,C)>=1,!0,"expected N-acetyl group from GalNAc"),(0,t.E3)(h(e,"[#6]1[#6][#6][#6][#6][O]1"),!0,"expected pyranose ring from GalNAc")})}),(0,t.t6)("rna-helm-lna-base-above-sugar",async()=>{const{molfile:e}=await a("RNA1{[lna](A)p.[lna](T)}$$$$V2.0");c(e,e=>{(0,t.E3)(h(e,"[*]"),!0,"molecule must be non-empty");const n=d(e,A);(0,t.E3)(n>=4,!0,`expected ≥ 4 ring carbons in 2 rings (LNA bicyclic), got ${n}`),(0,t.E3)(d(e,p)>=1,!0,"expected ≥ 1 phosphodiester linker"),(0,t.E3)(d(e,f),0,"expected zero direct C-P bonds"),(0,t.E3)(d(e,b)>=1,!0,"expected adenine ring (purine)"),(0,t.E3)(h(e,"[CH3][#6]1=[#6][#7]([!#1])[#6](=O)[#7][#6]1=O")||h(e,"Cc1cn([!#1])c(=O)[nH]c1=O"),!0,"expected thymine ring (5-methyluracil)")}),function(e){const n=function(e){const t=[],n=e.indexOf("M V30 BEGIN ATOM");if(n<0)return t;const i=e.indexOf("M V30 END ATOM",n),o=e.substring(n,i>=0?i:e.length),s=/^M\s+V30\s+(\d+)\s+(\S+)\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)/gm;let r;for(;r=s.exec(o);)parseInt(r[1])-1===t.length&&t.push({element:r[2],x:parseFloat(r[3]),y:parseFloat(r[4])});return t}(e);if(0===n.length)throw new Error("failed to parse molblock atoms");c(e,e=>{const i=S(e,y),o=S(e,"[a]");if(0===i.size)throw new Error("no furanose ring atoms found — cannot verify layout");if(0===o.size)throw new Error("no aromatic base atoms found — cannot verify layout");let s=-1/0;for(const e of i)s=Math.max(s,n[e].y);let r=1/0;for(const e of o)r=Math.min(r,n[e].y);(0,t.E3)(r>s,!0,`expected base atoms above sugar (minBaseY=${r.toFixed(3)}, maxSugarY=${s.toFixed(3)})`)})}(e)}),(0,t.t6)("rna-helm-3p-terminal-galnac-no-extra-oh",async()=>{const{molfile:e}=await a("RNA1{[lna](T)[GalNAc]}$$$$V2.0");c(e,e=>{(0,t.E3)(m(e,8),10,"expected exactly 10 oxygen atoms in lna(T)GalNAc"),(0,t.E3)(m(e,15),0,"expected no phosphate"),(0,t.E3)(h(e,C),!0,"expected GalNAc N-acetyl group"),(0,t.E3)(d(e,A)>=2,!0,"expected LNA bicyclic bridgeheads")})}),(0,t.t6)("rna-helm-h-cap-phosphate-sp-connects",async()=>{const{molfile:e,smiles:n}=await a("RNA1{r(T)[sp].r(A)}$$$$V2.0");(0,t.E3)(-1===n.indexOf("."),!0,`expected single connected fragment, got: ${n}`),c(e,e=>{(0,t.E3)(d(e,"[PX4][SX2,SX1H,SX1-]"),1,"sp's sulfur must be on its phosphorus"),(0,t.E3)(m(e,15),1,"one phosphorus from the sp linker"),(0,t.E3)(m(e,16),1,"one sulfur from the sp linker"),(0,t.E3)(d(e,g),1,"sp linker must be a phosphorothioate diester (C-O-P-O-C)"),(0,t.E3)(d(e,f),0,"no direct C-P bond")})}),(0,t.t6)("rna-helm-sp-bridging-o-preserved",async()=>{const{molfile:e}=await a("RNA1{m(A)[sp].r(A)[sp]}$$$$V2.0");c(e,e=>{(0,t.E3)(m(e,15),2,"expected exactly 2 phosphorus atoms"),(0,t.E3)(m(e,16),2,"expected exactly 2 sulfur atoms"),(0,t.E3)(d(e,"[PX4][SX2,SX1H,SX1-]"),2,"both sulfurs must be bonded to a phosphorus atom"),(0,t.E3)(d(e,g),1,"inter-nucleotide sp must remain a phosphorothioate diester"),(0,t.E3)(d(e,"[CX4][OX2][PX4](=[OX1])[SX2,SX1H,SX1-]"),3,"every C-O-P-P=O-S match must be present (3: 2 from diester, 1 from monoester)"),(0,t.E3)(d(e,f),0,"expected zero direct C-P bonds — bridging O must be present"),(0,t.E3)(d(e,"[CH3][OX2][#6;R]"),1,"expected exactly one 2'-OMe group on the m sugar")})}),(0,t.t6)("rna-helm-bio-terminal-at-end",async()=>{const{molfile:e}=await a("RNA1{r(T)[Bio]}$$$$V2.0");c(e,e=>{(0,t.E3)(m(e,15),0,"Bio terminus: no phosphate"),(0,t.E3)(h(e,T),!0,"expected biotin ureido (cyclic urea) ring system"),(0,t.E3)(h(e,"[#16;R]"),!0,"expected ring sulfur (biotin's thiolane)"),(0,t.E3)(d(e,y),1,"expected the r(T) furanose")})}),(0,t.t6)("rna-helm-bio-terminal-at-start",async()=>{const{molfile:e}=await a("RNA1{[Bio].r(T)}$$$$V2.0");c(e,e=>{(0,t.E3)(m(e,15),0,"no phosphates"),(0,t.E3)(h(e,T),!0,"expected biotin ureido ring system at the 5' end"),(0,t.E3)(h(e,"[#16;R]"),!0,"expected biotin's thiolane ring sulfur"),(0,t.E3)(d(e,y),1,"expected the r(T) furanose")})}),(0,t.t6)("rna-helm-chol-terminal-at-start",async()=>{const{molfile:e}=await a("RNA1{[Chol].r(T)}$$$$V2.0");c(e,e=>{(0,t.E3)(E(e),!0,"expected steroid (gonane) ring system from Chol at 5'"),(0,t.E3)(d(e,y),1,"expected one r(T) furanose")})}),(0,t.t6)("rna-helm-chol-terminal-at-end",async()=>{const{molfile:e}=await a("RNA1{r(T)[Chol]}$$$$V2.0");c(e,e=>{(0,t.E3)(m(e,15),0,"no phosphate when Chol replaces trailing P"),(0,t.E3)(E(e),!0,"expected steroid (gonane) ring system from Chol at 3'"),(0,t.E3)(d(e,y),1,"expected one r(T) furanose")})})});var Te=o(8754);(0,t.L1)("toAtomicLevel-ui",()=>{let n,i,o,s,r;(0,t.gM)(async()=>{o=await(0,u.Q)(),r=await(0,fe.j)(),n=await(0,_.pj)(),i=await(0,D.u)(),await n.loadMonomerLibForTests(),s=n.getMonomerLib()}),(0,t.Pl)(async()=>{await(0,D.E)(i),await n.loadMonomerLib(!0)});const a={fasta:{src:{seq:"MDYKETLLMPK",units:c.Hi.FASTA},tgt:{atomCount:94,bondCount:95}},"fasta-with-gap":{src:{seq:"MD-YKETLLMPK",units:c.Hi.FASTA},tgt:{atomCount:94,bondCount:95}},helm:{src:{seq:"PEPTIDE1{meI.hHis.Aca.N.T.dK.Thr_PO3H2}$$$$",units:c.Hi.HELM},tgt:{atomCount:68,bondCount:68}},"helm-with-gap":{src:{seq:"PEPTIDE1{meI.hHis.*.Aca.N.T.dK.Thr_PO3H2}$$$$",units:c.Hi.HELM},tgt:{atomCount:68,bondCount:68}}},h=async t=>{const n=t.src.seq,i=e.DataFrame.fromColumns([e.Column.fromList(e.COLUMN_TYPE.STRING,"seq",[n])]);return await l.data.detectSemanticTypes(i),i.getCol("seq")};for(const[e,n]of Object.entries(a))(0,t.t6)(`${e}-linear`,async()=>{const e=await h(n);await d(e,!1,n.tgt)});if(e.Func.find({package:"Helm",name:"getHelmHelper"}).length)for(const[e,n]of Object.entries(a))(0,t.t6)(`${e}-nonlinear`,async()=>{const e=await h(n);await d(e,!0,n.tgt)});async function d(n,i,a){const l=await(0,Te.V)(n.dataFrame,n,i,!1,s,o,r);(0,t.E3)(l.molCol.semType,e.SEMTYPE.MOLECULE);const c=l.molCol.get(0),u=r.get_mol(c);(0,t.E3)(null!=u,!0,"No molecule generated");try{const e=u.get_num_atoms(),n=u.get_num_bonds();(0,t.E3)(e,a.atomCount),(0,t.E3)(n,a.bondCount)}finally{u.delete()}}});var Ee=o(6863);async function Se(t,n){const i=e.DataFrame.fromCsv(t),o=i.col("seq"),s=await l.functions.call("Bio:detectMacromolecule",{col:o});return s&&(o.semType=s),await l.data.detectSemanticTypes(i),n.getSeqHandler(o)}function Me(e,n,i,o){const s=i(e,n);(0,t.E3)(Number(s.toFixed(3)),Number(o.toFixed(3)))}(0,t.L1)("Distance",async()=>{let n;(0,t.gM)(async()=>{n=await(0,u.Q)()});const i=[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]],o={F:0,W:1,R:2,Y:3},s="FWRWY",r="FWRWW",a="FWY",l="FWRWY",c="FWY",h="FWRRRRY";(0,t.t6)("protein-distance-function",async()=>{const e=(await Se("seq\nFWRWYVKHPFWRWYVKHP\nYNRWYVKHPYNRWYVKHP\nMWRSWYCKHPMWRSWYCKHP",n)).getDistanceFunctionName();(0,t.E3)(e,Ee.Z.LEVENSHTEIN)}),(0,t.t6)("DNA-distance-function",async()=>{const e=(await Se("seq\nATAACGATAACG\nATCGAATCGA\nATCGAATCGA",n)).getDistanceFunctionName();(0,t.E3)(e,Ee.Z.LEVENSHTEIN)}),(0,t.t6)("MSA-distance-function",async()=>{const e=(await Se("seq\nATAACATAAC\nATCGAATCGA\nATCGAATCGA",n)).getDistanceFunctionName();(0,t.E3)(e,Ee.Z.HAMMING)}),(0,t.t6)("levenstein-sub",async()=>{const e=Ee.V[Ee.Z.LEVENSHTEIN]();Me(s,r,e,.2)}),(0,t.t6)("levenstein-del",async()=>{const e=Ee.V[Ee.Z.LEVENSHTEIN]();Me(a,l,e,.4)}),(0,t.t6)("hamming",async()=>{const e=Ee.V[Ee.Z.HAMMING]();Me(a,l,e,.6)}),(0,t.t6)("needleman-blosum62",async()=>{const e=Ee.V[Ee.Z.NEEDLEMANN_WUNSCH]({gapOpen:8,gapExtend:2});Me(s,r,e,-6)}),(0,t.t6)("needleman-blosum62-del",async()=>{const e=Ee.V[Ee.Z.NEEDLEMANN_WUNSCH]({gapOpen:8,gapExtend:2});Me(a,l,e,-3.667)}),(0,t.t6)("needleman-custom-sub",async()=>{const e=Ee.V[Ee.Z.NEEDLEMANN_WUNSCH]({scoringMatrix:i,alphabetIndexes:o,gapOpen:1,gapExtend:1});Me(s,r,e,.2)}),(0,t.t6)("needleman-custom-del",async()=>{const e=Ee.V[Ee.Z.NEEDLEMANN_WUNSCH]({scoringMatrix:i,alphabetIndexes:o,gapOpen:1,gapExtend:1});Me(a,l,e,.667)}),(0,t.t6)("needleman-custom-zero-extend",async()=>{const e=Ee.V[Ee.Z.NEEDLEMANN_WUNSCH]({scoringMatrix:i,alphabetIndexes:o,gapOpen:1,gapExtend:0});Me(c,h,e,.333)}),(0,t.t6)("needleman-custom-half-extend",async()=>{const e=Ee.V[Ee.Z.NEEDLEMANN_WUNSCH]({scoringMatrix:i,alphabetIndexes:o,gapOpen:2,gapExtend:1});Me(c,h,e,1.667)}),(0,t.t6)("needleman-custom-same-extend",async()=>{const t=Ee.V[Ee.Z.NEEDLEMANN_WUNSCH]({scoringMatrix:i,alphabetIndexes:o,gapOpen:1,gapExtend:1});e.Test.isInBenchmark?Me(Array(1e3).fill(c).join(""),Array(1e3).fill(h).join(""),t,1.333):Me(c,h,t,1.333)},{benchmark:!0})});var xe=o(684);async function Pe(n,i,o,s,r,a,c,u){await l.data.detectSemanticTypes(n),await l.functions.call("Bio:activityCliffs",{table:n,molecules:n.getCol(o),activities:n.getCol(s),similarity:r,methodName:i,similarityMetric:c,preprocessingFunction:u,options:{[`${xe.vb}`]:!0},demo:!1});const h=Array.from(l.shell.tv.viewers)[1];(0,t.E3)(h?.type===e.VIEWER.SCATTER_PLOT,!0),await(0,t.bk)(()=>{const e=Array.from(h.root.getElementsByClassName("scatter_plot_link"));return!e.length||e[0].innerText.toLowerCase()===`${a} cliffs`},"incorrect cliffs link",3e3)}var Le=o(2780),Ie=o(9039),_e=o(9124);async function Ne(n,i,o){const s=n.getCol(o);n.name="seqSpaceDf";const r=await l.functions.call("Bio:detectMacromolecule",{col:s});r&&(s.semType=r);const a=e.Func.find({package:"Bio",name:"macromoleculePreprocessingFunction"})[0];if(!a)throw new Error("Preprocessing function not found");await l.functions.call("Bio:sequenceSpaceTopMenu",{table:n,molecules:n.col(o),methodName:i,similarityMetric:Ee.Z.LEVENSHTEIN,plotEmbeddings:!0,preprocessingFunction:a,options:{[xe.vb]:!0}});const c=l.shell.tableView(n.name),u=Array.from(c?.viewers??[])[1];(0,t.E3)(null!=u)}(0,t.L1)("activityCliffs",async()=>{let n,i,o;const s=e.Func.find({name:"macromoleculePreprocessingFunction",package:"Bio"})[0],r=e.Func.find({name:"helmPreprocessingFunction",package:"Bio"})[0];(0,t.gM)(async()=>{e.Func.find({package:"Helm",name:"getHelmHelper"}).length&&(n=await(0,_e.b2)()),i=await(0,_.pj)(),o=await(0,D.u)(),await i.loadMonomerLibForTests()}),(0,t.Pl)(async()=>{await(0,D.E)(o),await i.loadMonomerLib(!0)}),(0,t.t6)("activityCliffsOpens",async()=>{const t=e.Test.isInBenchmark?{fileName:"tests/peptides_with_random_motif_1600.csv",tgt:{cliffCount:64}}:{fileName:"tests/100_3_clustests.csv",tgt:{cliffCount:3}},n=await $(t.fileName);l.shell.addTableView(n),await Pe(n,Ie.c.UMAP,"sequence","Activity",90,t.tgt.cliffCount,Ee.Z.LEVENSHTEIN,s)},{benchmark:!0,skipReason:"Fails"}),(0,t.t6)("activityCliffsWithEmptyRows",async()=>{const e=await $("tests/100_3_clustests_empty_vals.csv");l.shell.addTableView(e),await Pe(e,Ie.c.UMAP,"sequence","Activity",90,3,Ee.Z.LEVENSHTEIN,s)}),(0,t.t6)("Helm",async()=>{if(e.Func.find({package:"Helm",name:"getHelmHelper"}).length){const e=await Ge.files.readCsv("samples/HELM_50.csv");l.shell.addTableView(e),await Pe(e,Ie.c.UMAP,"HELM","Activity",65,20,Le.aT.Tanimoto,r)}})}),(0,t.L1)("sequenceSpace",async()=>{let n,i,o,s;(0,t.t6)("sequenceSpaceOpens",async()=>{const t=e.Test.isInBenchmark?{fileName:"tests/peptides_with_random_motif_1600.csv"}:{fileName:"tests/100_3_clustests.csv"};n=await $(t.fileName),i=l.shell.addTableView(n),await Ne(n,Ie.c.UMAP,"sequence")},{benchmark:!0}),(0,t.t6)("sequenceSpaceWithEmptyRows",async()=>{o=await $("tests/100_3_clustests_empty_vals.csv"),s=l.shell.addTableView(o),await Ne(o,Ie.c.UMAP,"sequence")})}),(0,t.L1)("Scoring",()=>{const n="sequence",i="expected_similarity",o="expected_identity",s=e.DataFrame.fromCsv(`${n},${i},${o}\nPEPTIDE1{Aca.Orn.gGlu.Pqa.D-His_1Bn.dH.hHis.4Abz.D-Tic.D-Dap.Y.Iva.meS.F.P.F.D-1Nal}$$$$,1.0,1.0\nPEPTIDE1{Iva.Gly_allyl.gGlu.Pqa.D-Dip.dH.hHis.4Abz.D-aHyp.D-Dap.Y.Iva.I.Tyr_26diMe.P.Asu.meC}$$$$,0.691,0.53\nPEPTIDE1{[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal].[1Nal]}$$$$V2.0,0.37,0.0`),r=s.getCol(n);r.meta.units=c.Hi.HELM,r.semType=e.SEMTYPE.MACROMOLECULE;const a=r.get(0);let u,h;(0,t.gM)(async()=>{u=await(0,_.pj)(),h=await(0,D.u)(),await u.loadMonomerLibForTests()}),(0,t.Pl)(async()=>{await(0,D.E)(h),await u.loadMonomerLib(!0)}),(0,t.t6)("Identity",async()=>{const e=await l.functions.call("Bio:sequenceIdentityScoring",{table:s,macromolecule:r,reference:a});for(let n=0;n<e.length;n++){const i=e.get(n),r=s.get(o,n);(0,t.Wj)(i,r,.01,`Wrong identity score for sequence at position ${n}`)}}),(0,t.t6)("Identity-shortReference",async()=>{const e=await l.functions.call("Bio:sequenceIdentityScoring",{table:s,macromolecule:r,reference:"PEPTIDE1{Iva.Gly_allyl.gGlu.Pqa.D-Dip.dH.hHis.4Abz.D-aHyp.D-Dap.Y.Iva}$$$$"});(0,t.E3)(L().count(0).take(e.length).map(t=>e.get(t)).every(e=>null!=e&&!isNaN(e)),!0)}),(0,t.t6)("Identity-longReference",async()=>{const e=await l.functions.call("Bio:sequenceIdentityScoring",{table:s,macromolecule:r,reference:"PEPTIDE1{Iva.Gly_allyl.gGlu.Pqa.D-Dip.dH.hHis.4Abz.D-aHyp.D-Dap.Y.Iva.I.Tyr_26diMe.P.Asu.meC.I.Tyr_26diMe.P.Asu.meC}$$$$"});(0,t.E3)(L().count(0).take(e.length).map(t=>e.get(t)).every(e=>null!=e&&!isNaN(e)),!0)}),(0,t.t6)("Similarity",async()=>{const e=await l.functions.call("Bio:sequenceSimilarityScoring",{table:s,macromolecule:r,reference:a});for(let n=0;n<e.length;n++){const o=e.get(n),r=s.get(i,n);(0,t.Wj)(o,r,.01,`Wrong similarity score for sequence at position ${n}`)}})}),(0,t.L1)("projects",()=>{let n,i;async function o(n,i,o,s,r,a){let c;r?(await e.Func.find({name:"OpenFile"})[0].prepare({fullPath:`System:AppData/Bio/${n}`}).call(void 0,void 0,{processed:!1}),c=l.shell.tv,await l.data.detectSemanticTypes(c.dataFrame)):c=await async function(e){const t=await $(e);return t.name=e.replace(".csv",""),await l.data.detectSemanticTypes(t),l.shell.addTableView(t)}(n),await(0,t.cb)(100),await i(c),await(0,t.cb)(10),await async function(t,n){const i=e.Project.create();i.name="Test project";const o=t.dataFrame.getTableInfo();n&&(o.tags[e.Tags.DataSync]="sync",o.tags[e.Tags.CreationScript]=l.shell.tv.dataFrame.getTag(e.Tags.CreationScript));const s=t.getInfo();i.addChild(o),i.addChild(s),await l.dapi.tables.uploadDataFrame(t.dataFrame),await l.dapi.tables.save(o),await l.dapi.views.save(s),await l.dapi.projects.save(i);const r=i.id;l.shell.closeAll();const a=await l.dapi.projects.find(r);await a.open()}(c,r),await(0,t.cb)(10),await async function(e){let n="";await(0,t.bk)(()=>{if(!l.shell.tv.dataFrame)return!1;for(const t of e)if(!l.shell.tv.dataFrame.col(t))return n=t,!1;return!0},`${n} hasn't been added to dataframe`,5e3)}(o),s&&await async function(e){await(0,t.bk)(()=>{for(const t of l.shell.tv.viewers)if(t.type===e)return!0;return!1},`${e} hasn't been added`,5e3)}(s),a&&await a(c)}async function s(n){const i=n.dataFrame.col("sequence"),o=await l.functions.call("Bio:detectMacromolecule",{col:i});o&&(i.semType=o),await e.Func.find({package:"Bio",name:"sequenceSpaceTopMenu"})[0].prepare({table:n.dataFrame,molecules:i,methodName:"UMAP",similarityMetric:Ee.Z.LEVENSHTEIN,plotEmbeddings:!0,options:{[xe.vb]:!0},clusterEmbeddings:!0}).call(void 0,void 0,{processed:!1}),await(0,t.cb)(10)}async function r(n){const i=n.dataFrame.col("sequence"),o=await l.functions.call("Bio:detectMacromolecule",{col:i});o&&(i.semType=o),await e.Func.find({package:"Bio",name:"activityCliffs"})[0].prepare({table:n.dataFrame,molecules:i,activities:n.dataFrame.col("Activity"),similarity:90,methodName:"UMAP",similarityMetric:Ee.Z.LEVENSHTEIN,preprocessingFunction:e.Func.find({name:"macromoleculePreprocessingFunction",package:"Bio"})[0],options:{[xe.vb]:!0}}).call(void 0,void 0,{processed:!1}),await(0,t.cb)(10)}async function a(n){let i=null;for(const t of l.shell.tv.viewers)t.type===e.VIEWER.SCATTER_PLOT&&(i=t);await(0,t.bk)(()=>{const e=i?.root.getElementsByClassName("scatter_plot_link");return!(!e||!e.length)&&e[0].innerText.toLowerCase().includes("cliffs")},"Initialization function hasn't been applied on scatter plot",5e3)}(0,t.t6)("sequence_space",async()=>{n=await(0,_.pj)(),i=await(0,D.u)(),await n.loadMonomerLibForTests(),await o("tests/100_3_clustests.csv",s,["sequence","Embed_X_1","Embed_Y_1","Cluster (DBSCAN)"],e.VIEWER.SCATTER_PLOT),await(0,t.cb)(100),await(0,D.E)(i),await n.loadMonomerLib(!0)},{timeout:6e4}),(0,t.t6)("sequence_space_sync",async()=>{n=await(0,_.pj)(),i=await(0,D.u)(),await n.loadMonomerLibForTests(),await o("tests/100_3_clustests.csv",s,["sequence","Embed_X_1","Embed_Y_1","Cluster (DBSCAN)"],e.VIEWER.SCATTER_PLOT,!0),await(0,t.cb)(100),await(0,D.E)(i),await n.loadMonomerLib(!0)},{timeout:6e4}),(0,t.t6)("activity_cliffs",async()=>{n=await(0,_.pj)(),i=await(0,D.u)(),await n.loadMonomerLibForTests(),await o("tests/100_3_clustests.csv",r,["sequence","Activity","Embed_X_1","Embed_Y_1"],e.VIEWER.SCATTER_PLOT,!1,a),await(0,t.cb)(100),await(0,D.E)(i),await n.loadMonomerLib(!0)},{timeout:6e4}),(0,t.t6)("activity_cliffs_sync",async()=>{n=await(0,_.pj)(),i=await(0,D.u)(),await n.loadMonomerLibForTests(),await o("tests/100_3_clustests.csv",r,["sequence","Activity","Embed_X_1","Embed_Y_1"],e.VIEWER.SCATTER_PLOT,!0,a),await(0,t.cb)(100),await(0,D.E)(i),await n.loadMonomerLib(!0)},{timeout:6e4})});var Re=o(3328),$e=o(417),Oe=o(9036);const He="QVQLVQSGAEVKKPGASVKVSCKASGYTFTGYYMHWVRQAPGQGLEWMGWINPNSGGTNYAQKFQGRVTMTRDTSISTAYMELSRLRSDDTAVYYCARVAPGALDYWGQGTLVTVSS",De="DIQMTQSPSSLSASVGDRVTITCRASQDVSTAVAWYQQKPGKAPKLLIYSASFLYSGVPSRFSGSGSGTDFTLTISSLQPEDFATYYCQQSYSTPRTFGQGTKVEIK",Fe="QSALTQPASVSGSPGQSITISCTGTSSDVGGYNYVSWYQQHPGKAPKLMIYDVSNRPSGVSNRFSGSKSGNTASLTISGLQAEDEADYYCSSYTSSSTLVFGGGTKLTVL",ke=["FR1","CDR1","FR2","CDR2","FR3","CDR3","FR4"];(0,t.L1)("antibody numbering (immunum)",()=>{(0,t.t6)("worker: heavy chain (IMGT)",async()=>{const[e]=await(0,$e.m)([He],"imgt");(0,t.E3)(e.chainType,"Heavy"),(0,t.E3)(e.chainCode,"H"),(0,t.E3)(e.confidence>=.5,!0),(0,t.E3)(e.positionNames.length>0,!0),(0,t.E3)(e.numberingDetail.length>0,!0);for(const n of Object.values(e.numberingMap))(0,t.E3)(n>=0&&n<117,!0);(0,t.E3)(e.numberingDetail.length,Object.keys(e.numberingMap).length)}),(0,t.t6)("worker: light kappa chain (IMGT)",async()=>{const[e]=await(0,$e.m)([De],"imgt");(0,t.E3)(e.chainType,"Light"),(0,t.E3)("K"===e.chainCode||"L"===e.chainCode,!0),(0,t.E3)(e.confidence>=.5,!0),(0,t.E3)(e.numberingDetail.length>0,!0)}),(0,t.t6)("worker: light lambda chain (IMGT)",async()=>{const[e]=await(0,$e.m)([Fe],"imgt");(0,t.E3)(e.chainType,"Light"),(0,t.E3)(e.confidence>=.5,!0)}),(0,t.t6)("worker: batch numbering",async()=>{const e=await(0,$e.m)([He,De,"EVQLVESGGGLVQPGGSLRLSCAASGFTFSSYAMSWVRQAPGKGLEWVSAISGSGGSTYYADSVKGRFTISRDNSKNTLYLQMNSLRAEDTAVYYCAKDHYSGSGSYYYYFDYWGQGTLVTVSS",Fe],"imgt");(0,t.E3)(e.length,4),(0,t.E3)(e[0].chainType,"Heavy"),(0,t.E3)(e[1].chainType,"Light"),(0,t.E3)(e[2].chainType,"Heavy"),(0,t.E3)(e[3].chainType,"Light")}),(0,t.t6)("worker: empty / short sequences fail gracefully",async()=>{const e=await(0,$e.m)(["","AAAA"," "],"imgt");(0,t.E3)(e.length,3);for(const n of e)(0,t.E3)(n.positionNames,""),(0,t.E3)(n.numberingDetail.length,0),(0,t.E3)(n.error.length>0,!0)}),(0,t.t6)("worker: kabat scheme returns kabat-style position codes",async()=>{const[e]=await(0,$e.m)([He],"imgt"),[n]=await(0,$e.m)([He],"kabat");(0,t.E3)(e.chainType,"Heavy"),(0,t.E3)(n.chainType,"Heavy");const i=new Set(Object.keys(e.numberingMap)),o=new Set(Object.keys(n.numberingMap));let s=!1;for(const e of o)if(!i.has(e)){s=!0;break}(0,t.E3)(s,!0)}),(0,t.t6)("numberAntibodyColumn: DataFrame shape matches antpack script",async()=>{const n=e.Column.fromStrings("seq",[He,De,""]);n.semType=e.SEMTYPE.MACROMOLECULE;const i=await(0,Oe.C)(n,"imgt");for(const e of["position_names","chain_type","annotations_json","numbering_detail","numbering_map"])(0,t.E3)(null!==i.col(e),!0);(0,t.E3)(i.rowCount,3),(0,t.E3)(i.get("position_names",0).length>0,!0),(0,t.E3)(i.get("chain_type",0),"Heavy");const o=JSON.parse(i.get("annotations_json",0));(0,t.E3)(o.length,7),(0,t.E3)(o.map(e=>e.name).join(","),ke.join(","));for(const e of o)(0,t.E3)(e.visualType,"region"),(0,t.E3)(e.category,"structure"),(0,t.E3)(e.sourceScheme,"IMGT"),(0,t.E3)(e.autoGenerated,!0);(0,t.E3)(i.get("chain_type",1),"Light");const s=JSON.parse(i.get("annotations_json",1));(0,t.E3)(s.length,7),(0,t.E3)(i.get("position_names",2),""),(0,t.E3)(i.get("chain_type",2),""),(0,t.E3)(i.get("annotations_json",2),"[]"),(0,t.E3)(i.get("numbering_detail",2),""),(0,t.E3)(i.get("numbering_map",2),"")}),(0,t.t6)("numberAntibodyColumn: numbering_map indices line up with sequence",async()=>{const n=e.Column.fromStrings("seq",[He]);n.semType=e.SEMTYPE.MACROMOLECULE;const i=await(0,Oe.C)(n,"imgt"),o=JSON.parse(i.get("numbering_detail",0)),s=JSON.parse(i.get("numbering_map",0));for(const e of o){const n=s[e.position];(0,t.E3)("number"==typeof n,!0),(0,t.E3)(He[n],e.aa)}}),(0,t.t6)("numberAntibodyColumn: annotations_json start/end resolve via numbering_map",async()=>{const n=e.Column.fromStrings("seq",[He]);n.semType=e.SEMTYPE.MACROMOLECULE;const i=await(0,Oe.C)(n,"imgt"),o=JSON.parse(i.get("annotations_json",0)),s=JSON.parse(i.get("numbering_map",0)),r=o.find(e=>"FR1"===e.name);(0,t.E3)(void 0!==r,!0);const a=s[r.start];(0,t.E3)("number"==typeof a,!0),(0,t.E3)(a>=0&&a<117,!0)}),(0,t.t6)("numberAntibodyColumn: loads antibodies.csv sample subset",async()=>{let n;try{n=await Re._package.files.readCsv("samples/antibodies.csv")}catch(e){return void console.warn("antibodies.csv not available — skipping",e)}const i=n.col("AntibodyHC")??n.col("HeavyChain")??n.columns.byName("AntibodyHC");if(!i)return;const o=e.Column.fromStrings("seq",Array.from({length:Math.min(10,i.length)},(e,t)=>i.get(t)??""));o.semType=e.SEMTYPE.MACROMOLECULE;const s=await(0,Oe.C)(o,"imgt");(0,t.E3)(s.rowCount,o.length);let r=0;for(let e=0;e<s.rowCount;e++)"Heavy"===s.get("chain_type",e)&&r++;(0,t.E3)(r>=Math.ceil(.6*o.length),!0)})});const Ge=new e.Package;async function Be(n,i,o,s){const r=await(0,t.N$)({category:n,test:i,testContext:o,stressTest:s});return e.DataFrame.fromObjects(r)}async function Ve(){await(0,t.Xb)(Ge,Ge.getModule("package-test.js"))}})(),bio_test=s})();
|
|
8
8
|
//# sourceMappingURL=package-test.js.map
|