@datagrok/proteomics 1.2.0 → 1.2.1
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/package.json +4 -3
- package/test-console-output-1.log +1077 -1059
- package/test-record-1.mp4 +0 -0
package/dist/package-test.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var proteomics_test;(()=>{var e={749(e,t,n){"use strict";n.d(t,{bk:()=>L,L1:()=>b,cb:()=>D,E3:()=>C,Xb:()=>P,N$:()=>S,t6:()=>_,CN:()=>m}),n(982);const o=DG.DataFrame.fromCsv('countries,fasta,smiles,molregno,LON,Zip Code,Street Address Line 1,ImageUrl,user_id,error_message,xray,flag,magnitude,CS-id,pdb_id,accel_a,time_offset,chart,fit,Questions,empty_number,empty_string\nBelgium,MSNFHNEHVMQFYRNNLKTKGVFGRQ,CC(C(=O)OCCCc1cccnc1)c2cccc(c2)C(=O)c3ccccc3,1480014,36.276729583740234,995042300,14016 ROUTE 31W,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,1,1,1QBS,1,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[2.497360340644872, 1.7058694986686864, 5.278052678195135, 0.16000320889028383],""points"":[{""x"":0.10000000149011612,""y"":2.374499797821045},{""x"":0.6000000238418579,""y"":2.6242473125457764},{""x"":1.100000023841858,""y"":2.367267608642578},{""x"":1.600000023841858,""y"":2.6723148822784424},{""x"":2.0999999046325684,""y"":2.6537344455718994},{""x"":2.5999999046325684,""y"":2.3651671409606934},{""x"":3.0999999046325684,""y"":2.5654284954071045},{""x"":3.5999999046325684,""y"":2.4160959720611572},{""x"":4.099999904632568,""y"":2.286726713180542},{""x"":4.599999904632568,""y"":2.5100042819976807},{""x"":5.099999904632568,""y"":1.6676985025405884},{""x"":5.599999904632568,""y"":0.680136501789093},{""x"":6.099999904632568,""y"":0.3391543924808502},{""x"":6.599999904632568,""y"":0.09038983285427094},{""x"":7.099999904632568,""y"":0.19802775979042053}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[7.525235855508179, 1.3186911876809984, 5.335672608564294, 0.7860743343958098],""points"":[{""x"":0.10000000149011612,""y"":7.988070487976074},{""x"":0.6000000238418579,""y"":7.018453121185303},{""x"":1.100000023841858,""y"":8.115279197692871},{""x"":1.600000023841858,""y"":7.486658096313477},{""x"":2.0999999046325684,""y"":7.396438121795654},{""x"":2.5999999046325684,""y"":7.477052211761475},{""x"":3.0999999046325684,""y"":6.913095474243164},{""x"":3.5999999046325684,""y"":8.01385498046875},{""x"":4.099999904632568,""y"":6.985900402069092},{""x"":4.599999904632568,""y"":6.970335960388184},{""x"":5.099999904632568,""y"":5.448817253112793},{""x"":5.599999904632568,""y"":2.5534818172454834},{""x"":6.099999904632568,""y"":1.893947958946228},{""x"":6.599999904632568,""y"":0.6340042352676392},{""x"":7.099999904632568,""y"":0.8403874039649963}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,100,abc\nBurundi,MDYKETLLMPKTDFPMRGGLPNKEPQIQEKW,COc1ccc2cc(ccc2c1)C(C)C(=O)Oc3ccc(C)cc3OC,1480015,36.276729583740234,995073444,80 STATE HIGHWAY 310,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,2,2,1ZP8,2,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[4.431460753103398, 2.1691498799246745, 5.266445597102774, 0.7825762827017926],""points"":[{""x"":0.10000000149011612,""y"":4.751083850860596},{""x"":0.6000000238418579,""y"":4.203000068664551},{""x"":1.100000023841858,""y"":4.415858745574951},{""x"":1.600000023841858,""y"":4.68414306640625},{""x"":2.0999999046325684,""y"":4.198400974273682},{""x"":2.5999999046325684,""y"":4.179222106933594},{""x"":3.0999999046325684,""y"":4.638473987579346},{""x"":3.5999999046325684,""y"":4.708553314208984},{""x"":4.099999904632568,""y"":4.291589260101318},{""x"":4.599999904632568,""y"":4.038082599639893},{""x"":5.099999904632568,""y"":3.4349939823150635},{""x"":5.599999904632568,""y"":1.2194708585739136},{""x"":6.099999904632568,""y"":1.1920831203460693},{""x"":6.599999904632568,""y"":0.5352635979652405},{""x"":7.099999904632568,""y"":0.3346920311450958}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[2.339458017970126, -1.0734184310171178, 4.746332950550934, 0.2482416857595658],""points"":[{""x"":0.10000000149011612,""y"":0.2139337658882141},{""x"":0.6000000238418579,""y"":0.4269562065601349},{""x"":1.100000023841858,""y"":0.2441573292016983},{""x"":1.600000023841858,""y"":0.146635964512825},{""x"":2.0999999046325684,""y"":0.08818462491035461},{""x"":2.5999999046325684,""y"":0.2560656666755676},{""x"":3.0999999046325684,""y"":0.42434045672416687},{""x"":3.5999999046325684,""y"":0.37111231684684753},{""x"":4.099999904632568,""y"":0.5581737160682678},{""x"":4.599999904632568,""y"":1.183590054512024},{""x"":5.099999904632568,""y"":1.5629843473434448},{""x"":5.599999904632568,""y"":2.3211288452148438},{""x"":6.099999904632568,""y"":2.229961633682251},{""x"":6.599999904632568,""y"":2.2560226917266846},{""x"":7.099999904632568,""y"":2.2142398357391357}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nCameroon,MIEVFLFGIVLGLIPITLAGLFVTAYLQYRRGDQLDL,COc1ccc2cc(ccc2c1)C(C)C(=O)OCCCc3cccnc3,1480016,36.26095962524414,995153596,30-56 WHITESTONE EXPY,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,3,3,2BDJ,3,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[4.6760652578642325, 0.9046956320756703, 5.651408971856738, 0.07738846012184185],""points"":[{""x"":0.10000000149011612,""y"":4.32425594329834},{""x"":0.6000000238418579,""y"":4.668442249298096},{""x"":1.100000023841858,""y"":4.379785060882568},{""x"":1.600000023841858,""y"":5.0345139503479},{""x"":2.0999999046325684,""y"":4.878653526306152},{""x"":2.5999999046325684,""y"":4.3451313972473145},{""x"":3.0999999046325684,""y"":4.336992263793945},{""x"":3.5999999046325684,""y"":5.037430286407471},{""x"":4.099999904632568,""y"":5.0092692375183105},{""x"":4.599999904632568,""y"":4.151902675628662},{""x"":5.099999904632568,""y"":3.4066951274871826},{""x"":5.599999904632568,""y"":2.3732759952545166},{""x"":6.099999904632568,""y"":1.673728108406067},{""x"":6.599999904632568,""y"":0.48574790358543396},{""x"":7.099999904632568,""y"":0.2783052325248718}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[2.938395863010111, -1.4658480661392117, 5.462702751996584, 0.3473139023615039],""points"":[{""x"":0.10000000149011612,""y"":0.4941710829734802},{""x"":0.6000000238418579,""y"":0.15323974192142487},{""x"":1.100000023841858,""y"":0.46373432874679565},{""x"":1.600000023841858,""y"":0.3370431363582611},{""x"":2.0999999046325684,""y"":0.5179030299186707},{""x"":2.5999999046325684,""y"":0.27899765968322754},{""x"":3.0999999046325684,""y"":0.22075064480304718},{""x"":3.5999999046325684,""y"":0.5789918899536133},{""x"":4.099999904632568,""y"":0.21169911324977875},{""x"":4.599999904632568,""y"":0.27857646346092224},{""x"":5.099999904632568,""y"":1.0906332731246948},{""x"":5.599999904632568,""y"":1.8520300388336182},{""x"":6.099999904632568,""y"":2.7177059650421143},{""x"":6.599999904632568,""y"":2.8680918216705322},{""x"":7.099999904632568,""y"":3.2413077354431152}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nCanada,MMELVLKTIIGPIVVGVVLRIVDKWLNKDK,CC(C(=O)NCCS)c1cccc(c1)C(=O)c2ccccc2,1480017,36.26095962524414,99515,30-56 WHITESTONE EXPY,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,4,4,1IAN,4,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[0.8597390975430008, 1.0957625732481946, 5.260537067987958, 0.07974187998177736],""points"":[{""x"":0.10000000149011612,""y"":0.8190152645111084},{""x"":0.6000000238418579,""y"":0.8421689867973328},{""x"":1.100000023841858,""y"":0.8740922212600708},{""x"":1.600000023841858,""y"":0.8924275040626526},{""x"":2.0999999046325684,""y"":0.8249067664146423},{""x"":2.5999999046325684,""y"":0.9327669143676758},{""x"":3.0999999046325684,""y"":0.8522974252700806},{""x"":3.5999999046325684,""y"":0.8174492716789246},{""x"":4.099999904632568,""y"":0.8394647240638733},{""x"":4.599999904632568,""y"":0.7139387726783752},{""x"":5.099999904632568,""y"":0.5561167597770691},{""x"":5.599999904632568,""y"":0.3276226818561554},{""x"":6.099999904632568,""y"":0.12479474395513535},{""x"":6.599999904632568,""y"":0.13006797432899475},{""x"":7.099999904632568,""y"":0.059702079743146896}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[5.760930219582546, 1.6591793293833013, 4.667155929720851, 0.7858109544121652],""points"":[{""x"":0.10000000149011612,""y"":6.156993389129639},{""x"":0.6000000238418579,""y"":5.236701965332031},{""x"":1.100000023841858,""y"":6.010560512542725},{""x"":1.600000023841858,""y"":5.495512962341309},{""x"":2.0999999046325684,""y"":6.087770462036133},{""x"":2.5999999046325684,""y"":5.79986572265625},{""x"":3.0999999046325684,""y"":5.597546577453613},{""x"":3.5999999046325684,""y"":5.520902156829834},{""x"":4.099999904632568,""y"":5.360654354095459},{""x"":4.599999904632568,""y"":3.5539746284484863},{""x"":5.099999904632568,""y"":1.577236294746399},{""x"":5.599999904632568,""y"":1.0001264810562134},{""x"":6.099999904632568,""y"":0.9305797815322876},{""x"":6.599999904632568,""y"":0.6033638715744019},{""x"":7.099999904632568,""y"":0.4203685522079468}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nColombia,MDRTDEVSNHTHDKPTLTWFEEIFEEYHSPFHN,FC(F)(F)c1ccc(OC2CCNCC2)cc1,1480029,36.3309440612793,995152050,1 COURT HOUSE SQUARE,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,5,5,4UJ1,5,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[6.4995088314153655, 2.4270351004539914, 5.178659535348579, 0.625653346241577],""points"":[{""x"":0.10000000149011612,""y"":6.496231555938721},{""x"":0.6000000238418579,""y"":6.42543363571167},{""x"":1.100000023841858,""y"":7.040063858032227},{""x"":1.600000023841858,""y"":6.1115403175354},{""x"":2.0999999046325684,""y"":6.680728435516357},{""x"":2.5999999046325684,""y"":6.406774520874023},{""x"":3.0999999046325684,""y"":6.611269474029541},{""x"":3.5999999046325684,""y"":5.889094352722168},{""x"":4.099999904632568,""y"":6.75344705581665},{""x"":4.599999904632568,""y"":6.361435890197754},{""x"":5.099999904632568,""y"":4.1666975021362305},{""x"":5.599999904632568,""y"":1.172118902206421},{""x"":6.099999904632568,""y"":0.801048994064331},{""x"":6.599999904632568,""y"":0.4640021026134491},{""x"":7.099999904632568,""y"":0.0010357667924836278}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[1.4734381347446401, 1.1649805188074196, 4.82958608866421, 0.09500545496710007],""points"":[{""x"":0.10000000149011612,""y"":1.5279096364974976},{""x"":0.6000000238418579,""y"":1.3559974431991577},{""x"":1.100000023841858,""y"":1.5246378183364868},{""x"":1.600000023841858,""y"":1.5567657947540283},{""x"":2.0999999046325684,""y"":1.4114240407943726},{""x"":2.5999999046325684,""y"":1.4045010805130005},{""x"":3.0999999046325684,""y"":1.4769829511642456},{""x"":3.5999999046325684,""y"":1.4875500202178955},{""x"":4.099999904632568,""y"":1.2991987466812134},{""x"":4.599999904632568,""y"":0.922961413860321},{""x"":5.099999904632568,""y"":0.6520044803619385},{""x"":5.599999904632568,""y"":0.15350978076457977},{""x"":6.099999904632568,""y"":0.1078903079032898},{""x"":6.599999904632568,""y"":0.17276449501514435},{""x"":7.099999904632568,""y"":0.14066608250141144}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nCosta Rica,MKSTKEEIQTIKTLLKDSRTAKYHKRLQIVL,CC(C)Cc1ccc(cc1)C(C)C(=O)N2CCCC2C(=O)OCCCc3ccccc3,1480018,36.3309440612793,995084218,4041 SOUTHWESTERN BLVD,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,6,6,2BPW,6,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[2.4833641843311227, -1.8945978742090062, 4.671127708092568, 0.24159861311815153],""points"":[{""x"":0.10000000149011612,""y"":0.0969524160027504},{""x"":0.6000000238418579,""y"":0.028483040630817413},{""x"":1.100000023841858,""y"":0.22087176144123077},{""x"":1.600000023841858,""y"":0.0068915546871721745},{""x"":2.0999999046325684,""y"":0.4305879771709442},{""x"":2.5999999046325684,""y"":0.44774115085601807},{""x"":3.0999999046325684,""y"":0.45346319675445557},{""x"":3.5999999046325684,""y"":0.2370593100786209},{""x"":4.099999904632568,""y"":0.4657953977584839},{""x"":4.599999904632568,""y"":1.155200719833374},{""x"":5.099999904632568,""y"":2.2294070720672607},{""x"":5.599999904632568,""y"":2.4311530590057373},{""x"":6.099999904632568,""y"":2.33846116065979},{""x"":6.599999904632568,""y"":2.608201026916504},{""x"":7.099999904632568,""y"":2.8136143684387207}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[5.224573521642033, 1.4454033924198528, 5.6014197746076535, 0.2823216054197577],""points"":[{""x"":0.10000000149011612,""y"":4.95027494430542},{""x"":0.6000000238418579,""y"":5.1754679679870605},{""x"":1.100000023841858,""y"":5.276752948760986},{""x"":1.600000023841858,""y"":5.589294910430908},{""x"":2.0999999046325684,""y"":5.616994857788086},{""x"":2.5999999046325684,""y"":5.120813846588135},{""x"":3.0999999046325684,""y"":5.340766906738281},{""x"":3.5999999046325684,""y"":4.876471042633057},{""x"":4.099999904632568,""y"":4.94999361038208},{""x"":4.599999904632568,""y"":5.162564754486084},{""x"":5.099999904632568,""y"":4.399557590484619},{""x"":5.599999904632568,""y"":2.7977969646453857},{""x"":6.099999904632568,""y"":1.0229872465133667},{""x"":6.599999904632568,""y"":0.48275601863861084},{""x"":7.099999904632568,""y"":0.10408931970596313}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nCuba,MHAILRYFIRRLFYHIFYKIYSLISKKHQSLPSDVRQF,COc1ccc2c(c1)c(CC(=O)N3CCCC3C(=O)Oc4ccc(C)cc4OC)c(C)n2C(=O)c5ccc(Cl)cc5,1480019,36.33115768432617,995081928,1227 US HIGHWAY 11,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,7,7,1QBS,7,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[3.320838679713925, -1.2421619987316728, 4.831325425225256, 0.3236011098403072],""points"":[{""x"":0.10000000149011612,""y"":0.3727470338344574},{""x"":0.6000000238418579,""y"":0.12365014106035233},{""x"":1.100000023841858,""y"":0.48422467708587646},{""x"":1.600000023841858,""y"":0.2264465093612671},{""x"":2.0999999046325684,""y"":0.16821794211864471},{""x"":2.5999999046325684,""y"":0.3879014551639557},{""x"":3.0999999046325684,""y"":0.5470244884490967},{""x"":3.5999999046325684,""y"":0.3419053554534912},{""x"":4.099999904632568,""y"":0.7655120491981506},{""x"":4.599999904632568,""y"":1.2346516847610474},{""x"":5.099999904632568,""y"":2.453336715698242},{""x"":5.599999904632568,""y"":2.9565491676330566},{""x"":6.099999904632568,""y"":3.335299491882324},{""x"":6.599999904632568,""y"":3.240290880203247},{""x"":7.099999904632568,""y"":3.1107218265533447}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[3.6401853521511094, 1.26211588875013, 5.399028074402744, 0.5089580830068091],""points"":[{""x"":0.10000000149011612,""y"":3.8585598468780518},{""x"":0.6000000238418579,""y"":3.6077206134796143},{""x"":1.100000023841858,""y"":3.855252265930176},{""x"":1.600000023841858,""y"":3.619039297103882},{""x"":2.0999999046325684,""y"":3.839388370513916},{""x"":2.5999999046325684,""y"":3.335283041000366},{""x"":3.0999999046325684,""y"":3.571141481399536},{""x"":3.5999999046325684,""y"":3.4155046939849854},{""x"":4.099999904632568,""y"":3.7316646575927734},{""x"":4.599999904632568,""y"":3.0680155754089355},{""x"":5.099999904632568,""y"":2.891066551208496},{""x"":5.599999904632568,""y"":1.6022753715515137},{""x"":6.099999904632568,""y"":0.7652576565742493},{""x"":6.599999904632568,""y"":0.6875326037406921},{""x"":7.099999904632568,""y"":0.5828871726989746}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nItaly,MSNFHNEHVMQFYRNNLKTKGVFGRQ,CC(C)Cc1ccc(cc1)C(C)C(=O)N2CCCC2C(=O)OCCO[N+](=O)[O-],1480020,36.33115768432617,99502,"168-46 91ST AVE., 2ND FLR",https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,8,8,1ZP8,8,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[2.293592105923809, 1.3781586549141835, 5.1025898038676605, 0.03493851245291291],""points"":[{""x"":0.10000000149011612,""y"":2.1287283897399902},{""x"":0.6000000238418579,""y"":2.267972230911255},{""x"":1.100000023841858,""y"":2.398442506790161},{""x"":1.600000023841858,""y"":2.5130622386932373},{""x"":2.0999999046325684,""y"":2.3255116939544678},{""x"":2.5999999046325684,""y"":2.127340793609619},{""x"":3.0999999046325684,""y"":2.47259783744812},{""x"":3.5999999046325684,""y"":2.131181478500366},{""x"":4.099999904632568,""y"":2.090421438217163},{""x"":4.599999904632568,""y"":2.02299165725708},{""x"":5.099999904632568,""y"":1.1105059385299683},{""x"":5.599999904632568,""y"":0.4494485855102539},{""x"":6.099999904632568,""y"":0.1375635862350464},{""x"":6.599999904632568,""y"":0.036351121962070465},{""x"":7.099999904632568,""y"":0.1619771122932434}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[5.953125499439879, 1.2528620255306528, 5.187637440149802, 0.3110348753260886],""points"":[{""x"":0.10000000149011612,""y"":5.6585283279418945},{""x"":0.6000000238418579,""y"":5.911152362823486},{""x"":1.100000023841858,""y"":5.924920082092285},{""x"":1.600000023841858,""y"":5.8469438552856445},{""x"":2.0999999046325684,""y"":5.929472923278809},{""x"":2.5999999046325684,""y"":6.190037727355957},{""x"":3.0999999046325684,""y"":6.236179828643799},{""x"":3.5999999046325684,""y"":6.141019344329834},{""x"":4.099999904632568,""y"":5.295210838317871},{""x"":4.599999904632568,""y"":5.265801906585693},{""x"":5.099999904632568,""y"":3.3722851276397705},{""x"":5.599999904632568,""y"":1.8299226760864258},{""x"":6.099999904632568,""y"":0.32690900564193726},{""x"":6.599999904632568,""y"":0.6274543404579163},{""x"":7.099999904632568,""y"":0.8441857099533081}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nRwanda,MPNSEPASLLELFNSIATQGELVRSLKAGNASK,CC(C)Cc1ccc(cc1)C(C)C(=O)N2CCCC2C(=O)OCCO,1480021,36.33137130737305,995037247,"168-46 91ST AVE., 2ND FLR",https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,9,9,2BDJ,9,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[3.8209972202654474, 1.3779216716448506, 5.299882228439686, 0.06040645519069608],""points"":[{""x"":0.10000000149011612,""y"":3.7821109294891357},{""x"":0.6000000238418579,""y"":3.542433023452759},{""x"":1.100000023841858,""y"":3.7008674144744873},{""x"":1.600000023841858,""y"":3.717301607131958},{""x"":2.0999999046325684,""y"":4.024452209472656},{""x"":2.5999999046325684,""y"":4.013899326324463},{""x"":3.0999999046325684,""y"":3.945094347000122},{""x"":3.5999999046325684,""y"":3.866621971130371},{""x"":4.099999904632568,""y"":3.7461626529693604},{""x"":4.599999904632568,""y"":3.3454740047454834},{""x"":5.099999904632568,""y"":2.61944317817688},{""x"":5.599999904632568,""y"":0.999405026435852},{""x"":6.099999904632568,""y"":0.46259793639183044},{""x"":6.599999904632568,""y"":0.054134611040353775},{""x"":7.099999904632568,""y"":0.05711187422275543}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[5.6318079657726035, 1.8495493770000595, 5.391793312471116, 0.17060707587348442],""points"":[{""x"":0.10000000149011612,""y"":5.458079814910889},{""x"":0.6000000238418579,""y"":5.554427146911621},{""x"":1.100000023841858,""y"":5.799983024597168},{""x"":1.600000023841858,""y"":5.364140033721924},{""x"":2.0999999046325684,""y"":5.864485740661621},{""x"":2.5999999046325684,""y"":5.4509806632995605},{""x"":3.0999999046325684,""y"":5.702574729919434},{""x"":3.5999999046325684,""y"":5.7314534187316895},{""x"":4.099999904632568,""y"":5.5123443603515625},{""x"":4.599999904632568,""y"":5.724395751953125},{""x"":5.099999904632568,""y"":4.354506969451904},{""x"":5.599999904632568,""y"":1.7307666540145874},{""x"":6.099999904632568,""y"":0.6305936574935913},{""x"":6.599999904632568,""y"":0.035183437168598175},{""x"":7.099999904632568,""y"":0.7575169205665588}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nSwitzerland,IRVVGRYLIEVWKAAGMDMDKVLFLWSSDEI,CN1CCC(CC1)Oc2ccc(cc2)C(F)(F)F,1480028,36.33137130737305,99504,92-11 179TH PLACE,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,9,10,1IAN,10,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[1.1190255865097471, 2.3163895161544437, 5.4968866182279195, 0.2035204047289052],""points"":[{""x"":0.10000000149011612,""y"":1.1057683229446411},{""x"":0.6000000238418579,""y"":1.1019697189331055},{""x"":1.100000023841858,""y"":1.0818607807159424},{""x"":1.600000023841858,""y"":1.062997817993164},{""x"":2.0999999046325684,""y"":1.046447515487671},{""x"":2.5999999046325684,""y"":1.1217249631881714},{""x"":3.0999999046325684,""y"":1.2166996002197266},{""x"":3.5999999046325684,""y"":1.215477705001831},{""x"":4.099999904632568,""y"":1.0581893920898438},{""x"":4.599999904632568,""y"":1.1747995615005493},{""x"":5.099999904632568,""y"":1.0181127786636353},{""x"":5.599999904632568,""y"":0.5344523191452026},{""x"":6.099999904632568,""y"":0.2569526433944702},{""x"":6.599999904632568,""y"":0.1912207305431366},{""x"":7.099999904632568,""y"":0.15060538053512573}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[3.1038581025805785, 2.0032224204185245, 5.087602825989163, 0.13277988512492753],""points"":[{""x"":0.10000000149011612,""y"":3.0498509407043457},{""x"":0.6000000238418579,""y"":2.805217742919922},{""x"":1.100000023841858,""y"":3.3415253162384033},{""x"":1.600000023841858,""y"":3.0549843311309814},{""x"":2.0999999046325684,""y"":3.250074863433838},{""x"":2.5999999046325684,""y"":3.0432586669921875},{""x"":3.0999999046325684,""y"":3.265852451324463},{""x"":3.5999999046325684,""y"":2.9475724697113037},{""x"":4.099999904632568,""y"":3.1929898262023926},{""x"":4.599999904632568,""y"":2.7460060119628906},{""x"":5.099999904632568,""y"":1.6175861358642578},{""x"":5.599999904632568,""y"":0.3006608486175537},{""x"":6.099999904632568,""y"":0.3444803059101105},{""x"":6.599999904632568,""y"":0.015537971630692482},{""x"":7.099999904632568,""y"":0.5527358055114746}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\n,,,,,,,,,,,,,,,,,,,,,');o.columns.add(DG.Column.fromList(DG.TYPE.BYTE_ARRAY,"BinaryImage",Array.from(new Uint8Array(11))));var r=function(e,t,n,o){return new(n||(n=Promise))(function(r,s){function a(e){try{l(o.next(e))}catch(e){s(e)}}function i(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,i)}l((o=o.apply(e,t||[])).next())})};const s=3e4,a=108e5,i=console.log.bind(console),l=console.info.bind(console),c=console.warn.bind(console),u=console.error.bind(console),m={},p="Auto Tests",d="Demo",f="Detectors",g="Core",h={};let y;var E;!function(e){e.notNull=function(e,t){if(null==e)throw new Error(`${null==t?"Value":t} not defined`)}}(E||(E={}));class w{constructor(e,t,n){this.catchUnhandled=!0,this.report=!1,this.returnOnFail=!1,void 0!==e&&(this.catchUnhandled=e),void 0!==t&&(this.report=t),void 0!==n&&(this.returnOnFail=n)}}class v{constructor(e,t,n,o){var a;this.category=e,this.name=t,null!=o||(o={}),null!==(a=o.timeout)&&void 0!==a||(o.timeout=s),this.options=o,this.test=()=>r(this,void 0,void 0,function*(){return new Promise((e,t)=>r(this,void 0,void 0,function*(){var o;let r="";try{DG.Test.isInDebug;let e=yield n();try{r=null!==(o=null==e?void 0:e.toString())&&void 0!==o?o:""}catch(e){r="Can't convert test's result to string",console.error(`Can't convert test's result to string in the ${this.category}:${this.name} test`)}}catch(e){t(e)}e(r)}))})}}function _(e,t,n){null==m[y]&&(m[y]={}),null==m[y].tests&&(m[y].tests=[]),m[y].tests.push(new v(y,e,t,n))}function C(e,t=!0,n){if(n=n?`${n}, `:"",e!==t)throw new Error(`${n}Expected "${t}", got "${e}"`)}function b(e,t,n){var o;y=e,t(),m[y]&&(m[y].clear=null===(o=null==n?void 0:n.clear)||void 0===o||o,m[y].timeout=null==n?void 0:n.timeout,m[y].benchmarks=null==n?void 0:n.benchmarks,m[y].stressTests=null==n?void 0:n.stressTests,m[y].owner=null==n?void 0:n.owner)}function T(e,t){return e.replace(new RegExp(t.name,"gi"),t.nqName)}function P(e,t){var n,i,l,c,u,y,E,w,_,b;return r(this,void 0,void 0,function*(){const P=e.id;if(h[P])return;const S=t?t.tests:m;if("DevTools"===e.name||t&&"DevTools"===t._package.name)for(const e of window.dartTests){const t=e.name.split(/\s*\|\s*!/g);let o=null!==(n=t.pop())&&void 0!==n?n:e.name,r=t.length?g+": "+t.join(": "):g,a=o.split(" | ");o=a[a.length-1],a.unshift(r),a.pop(),r=a.join(": "),void 0===S[r]&&(S[r]={tests:[],clear:!0}),S[r].tests.push(new v(r,o,e.test,{isAggregated:!1,timeout:null!==(l=null===(i=e.options)||void 0===i?void 0:i.timeout)&&void 0!==l?l:s,skipReason:null===(c=e.options)||void 0===c?void 0:c.skipReason,owner:null===(u=e.options)||void 0===u?void 0:u.owner,benchmark:null!==(E=null===(y=e.options)||void 0===y?void 0:y.benchmark)&&void 0!==E&&E}))}const N=[],A=[],x=[],L=yield grok.dapi.functions.filter(`package.id = "${P}"`).list(),F=new RegExp(/skip:\s*([^,\s]+)|wait:\s*(\d+)|cat:\s*([^,\s]+)|timeout:\s*(\d+)/g);for(const t of L){const n=t.options.test,i=t.options.demoPath;if(n&&Array.isArray(n)&&n.length)for(let e=0;e<n.length;e++){const o=n[e].matchAll(F),i={};Array.from(o).forEach(e=>{e[0].startsWith("skip")?i.skip=e[1]:e[0].startsWith("wait")?i.wait=parseInt(e[2]):e[0].startsWith("cat")?i.cat=e[3]:e[0].startsWith("timeout")&&(i.timeout=parseInt(e[4]))});const l=new v(null!==(w=i.cat)&&void 0!==w?w:p,1===n.length?t.name:`${t.name} ${e+1}`,()=>r(this,void 0,void 0,function*(){const o=yield grok.functions.eval(T(n[e],t));if(i.wait&&(yield D(i.wait)),"boolean"==typeof o&&!o)throw`Failed: ${n[e]}, expected true, got ${o}`}),{skipReason:i.skip,timeout:DG.Test.isInBenchmark?null!==(_=i.benchmarkTimeout)&&void 0!==_?_:a:null!==(b=i.timeout)&&void 0!==b?b:s});if(i.cat){const e=i.cat;void 0===S[e]&&(S[e]={tests:[],clear:!0}),S[e].tests||(S[e].tests=[]),S[e].tests.push(l)}else N.push(l)}if(i){const e=t.options.demoWait?parseInt(t.options.demoWait):void 0,n=new v(d,t.friendlyName,()=>r(this,void 0,void 0,function*(){yield D(300),grok.shell.clearLastError(),yield t.apply(),yield D(e||2e3);const n=yield grok.shell.lastError;if(n)throw new Error(n)}),{skipReason:t.options.demoSkip});A.push(n)}if(t.hasTag("semTypeDetector")){let n=o;t.options.testData&&(n=yield grok.data.files.openTable(`System:AppData/${e.nqName}/${t.options.testData}`));const s=new v(f,t.friendlyName,()=>r(this,void 0,void 0,function*(){const o=[];console.log(`System:AppData/${e.nqName}/${t.options.testData}`);for(const e of n.clone().columns){const n=yield t.apply([e]);o.push(n||e.semType)}const r=o.filter(e=>e);C(r.length,1),t.options.testDataColumnName&&C(r[0],t.options.testDataColumnName)}),{skipReason:t.options.skipTest});x.push(s)}}h[P]=!0,N.length>0&&(S[p]={tests:N,clear:!0}),A.length>0&&(S[d]={tests:A,clear:!0}),x.length>0&&(S[f]={tests:x,clear:!1})})}function S(e){var t,n,o;return r(this,void 0,void 0,function*(){const p=(null==e?void 0:e.nodeOptions)?e.nodeOptions.package:grok.functions.getCurrentCall().func.package;if(!p)throw new Error("Can't run tests outside of the package");const d=null===(t=p.packageOwner)||void 0===t?void 0:t.match(/<([^>]*)>/),f=d?d[1]:"";null!=p&&(yield P(p));const g=[];console.log("Running tests..."),console.log(e),null!=e||(e={}),null!==(n=(o=e).testContext)&&void 0!==n||(o.testContext=new w),grok.shell.clearLastError();const h=function(){const e=[];return console.log=(...t)=>{e.push(...t),i(...t)},console.info=(...t)=>{e.push(...t),l(...t)},console.warn=(...t)=>{e.push(...t),c(...t)},console.error=(...t)=>{e.push(...t),u(...t)},e}();yield function(e,t){var n,o,s,a,m,d;return r(this,void 0,void 0,function*(){try{let l=null!=(null==t?void 0:t.skipToCategory),c=!1;for(const[u,h]of Object.entries(e)){if(null===(n=t.exclude)||void 0===n?void 0:n.some(e=>u.startsWith(e)))continue;if(null!=(null==t?void 0:t.category)&&!u.toLowerCase().startsWith(null==t?void 0:t.category.toLowerCase().trim()))continue;if(l)if(c)l=!1;else{if(null==(null==t?void 0:t.skipToCategory)||u.toLowerCase().trim()!==(null==t?void 0:t.skipToCategory.toLowerCase().trim()))continue;c=!0}const e=null===(o=h.tests)||void 0===o?void 0:o.every(e=>{var n;return(null===(n=e.options)||void 0===n?void 0:n.skipReason)||null!=(null==t?void 0:t.test)&&t.test.toLowerCase()!==e.name.toLowerCase()});if(!e){const e=(null!==(s=h.tests)&&void 0!==s?s:[]).filter(e=>{var n;return(null===(n=e.options)||void 0===n?void 0:n.skipReason)||null!=(null==t?void 0:t.test)&&t.test.toLowerCase()!==e.name.toLowerCase()}).length;i(`Package testing: Started {{${u}}}${e>0?` skipped {{${e}}}`:""}`),h.beforeStatus=yield y(h.before,u)}let w,v=null!==(a=h.tests)&&void 0!==a?a:[];t.stressTest&&(v=v.filter(e=>{var t;return null===(t=e.options)||void 0===t?void 0:t.stressTest}),v=x(v)),(null!==(d=null===(m=t.tags)||void 0===m?void 0:m.length)&&void 0!==d?d:0)>0&&(v=v.filter(e=>{var n,o;return null===(o=null===(n=e.options)||void 0===n?void 0:n.tags)||void 0===o?void 0:o.some(e=>{var n;return(null!==(n=null==t?void 0:t.tags)&&void 0!==n?n:[]).includes(e)})})),h.beforeStatus?(w=Array.from(v.map(e=>({date:(new Date).toISOString(),category:u,name:e.name,success:!1,result:"before() failed",ms:0,skipped:!1,logs:"",owner:f,package:p.name,widgetsDifference:0,flaking:DG.Test.isReproducing}))),w.forEach(e=>r(this,void 0,void 0,function*(){return yield grok.shell.reportTest("package",e)}))):w=yield E(h,t,l);const _=w.filter(e=>"skipped"!=e.result);if(e||(h.afterStatus=yield y(h.after,u)),h.afterStatus&&(i(`Package testing: Category after() {{${u}}} failed`),i(`Package testing: Result for {{${u}}} after: ${h.afterStatus}`),_.push({date:(new Date).toISOString(),category:u,name:"after",success:!1,result:h.afterStatus,ms:0,skipped:!1,logs:"",owner:f,package:p.name,widgetsDifference:0,flaking:DG.Test.isReproducing})),h.beforeStatus&&(i(`Package testing: Category before() {{${u}}} failed`),i(`Package testing: Result for {{${u}}} before: ${h.beforeStatus}`),_.push({date:(new Date).toISOString(),category:u,name:"before",success:!1,result:h.beforeStatus,ms:0,skipped:!1,logs:"",owner:f,package:p.name,widgetsDifference:0,flaking:DG.Test.isReproducing})),g.push(..._),t.returnOnFail&&_.some(e=>!e.success&&!e.skipped&&e.name!==t.skipToTest))break}}finally{console.log=i,console.info=l,console.warn=c,console.error=u}if(t.testContext.catchUnhandled&&!DG.Test.isInBenchmark){yield D(1e3);const e=yield grok.shell.lastError;if(null!=e){const t={logs:"",date:(new Date).toISOString(),category:"Unhandled exceptions",name:"Exception",result:null!=e?e:"",success:!e,ms:0,skipped:!1,owner:null!=f?f:"",package:p.name,widgetsDifference:0};i(`Package testing: Unhandled Exception: ${e}`),g.push(Object.assign(Object.assign({},t),{flaking:DG.Test.isReproducing&&!e})),t.package=p.name,yield grok.shell.reportTest("package",t)}}})}(m,e);for(let e of g)e.result=e.result.toString().replace(/"/g,"'"),null!=e.logs&&(e.logs=e.logs.toString().replace(/"/g,"'"));return g;function y(e,t){return r(this,void 0,void 0,function*(){let n;try{void 0!==e&&(yield F(()=>r(this,void 0,void 0,function*(){yield e()}),1e5,`before ${t}: timeout error`))}catch(e){n=yield N(e)}return n})}function E(e,t,n){var o,i,l,c,u,m,d,g,y,E,w,_,C,b,T,P,S,N;return r(this,void 0,void 0,function*(){let r=null!==(o=e.tests)&&void 0!==o?o:[];const x=[],D=v();if(e.clear){let o=n&&null!=t.skipToTest;for(let n=0;n<r.length;n++){r[n].options&&void 0===(null===(i=r[n].options)||void 0===i?void 0:i.benchmark)&&(r[n].options||(r[n].options={}),r[n].options.benchmark=null!==(l=e.benchmarks)&&void 0!==l&&l);let _=r[n];if(t.test&&t.test.toLowerCase()!==_.name.toLowerCase())continue;if(o){if(null==(null==t?void 0:t.skipToTest)||_.name.toLowerCase().trim()!==(null==t?void 0:t.skipToTest.toLowerCase().trim()))continue;o=!1}(null==_?void 0:_.options)&&(_.options.owner=null!==(d=null!==(m=null!==(u=null===(c=r[n].options)||void 0===c?void 0:c.owner)&&void 0!==u?u:null==e?void 0:e.owner)&&void 0!==m?m:f)&&void 0!==d?d:"");let C=yield A(_,null==t?void 0:t.test,h,DG.Test.isInBenchmark?null!==(y=null===(g=r[n].options)||void 0===g?void 0:g.benchmarkTimeout)&&void 0!==y?y:a:null!==(w=null===(E=r[n].options)||void 0===E?void 0:E.timeout)&&void 0!==w?w:s,p.name,t.verbose);if(C&&(x.push(Object.assign(Object.assign({},C),{widgetsDifference:v()-D})),t.returnOnFail&&t.skipToTest!==_.name&&!C.success&&!C.skipped))return x;t.nodeOptions||(grok.shell.closeAll(),DG.Balloon.closeAll())}}else{let o=n&&null!=t.skipToTest;for(let n=0;n<r.length;n++){let s=r[n];if(t.test&&t.test.toLowerCase()!==s.name.toLowerCase())continue;if(o){null!=(null==t?void 0:t.skipToTest)&&s.name.toLowerCase().trim()===(null==t?void 0:t.skipToTest.toLowerCase().trim())&&(o=!1);continue}(null==s?void 0:s.options)&&(s.options.owner=null!==(T=null!==(b=null!==(C=null===(_=r[n].options)||void 0===_?void 0:_.owner)&&void 0!==C?C:null==e?void 0:e.owner)&&void 0!==b?b:f)&&void 0!==T?T:"");let i=yield A(s,null==t?void 0:t.test,h,DG.Test.isInBenchmark?null!==(S=null===(P=r[n].options)||void 0===P?void 0:P.benchmarkTimeout)&&void 0!==S?S:a:null===(N=r[n].options)||void 0===N?void 0:N.timeout,p.name,t.verbose);if(i&&(x.push(Object.assign(Object.assign({},i),{widgetsDifference:v()-D})),t.returnOnFail&&t.skipToTest!==s.name&&!i.success&&!i.skipped))return x}}return x})}function v(){var e;if("undefined"!=typeof process)return 0;let t=-1;try{t=DG.Widget.getAll().length}catch(t){console.warn(null!==(e=t.message)&&void 0!==e?e:t)}return t}})}function N(e){return r(this,void 0,void 0,function*(){return`${e.toString()}\n${e.stack?yield DG.Logger.translateStackTrace(e.stack):""}`})}function A(e,t,n,o,a,l){var c,m,p,d,f,g,h,y,E,w,v,_,C,b;return r(this,void 0,void 0,function*(){let r;n.length=0;const T=null!=t&&e.name.toLowerCase()!==t.toLowerCase();let P=(null===(c=e.options)||void 0===c?void 0:c.skipReason)||T,S=T?"skipped":null===(m=e.options)||void 0===m?void 0:m.skipReason;if(DG.Test.isInBenchmark&&!(null===(p=e.options)||void 0===p?void 0:p.benchmark))return void i(`Package testing: Skipped {{${e.category}}} {{${e.name}}} doesnt available in benchmark mode`);P&&!DG.Test.isInBenchmark&&i(`Package testing: Skipped {{${e.category}}} {{${e.name}}}`),P||i(`Package testing: Started {{${e.category}}} {{${e.name}}}`);const A=Date.now(),x=new Date(A).toISOString();try{if(P)r={name:e.name,owner:null!==(f=null===(d=e.options)||void 0===d?void 0:d.owner)&&void 0!==f?f:"",category:e.category,logs:"",date:x,success:!0,result:S,ms:0,skipped:!0,package:null!=a?a:"",flaking:DG.Test.isReproducing};else{let t=null!=o?o:s;DG.Test.isProfiling&&console.profile(`${e.category}: ${e.name}`),r={name:e.name,owner:null!==(h=null===(g=e.options)||void 0===g?void 0:g.owner)&&void 0!==h?h:"",category:e.category,logs:"",date:x,success:!0,result:null!==(y=(yield F(e.test,t)).toString())&&void 0!==y?y:"OK",ms:0,skipped:!1,package:null!=a?a:"",flaking:DG.Test.isReproducing},DG.Test.isProfiling&&(console.profileEnd(`${e.category}: ${e.name}`),grok.shell.info(`Profiling of ${e.category}: ${e.name} finished \n Please ensure that you have opened DevTools (F12) / Performance panel before test starts.`))}}catch(t){u(t),r={name:e.name,owner:null!==(w=null===(E=e.options)||void 0===E?void 0:E.owner)&&void 0!==w?w:"",category:e.category,logs:"",date:x,success:!1,result:yield N(t),ms:0,skipped:!1,package:null!=a?a:"",flaking:!1}}if((null===(v=e.options)||void 0===v?void 0:v.isAggregated)&&r.result.constructor===DG.DataFrame){const e=r.result.col("success");if(e&&(r.success=e.stats.sum===e.length),!l){const e=r.result;e.columns.remove("stack"),e.rows.removeWhere(e=>e.get("success")),r.result=e}r.result=r.result.toCsv()}if(r.logs=n.join("\n"),r.ms=Date.now()-A,P||i(`Package testing: Finished {{${e.category}}} {{${e.name}}} with {{${r.success?"success":"error"}}} for ${r.ms} ms`),r.success||i(`Package testing: Result for {{${e.category}}} {{${e.name}}}: ${r.result}`),r.category=e.category,r.name=e.name,r.owner=null!==(C=null===(_=e.options)||void 0===_?void 0:_.owner)&&void 0!==C?C:"",!T){let t={success:r.success,result:r.result,ms:r.ms,date:r.date,skipped:r.skipped,category:e.category,name:e.name,logs:r.logs,owner:r.owner,flaking:DG.Test.isReproducing&&r.success,package:r.package};if(r.result.constructor==Object){const e=Object.keys(r.result).reduce((e,t)=>Object.assign(Object.assign({},e),{["result."+t]:r.result[t]}),{});t=Object.assign(Object.assign({},t),e)}t.result instanceof DG.DataFrame&&(t.result=JSON.stringify(null===(b=t.result)||void 0===b?void 0:b.toJson())||""),yield grok.shell.reportTest("package",t)}return r})}function x(e){const t=e.slice();return t.sort(()=>Math.random()-.5),t}function D(e){return r(this,void 0,void 0,function*(){yield new Promise(t=>setTimeout(t,e))})}function L(e,t="Timeout exceeded",n=500,o=50){return r(this,void 0,void 0,function*(){return new Promise((r,s)=>{setTimeout(()=>{clearInterval(a),s(new Error(t))},n);const a=setInterval(()=>{e()&&(clearInterval(a),r(null))},o)})})}function F(e,t,n="EXECUTION TIMEOUT"){return r(this,void 0,void 0,function*(){let o=null;const r=new Promise((e,r)=>{o=setTimeout(()=>{r(n)},t)});try{return yield Promise.race([e(),r])}finally{o&&clearTimeout(o)}})}DG.DataFrame.fromColumns([DG.Column.fromStrings("col",["val1","val2","val3"])])},353(e){e.exports=function(){"use strict";var e=6e4,t=36e5,n="millisecond",o="second",r="minute",s="hour",a="day",i="week",l="month",c="quarter",u="year",m="date",p="Invalid Date",d=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,f=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,g={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(e){var t=["th","st","nd","rd"],n=e%100;return"["+e+(t[(n-20)%10]||t[n]||t[0])+"]"}},h=function(e,t,n){var o=String(e);return!o||o.length>=t?e:""+Array(t+1-o.length).join(n)+e},y={s:h,z:function(e){var t=-e.utcOffset(),n=Math.abs(t),o=Math.floor(n/60),r=n%60;return(t<=0?"+":"-")+h(o,2,"0")+":"+h(r,2,"0")},m:function e(t,n){if(t.date()<n.date())return-e(n,t);var o=12*(n.year()-t.year())+(n.month()-t.month()),r=t.clone().add(o,l),s=n-r<0,a=t.clone().add(o+(s?-1:1),l);return+(-(o+(n-r)/(s?r-a:a-r))||0)},a:function(e){return e<0?Math.ceil(e)||0:Math.floor(e)},p:function(e){return{M:l,y:u,w:i,d:a,D:m,h:s,m:r,s:o,ms:n,Q:c}[e]||String(e||"").toLowerCase().replace(/s$/,"")},u:function(e){return void 0===e}},E="en",w={};w[E]=g;var v="$isDayjsObject",_=function(e){return e instanceof P||!(!e||!e[v])},C=function e(t,n,o){var r;if(!t)return E;if("string"==typeof t){var s=t.toLowerCase();w[s]&&(r=s),n&&(w[s]=n,r=s);var a=t.split("-");if(!r&&a.length>1)return e(a[0])}else{var i=t.name;w[i]=t,r=i}return!o&&r&&(E=r),r||!o&&E},b=function(e,t){if(_(e))return e.clone();var n="object"==typeof t?t:{};return n.date=e,n.args=arguments,new P(n)},T=y;T.l=C,T.i=_,T.w=function(e,t){return b(e,{locale:t.$L,utc:t.$u,x:t.$x,$offset:t.$offset})};var P=function(){function g(e){this.$L=C(e.locale,null,!0),this.parse(e),this.$x=this.$x||e.x||{},this[v]=!0}var h=g.prototype;return h.parse=function(e){this.$d=function(e){var t=e.date,n=e.utc;if(null===t)return new Date(NaN);if(T.u(t))return new Date;if(t instanceof Date)return new Date(t);if("string"==typeof t&&!/Z$/i.test(t)){var o=t.match(d);if(o){var r=o[2]-1||0,s=(o[7]||"0").substring(0,3);return n?new Date(Date.UTC(o[1],r,o[3]||1,o[4]||0,o[5]||0,o[6]||0,s)):new Date(o[1],r,o[3]||1,o[4]||0,o[5]||0,o[6]||0,s)}}return new Date(t)}(e),this.init()},h.init=function(){var e=this.$d;this.$y=e.getFullYear(),this.$M=e.getMonth(),this.$D=e.getDate(),this.$W=e.getDay(),this.$H=e.getHours(),this.$m=e.getMinutes(),this.$s=e.getSeconds(),this.$ms=e.getMilliseconds()},h.$utils=function(){return T},h.isValid=function(){return!(this.$d.toString()===p)},h.isSame=function(e,t){var n=b(e);return this.startOf(t)<=n&&n<=this.endOf(t)},h.isAfter=function(e,t){return b(e)<this.startOf(t)},h.isBefore=function(e,t){return this.endOf(t)<b(e)},h.$g=function(e,t,n){return T.u(e)?this[t]:this.set(n,e)},h.unix=function(){return Math.floor(this.valueOf()/1e3)},h.valueOf=function(){return this.$d.getTime()},h.startOf=function(e,t){var n=this,c=!!T.u(t)||t,p=T.p(e),d=function(e,t){var o=T.w(n.$u?Date.UTC(n.$y,t,e):new Date(n.$y,t,e),n);return c?o:o.endOf(a)},f=function(e,t){return T.w(n.toDate()[e].apply(n.toDate("s"),(c?[0,0,0,0]:[23,59,59,999]).slice(t)),n)},g=this.$W,h=this.$M,y=this.$D,E="set"+(this.$u?"UTC":"");switch(p){case u:return c?d(1,0):d(31,11);case l:return c?d(1,h):d(0,h+1);case i:var w=this.$locale().weekStart||0,v=(g<w?g+7:g)-w;return d(c?y-v:y+(6-v),h);case a:case m:return f(E+"Hours",0);case s:return f(E+"Minutes",1);case r:return f(E+"Seconds",2);case o:return f(E+"Milliseconds",3);default:return this.clone()}},h.endOf=function(e){return this.startOf(e,!1)},h.$set=function(e,t){var i,c=T.p(e),p="set"+(this.$u?"UTC":""),d=(i={},i[a]=p+"Date",i[m]=p+"Date",i[l]=p+"Month",i[u]=p+"FullYear",i[s]=p+"Hours",i[r]=p+"Minutes",i[o]=p+"Seconds",i[n]=p+"Milliseconds",i)[c],f=c===a?this.$D+(t-this.$W):t;if(c===l||c===u){var g=this.clone().set(m,1);g.$d[d](f),g.init(),this.$d=g.set(m,Math.min(this.$D,g.daysInMonth())).$d}else d&&this.$d[d](f);return this.init(),this},h.set=function(e,t){return this.clone().$set(e,t)},h.get=function(e){return this[T.p(e)]()},h.add=function(n,c){var m,p=this;n=Number(n);var d=T.p(c),f=function(e){var t=b(p);return T.w(t.date(t.date()+Math.round(e*n)),p)};if(d===l)return this.set(l,this.$M+n);if(d===u)return this.set(u,this.$y+n);if(d===a)return f(1);if(d===i)return f(7);var g=(m={},m[r]=e,m[s]=t,m[o]=1e3,m)[d]||1,h=this.$d.getTime()+n*g;return T.w(h,this)},h.subtract=function(e,t){return this.add(-1*e,t)},h.format=function(e){var t=this,n=this.$locale();if(!this.isValid())return n.invalidDate||p;var o=e||"YYYY-MM-DDTHH:mm:ssZ",r=T.z(this),s=this.$H,a=this.$m,i=this.$M,l=n.weekdays,c=n.months,u=n.meridiem,m=function(e,n,r,s){return e&&(e[n]||e(t,o))||r[n].slice(0,s)},d=function(e){return T.s(s%12||12,e,"0")},g=u||function(e,t,n){var o=e<12?"AM":"PM";return n?o.toLowerCase():o};return o.replace(f,function(e,o){return o||function(e){switch(e){case"YY":return String(t.$y).slice(-2);case"YYYY":return T.s(t.$y,4,"0");case"M":return i+1;case"MM":return T.s(i+1,2,"0");case"MMM":return m(n.monthsShort,i,c,3);case"MMMM":return m(c,i);case"D":return t.$D;case"DD":return T.s(t.$D,2,"0");case"d":return String(t.$W);case"dd":return m(n.weekdaysMin,t.$W,l,2);case"ddd":return m(n.weekdaysShort,t.$W,l,3);case"dddd":return l[t.$W];case"H":return String(s);case"HH":return T.s(s,2,"0");case"h":return d(1);case"hh":return d(2);case"a":return g(s,a,!0);case"A":return g(s,a,!1);case"m":return String(a);case"mm":return T.s(a,2,"0");case"s":return String(t.$s);case"ss":return T.s(t.$s,2,"0");case"SSS":return T.s(t.$ms,3,"0");case"Z":return r}return null}(e)||r.replace(":","")})},h.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},h.diff=function(n,m,p){var d,f=this,g=T.p(m),h=b(n),y=(h.utcOffset()-this.utcOffset())*e,E=this-h,w=function(){return T.m(f,h)};switch(g){case u:d=w()/12;break;case l:d=w();break;case c:d=w()/3;break;case i:d=(E-y)/6048e5;break;case a:d=(E-y)/864e5;break;case s:d=E/t;break;case r:d=E/e;break;case o:d=E/1e3;break;default:d=E}return p?d:T.a(d)},h.daysInMonth=function(){return this.endOf(l).$D},h.$locale=function(){return w[this.$L]},h.locale=function(e,t){if(!e)return this.$L;var n=this.clone(),o=C(e,t,!0);return o&&(n.$L=o),n},h.clone=function(){return T.w(this.$d,this)},h.toDate=function(){return new Date(this.valueOf())},h.toJSON=function(){return this.isValid()?this.toISOString():null},h.toISOString=function(){return this.$d.toISOString()},h.toString=function(){return this.$d.toUTCString()},g}(),S=P.prototype;return b.prototype=S,[["$ms",n],["$s",o],["$m",r],["$H",s],["$W",a],["$M",l],["$y",u],["$D",m]].forEach(function(e){S[e[1]]=function(t){return this.$g(t,e[0],e[1])}}),b.extend=function(e,t){return e.$i||(e(t,P,b),e.$i=!0),b},b.locale=C,b.isDayjs=_,b.unix=function(e){return b(1e3*e)},b.en=w[E],b.Ls=w,b.p={},b}()},982(e,t,n){var o;!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,o,r,s){for(var a,i,l,c,u,m,p,d,f,g,h,y,E;s>=64;){for(a=n[0],i=n[1],l=n[2],c=n[3],u=n[4],m=n[5],p=n[6],d=n[7],g=0;g<16;g++)h=r+4*g,e[g]=(255&o[h])<<24|(255&o[h+1])<<16|(255&o[h+2])<<8|255&o[h+3];for(g=16;g<64;g++)y=((f=e[g-2])>>>17|f<<15)^(f>>>19|f<<13)^f>>>10,E=((f=e[g-15])>>>7|f<<25)^(f>>>18|f<<14)^f>>>3,e[g]=(y+e[g-7]|0)+(E+e[g-16]|0);for(g=0;g<64;g++)y=(((u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7))+(u&m^~u&p)|0)+(d+(t[g]+e[g]|0)|0)|0,E=((a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10))+(a&i^a&l^i&l)|0,d=p,p=m,m=u,u=c+y|0,c=l,l=i,i=a,a=y+E|0;n[0]+=a,n[1]+=i,n[2]+=l,n[3]+=c,n[4]+=u,n[5]+=m,n[6]+=p,n[7]+=d,r+=64,s-=64}return r}var o=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 o=0;if(this.bytesHashed+=t,this.bufferLength>0){for(;this.bufferLength<64&&t>0;)this.buffer[this.bufferLength++]=e[o++],t--;64===this.bufferLength&&(n(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(t>=64&&(o=n(this.temp,this.state,e,o,t),t%=64);t>0;)this.buffer[this.bufferLength++]=e[o++],t--;return this},t.prototype.finish=function(e){if(!this.finished){var t=this.bytesHashed,o=this.bufferLength,r=t/536870912|0,s=t<<3,a=t%64<56?64:128;this.buffer[o]=128;for(var i=o+1;i<a-8;i++)this.buffer[i]=0;this.buffer[a-8]=r>>>24&255,this.buffer[a-7]=r>>>16&255,this.buffer[a-6]=r>>>8&255,this.buffer[a-5]=r>>>0&255,this.buffer[a-4]=s>>>24&255,this.buffer[a-3]=s>>>16&255,this.buffer[a-2]=s>>>8&255,this.buffer[a-1]=s>>>0&255,n(this.temp,this.state,this.buffer,0,a),this.finished=!0}for(i=0;i<8;i++)e[4*i+0]=this.state[i]>>>24&255,e[4*i+1]=this.state[i]>>>16&255,e[4*i+2]=this.state[i]>>>8&255,e[4*i+3]=this.state[i]>>>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=o;var r=function(){function e(e){this.inner=new o,this.outer=new o,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var t=new Uint8Array(this.blockSize);if(e.length>this.blockSize)(new o).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 o).update(e),n=t.digest();return t.clean(),n}function a(e,t){var n=new r(e).update(t),o=n.digest();return n.clean(),o}function i(e,t,n,o){var r=o[0];if(0===r)throw new Error("hkdf: cannot expand more");t.reset(),r>1&&t.update(e),n&&t.update(n),t.update(o),t.finish(e),o[0]++}e.HMAC=r,e.hash=s,e.default=s,e.hmac=a;var l=new Uint8Array(e.digestLength);e.hkdf=function(e,t,n,o){void 0===t&&(t=l),void 0===o&&(o=32);for(var s=new Uint8Array([1]),c=a(t,e),u=new r(c),m=new Uint8Array(u.digestLength),p=m.length,d=new Uint8Array(o),f=0;f<o;f++)p===m.length&&(i(m,u,n,s),p=0),d[f]=m[p++];return u.clean(),m.fill(0),s.fill(0),d},e.pbkdf2=function(e,t,n,o){for(var s=new r(e),a=s.digestLength,i=new Uint8Array(4),l=new Uint8Array(a),c=new Uint8Array(a),u=new Uint8Array(o),m=0;m*a<o;m++){var p=m+1;i[0]=p>>>24&255,i[1]=p>>>16&255,i[2]=p>>>8&255,i[3]=p>>>0&255,s.reset(),s.update(t),s.update(i),s.finish(c);for(var d=0;d<a;d++)l[d]=c[d];for(d=2;d<=n;d++){s.reset(),s.update(c).finish(c);for(var f=0;f<a;f++)l[f]^=c[f]}for(d=0;d<a&&m*a+d<o;d++)u[m*a+d]=l[d]}for(m=0;m<a;m++)l[m]=c[m]=0;for(m=0;m<4;m++)i[m]=0;return s.clean(),u}}(t);var r=t.default;for(var s in t)r[s]=t[s];"object"==typeof e.exports?e.exports=r:void 0===(o=function(){return r}.call(t,n,t,e))||(e.exports=o)}()},572(e){var t;e.exports=(t=function(e,t){var n=Array.prototype.concat,o=Array.prototype.slice,r=Object.prototype.toString;function s(t,n){var o=t>n?t:n;return e.pow(10,17-~~(e.log(o>0?o:-o)*e.LOG10E))}var a=Array.isArray||function(e){return"[object Array]"===r.call(e)};function i(e){return"[object Function]"===r.call(e)}function l(e){return"number"==typeof e&&e-e===0}function c(){return new c._init(arguments)}function u(){return 0}function m(){return 1}function p(e,t){return e===t?1:0}c.fn=c.prototype,c._init=function(e){if(a(e[0]))if(a(e[0][0])){i(e[1])&&(e[0]=c.map(e[0],e[1]));for(var t=0;t<e[0].length;t++)this[t]=e[0][t];this.length=e[0].length}else this[0]=i(e[1])?c.map(e[0],e[1]):e[0],this.length=1;else if(l(e[0]))this[0]=c.seq.apply(null,e),this.length=1;else{if(e[0]instanceof c)return c(e[0].toArray());this[0]=[],this.length=1}return this},c._init.prototype=c.prototype,c._init.constructor=c,c.utils={calcRdx:s,isArray:a,isFunction:i,isNumber:l,toVector:function(e){return n.apply([],e)}},c._random_fn=e.random,c.setRandom=function(e){if("function"!=typeof e)throw new TypeError("fn is not a function");c._random_fn=e},c.extend=function(e){var t,n;if(1===arguments.length){for(n in e)c[n]=e[n];return this}for(t=1;t<arguments.length;t++)for(n in arguments[t])e[n]=arguments[t][n];return e},c.rows=function(e){return e.length||1},c.cols=function(e){return e[0].length||1},c.dimensions=function(e){return{rows:c.rows(e),cols:c.cols(e)}},c.row=function(e,t){return a(t)?t.map(function(t){return c.row(e,t)}):e[t]},c.rowa=function(e,t){return c.row(e,t)},c.col=function(e,t){if(a(t)){var n=c.arange(e.length).map(function(){return new Array(t.length)});return t.forEach(function(t,o){c.arange(e.length).forEach(function(r){n[r][o]=e[r][t]})}),n}for(var o=new Array(e.length),r=0;r<e.length;r++)o[r]=[e[r][t]];return o},c.cola=function(e,t){return c.col(e,t).map(function(e){return e[0]})},c.diag=function(e){for(var t=c.rows(e),n=new Array(t),o=0;o<t;o++)n[o]=[e[o][o]];return n},c.antidiag=function(e){for(var t=c.rows(e)-1,n=new Array(t),o=0;t>=0;t--,o++)n[o]=[e[o][t]];return n},c.transpose=function(e){var t,n,o,r,s,i=[];for(a(e[0])||(e=[e]),n=e.length,o=e[0].length,s=0;s<o;s++){for(t=new Array(n),r=0;r<n;r++)t[r]=e[r][s];i.push(t)}return 1===i.length?i[0]:i},c.map=function(e,t,n){var o,r,s,i,l;for(a(e[0])||(e=[e]),r=e.length,s=e[0].length,i=n?e:new Array(r),o=0;o<r;o++)for(i[o]||(i[o]=new Array(s)),l=0;l<s;l++)i[o][l]=t(e[o][l],o,l);return 1===i.length?i[0]:i},c.cumreduce=function(e,t,n){var o,r,s,i,l;for(a(e[0])||(e=[e]),r=e.length,s=e[0].length,i=n?e:new Array(r),o=0;o<r;o++)for(i[o]||(i[o]=new Array(s)),s>0&&(i[o][0]=e[o][0]),l=1;l<s;l++)i[o][l]=t(i[o][l-1],e[o][l]);return 1===i.length?i[0]:i},c.alter=function(e,t){return c.map(e,t,!0)},c.create=function(e,t,n){var o,r,s=new Array(e);for(i(t)&&(n=t,t=e),o=0;o<e;o++)for(s[o]=new Array(t),r=0;r<t;r++)s[o][r]=n(o,r);return s},c.zeros=function(e,t){return l(t)||(t=e),c.create(e,t,u)},c.ones=function(e,t){return l(t)||(t=e),c.create(e,t,m)},c.rand=function(e,t){return l(t)||(t=e),c.create(e,t,c._random_fn)},c.identity=function(e,t){return l(t)||(t=e),c.create(e,t,p)},c.symmetric=function(e){var t,n,o=e.length;if(e.length!==e[0].length)return!1;for(t=0;t<o;t++)for(n=0;n<o;n++)if(e[n][t]!==e[t][n])return!1;return!0},c.clear=function(e){return c.alter(e,u)},c.seq=function(e,t,n,o){i(o)||(o=!1);var r,a=[],l=s(e,t),c=(t*l-e*l)/((n-1)*l),u=e;for(r=0;u<=t&&r<n;u=(e*l+c*l*++r)/l)a.push(o?o(u,r):u);return a},c.arange=function(e,n,o){var r,s=[];if(o=o||1,n===t&&(n=e,e=0),e===n||0===o)return[];if(e<n&&o<0)return[];if(e>n&&o>0)return[];if(o>0)for(r=e;r<n;r+=o)s.push(r);else for(r=e;r>n;r+=o)s.push(r);return s},c.slice=function(){function e(e,n,o,r){var s,a=[],i=e.length;if(n===t&&o===t&&r===t)return c.copy(e);if(r=r||1,(n=(n=n||0)>=0?n:i+n)===(o=(o=o||e.length)>=0?o:i+o)||0===r)return[];if(n<o&&r<0)return[];if(n>o&&r>0)return[];if(r>0)for(s=n;s<o;s+=r)a.push(e[s]);else for(s=n;s>o;s+=r)a.push(e[s]);return a}return function(t,n){var o,r;return l((n=n||{}).row)?l(n.col)?t[n.row][n.col]:e(c.rowa(t,n.row),(o=n.col||{}).start,o.end,o.step):l(n.col)?e(c.cola(t,n.col),(r=n.row||{}).start,r.end,r.step):(r=n.row||{},o=n.col||{},e(t,r.start,r.end,r.step).map(function(t){return e(t,o.start,o.end,o.step)}))}}(),c.sliceAssign=function(n,o,r){var s,a;if(l(o.row)){if(l(o.col))return n[o.row][o.col]=r;o.col=o.col||{},o.col.start=o.col.start||0,o.col.end=o.col.end||n[0].length,o.col.step=o.col.step||1,s=c.arange(o.col.start,e.min(n.length,o.col.end),o.col.step);var i=o.row;return s.forEach(function(e,t){n[i][e]=r[t]}),n}if(l(o.col)){o.row=o.row||{},o.row.start=o.row.start||0,o.row.end=o.row.end||n.length,o.row.step=o.row.step||1,a=c.arange(o.row.start,e.min(n[0].length,o.row.end),o.row.step);var u=o.col;return a.forEach(function(e,t){n[e][u]=r[t]}),n}return r[0].length===t&&(r=[r]),o.row.start=o.row.start||0,o.row.end=o.row.end||n.length,o.row.step=o.row.step||1,o.col.start=o.col.start||0,o.col.end=o.col.end||n[0].length,o.col.step=o.col.step||1,a=c.arange(o.row.start,e.min(n.length,o.row.end),o.row.step),s=c.arange(o.col.start,e.min(n[0].length,o.col.end),o.col.step),a.forEach(function(e,t){s.forEach(function(o,s){n[e][o]=r[t][s]})}),n},c.diagonal=function(e){var t=c.zeros(e.length,e.length);return e.forEach(function(e,n){t[n][n]=e}),t},c.copy=function(e){return e.map(function(e){return l(e)?e:e.map(function(e){return e})})};var d=c.prototype;return d.length=0,d.push=Array.prototype.push,d.sort=Array.prototype.sort,d.splice=Array.prototype.splice,d.slice=Array.prototype.slice,d.toArray=function(){return this.length>1?o.call(this):o.call(this)[0]},d.map=function(e,t){return c(c.map(this,e,t))},d.cumreduce=function(e,t){return c(c.cumreduce(this,e,t))},d.alter=function(e){return c.alter(this,e),this},function(e){for(var t=0;t<e.length;t++)(function(e){d[e]=function(t){var n,o=this;return t?(setTimeout(function(){t.call(o,d[e].call(o))}),this):(n=c[e](this),a(n)?c(n):n)}})(e[t])}("transpose clear symmetric rows cols dimensions diag antidiag".split(" ")),function(e){for(var t=0;t<e.length;t++)(function(e){d[e]=function(t,n){var o=this;return n?(setTimeout(function(){n.call(o,d[e].call(o,t))}),this):c(c[e](this,t))}})(e[t])}("row col".split(" ")),function(e){for(var t=0;t<e.length;t++)(function(e){d[e]=function(){return c(c[e].apply(null,arguments))}})(e[t])}("create zeros ones rand identity".split(" ")),c}(Math),function(e,t){var n=e.utils.isFunction;function o(e,t){return e-t}function r(e,n,o){return t.max(n,t.min(e,o))}e.sum=function(e){for(var t=0,n=e.length;--n>=0;)t+=e[n];return t},e.sumsqrd=function(e){for(var t=0,n=e.length;--n>=0;)t+=e[n]*e[n];return t},e.sumsqerr=function(t){for(var n,o=e.mean(t),r=0,s=t.length;--s>=0;)r+=(n=t[s]-o)*n;return r},e.sumrow=function(e){for(var t=0,n=e.length;--n>=0;)t+=e[n];return t},e.product=function(e){for(var t=1,n=e.length;--n>=0;)t*=e[n];return t},e.min=function(e){for(var t=e[0],n=0;++n<e.length;)e[n]<t&&(t=e[n]);return t},e.max=function(e){for(var t=e[0],n=0;++n<e.length;)e[n]>t&&(t=e[n]);return t},e.unique=function(e){for(var t={},n=[],o=0;o<e.length;o++)t[e[o]]||(t[e[o]]=!0,n.push(e[o]));return n},e.mean=function(t){return e.sum(t)/t.length},e.meansqerr=function(t){return e.sumsqerr(t)/t.length},e.geomean=function(n){var o=n.map(t.log),r=e.mean(o);return t.exp(r)},e.median=function(e){var t=e.length,n=e.slice().sort(o);return 1&t?n[t/2|0]:(n[t/2-1]+n[t/2])/2},e.cumsum=function(t){return e.cumreduce(t,function(e,t){return e+t})},e.cumprod=function(t){return e.cumreduce(t,function(e,t){return e*t})},e.diff=function(e){var t,n=[],o=e.length;for(t=1;t<o;t++)n.push(e[t]-e[t-1]);return n},e.rank=function(e){var t,n=[],r={};for(t=0;t<e.length;t++)r[l=e[t]]?r[l]++:(r[l]=1,n.push(l));var s=n.sort(o),a={},i=1;for(t=0;t<s.length;t++){var l,c=r[l=s[t]],u=(i+(i+c-1))/2;a[l]=u,i+=c}return e.map(function(e){return a[e]})},e.mode=function(e){var t,n=e.length,r=e.slice().sort(o),s=1,a=0,i=0,l=[];for(t=0;t<n;t++)r[t]===r[t+1]?s++:(s>a?(l=[r[t]],a=s,i=0):s===a&&(l.push(r[t]),i++),s=1);return 0===i?l[0]:l},e.range=function(t){return e.max(t)-e.min(t)},e.variance=function(t,n){return e.sumsqerr(t)/(t.length-(n?1:0))},e.pooledvariance=function(t){return t.reduce(function(t,n){return t+e.sumsqerr(n)},0)/(t.reduce(function(e,t){return e+t.length},0)-t.length)},e.deviation=function(t){for(var n=e.mean(t),o=t.length,r=new Array(o),s=0;s<o;s++)r[s]=t[s]-n;return r},e.stdev=function(n,o){return t.sqrt(e.variance(n,o))},e.pooledstdev=function(n){return t.sqrt(e.pooledvariance(n))},e.meandev=function(n){for(var o=e.mean(n),r=[],s=n.length-1;s>=0;s--)r.push(t.abs(n[s]-o));return e.mean(r)},e.meddev=function(n){for(var o=e.median(n),r=[],s=n.length-1;s>=0;s--)r.push(t.abs(n[s]-o));return e.median(r)},e.coeffvar=function(t){return e.stdev(t)/e.mean(t)},e.quartiles=function(e){var n=e.length,r=e.slice().sort(o);return[r[t.round(n/4)-1],r[t.round(n/2)-1],r[t.round(3*n/4)-1]]},e.quantiles=function(e,n,s,a){var i,l,c,u,m,p=e.slice().sort(o),d=[n.length],f=e.length;for(void 0===s&&(s=3/8),void 0===a&&(a=3/8),i=0;i<n.length;i++)c=f*(l=n[i])+(s+l*(1-s-a)),u=t.floor(r(c,1,f-1)),m=r(c-u,0,1),d[i]=(1-m)*p[u-1]+m*p[u];return d},e.percentile=function(e,t,n){var r=e.slice().sort(o),s=t*(r.length+(n?1:-1))+(n?0:1),a=parseInt(s),i=s-a;return a+1<r.length?r[a-1]+i*(r[a]-r[a-1]):r[a-1]},e.percentileOfScore=function(e,t,n){var o,r,s=0,a=e.length,i=!1;for("strict"===n&&(i=!0),r=0;r<a;r++)o=e[r],(i&&o<t||!i&&o<=t)&&s++;return s/a},e.histogram=function(n,o){o=o||4;var r,s=e.min(n),a=(e.max(n)-s)/o,i=n.length,l=[];for(r=0;r<o;r++)l[r]=0;for(r=0;r<i;r++)l[t.min(t.floor((n[r]-s)/a),o-1)]+=1;return l},e.covariance=function(t,n){var o,r=e.mean(t),s=e.mean(n),a=t.length,i=new Array(a);for(o=0;o<a;o++)i[o]=(t[o]-r)*(n[o]-s);return e.sum(i)/(a-1)},e.corrcoeff=function(t,n){return e.covariance(t,n)/e.stdev(t,1)/e.stdev(n,1)},e.spearmancoeff=function(t,n){return t=e.rank(t),n=e.rank(n),e.corrcoeff(t,n)},e.stanMoment=function(n,o){for(var r=e.mean(n),s=e.stdev(n),a=n.length,i=0,l=0;l<a;l++)i+=t.pow((n[l]-r)/s,o);return i/n.length},e.skewness=function(t){return e.stanMoment(t,3)},e.kurtosis=function(t){return e.stanMoment(t,4)-3};var s=e.prototype;!function(t){for(var o=0;o<t.length;o++)(function(t){s[t]=function(o,r){var a=[],i=0,l=this;if(n(o)&&(r=o,o=!1),r)return setTimeout(function(){r.call(l,s[t].call(l,o))}),this;if(this.length>1){for(l=!0===o?this:this.transpose();i<l.length;i++)a[i]=e[t](l[i]);return a}return e[t](this[0],o)}})(t[o])}("cumsum cumprod".split(" ")),function(t){for(var o=0;o<t.length;o++)(function(t){s[t]=function(o,r){var a=[],i=0,l=this;if(n(o)&&(r=o,o=!1),r)return setTimeout(function(){r.call(l,s[t].call(l,o))}),this;if(this.length>1){for("sumrow"!==t&&(l=!0===o?this:this.transpose());i<l.length;i++)a[i]=e[t](l[i]);return!0===o?e[t](e.utils.toVector(a)):a}return e[t](this[0],o)}})(t[o])}("sum sumsqrd sumsqerr sumrow product min max unique mean meansqerr geomean median diff rank mode range variance deviation stdev meandev meddev coeffvar quartiles histogram skewness kurtosis".split(" ")),function(t){for(var o=0;o<t.length;o++)(function(t){s[t]=function(){var o,r=[],a=0,i=this,l=Array.prototype.slice.call(arguments);if(n(l[l.length-1])){o=l[l.length-1];var c=l.slice(0,l.length-1);return setTimeout(function(){o.call(i,s[t].apply(i,c))}),this}o=void 0;var u=function(n){return e[t].apply(i,[n].concat(l))};if(this.length>1){for(i=i.transpose();a<i.length;a++)r[a]=u(i[a]);return r}return u(this[0])}})(t[o])}("quantiles percentileOfScore".split(" "))}(t,Math),function(e,t){e.gammaln=function(e){var n,o,r,s=0,a=[76.18009172947146,-86.50532032941678,24.01409824083091,-1.231739572450155,.001208650973866179,-5395239384953e-18],i=1.000000000190015;for(r=(o=n=e)+5.5,r-=(n+.5)*t.log(r);s<6;s++)i+=a[s]/++o;return t.log(2.5066282746310007*i/n)-r},e.loggam=function(e){var n,o,r,s,a,i,l,c=[.08333333333333333,-.002777777777777778,.0007936507936507937,-.0005952380952380952,.0008417508417508418,-.001917526917526918,.00641025641025641,-.02955065359477124,.1796443723688307,-1.3924322169059];if(n=e,l=0,1==e||2==e)return 0;for(e<=7&&(n=e+(l=t.floor(7-e))),o=1/(n*n),r=2*t.PI,a=c[9],i=8;i>=0;i--)a*=o,a+=c[i];if(s=a/n+.5*t.log(r)+(n-.5)*t.log(n)-n,e<=7)for(i=1;i<=l;i++)s-=t.log(n-1),n-=1;return s},e.gammafn=function(e){var n,o,r,s,a=[-1.716185138865495,24.76565080557592,-379.80425647094563,629.3311553128184,866.9662027904133,-31451.272968848367,-36144.413418691176,66456.14382024054],i=[-30.8402300119739,315.35062697960416,-1015.1563674902192,-3107.771671572311,22538.11842098015,4755.846277527881,-134659.9598649693,-115132.2596755535],l=!1,c=0,u=0,m=0,p=e;if(e>171.6243769536076)return 1/0;if(p<=0){if(!(s=p%1+36e-17))return 1/0;l=(1&p?-1:1)*t.PI/t.sin(t.PI*s),p=1-p}for(r=p,o=p<1?p++:(p-=c=(0|p)-1)-1,n=0;n<8;++n)m=(m+a[n])*o,u=u*o+i[n];if(s=m/u+1,r<p)s/=r;else if(r>p)for(n=0;n<c;++n)s*=p,p++;return l&&(s=l/s),s},e.gammap=function(t,n){return e.lowRegGamma(t,n)*e.gammafn(t)},e.lowRegGamma=function(n,o){var r,s=e.gammaln(n),a=n,i=1/n,l=i,c=o+1-n,u=1/1e-30,m=1/c,p=m,d=1,f=-~(8.5*t.log(n>=1?n:1/n)+.4*n+17);if(o<0||n<=0)return NaN;if(o<n+1){for(;d<=f;d++)i+=l*=o/++a;return i*t.exp(-o+n*t.log(o)-s)}for(;d<=f;d++)p*=(m=1/(m=(r=-d*(d-n))*m+(c+=2)))*(u=c+r/u);return 1-p*t.exp(-o+n*t.log(o)-s)},e.factorialln=function(t){return t<0?NaN:e.gammaln(t+1)},e.factorial=function(t){return t<0?NaN:e.gammafn(t+1)},e.combination=function(n,o){return n>170||o>170?t.exp(e.combinationln(n,o)):e.factorial(n)/e.factorial(o)/e.factorial(n-o)},e.combinationln=function(t,n){return e.factorialln(t)-e.factorialln(n)-e.factorialln(t-n)},e.permutation=function(t,n){return e.factorial(t)/e.factorial(t-n)},e.betafn=function(n,o){if(!(n<=0||o<=0))return n+o>170?t.exp(e.betaln(n,o)):e.gammafn(n)*e.gammafn(o)/e.gammafn(n+o)},e.betaln=function(t,n){return e.gammaln(t)+e.gammaln(n)-e.gammaln(t+n)},e.betacf=function(e,n,o){var r,s,a,i,l=1e-30,c=1,u=n+o,m=n+1,p=n-1,d=1,f=1-u*e/m;for(t.abs(f)<l&&(f=l),i=f=1/f;c<=100&&(f=1+(s=c*(o-c)*e/((p+(r=2*c))*(n+r)))*f,t.abs(f)<l&&(f=l),d=1+s/d,t.abs(d)<l&&(d=l),i*=(f=1/f)*d,f=1+(s=-(n+c)*(u+c)*e/((n+r)*(m+r)))*f,t.abs(f)<l&&(f=l),d=1+s/d,t.abs(d)<l&&(d=l),i*=a=(f=1/f)*d,!(t.abs(a-1)<3e-7));c++);return i},e.gammapinv=function(n,o){var r,s,a,i,l,c,u=0,m=o-1,p=e.gammaln(o);if(n>=1)return t.max(100,o+100*t.sqrt(o));if(n<=0)return 0;for(o>1?(l=t.log(m),c=t.exp(m*(l-1)-p),i=n<.5?n:1-n,r=(2.30753+.27061*(s=t.sqrt(-2*t.log(i))))/(1+s*(.99229+.04481*s))-s,n<.5&&(r=-r),r=t.max(.001,o*t.pow(1-1/(9*o)-r/(3*t.sqrt(o)),3))):r=n<(s=1-o*(.253+.12*o))?t.pow(n/s,1/o):1-t.log(1-(n-s)/(1-s));u<12;u++){if(r<=0)return 0;if((r-=s=(a=(e.lowRegGamma(o,r)-n)/(s=o>1?c*t.exp(-(r-m)+m*(t.log(r)-l)):t.exp(-r+m*t.log(r)-p)))/(1-.5*t.min(1,a*((o-1)/r-1))))<=0&&(r=.5*(r+s)),t.abs(s)<1e-8*r)break}return r},e.erf=function(e){var n,o,r,s,a=[-1.3026537197817094,.6419697923564902,.019476473204185836,-.00956151478680863,-.000946595344482036,.000366839497852761,42523324806907e-18,-20278578112534e-18,-1624290004647e-18,130365583558e-17,1.5626441722e-8,-8.5238095915e-8,6.529054439e-9,5.059343495e-9,-9.91364156e-10,-2.27365122e-10,96467911e-18,2394038e-18,-6886027e-18,894487e-18,313092e-18,-112708e-18,381e-18,7106e-18,-1523e-18,-94e-18,121e-18,-28e-18],i=a.length-1,l=!1,c=0,u=0;for(e<0&&(e=-e,l=!0),o=4*(n=2/(2+e))-2;i>0;i--)r=c,c=o*c-u+a[i],u=r;return s=n*t.exp(-e*e+.5*(a[0]+o*c)-u),l?s-1:1-s},e.erfc=function(t){return 1-e.erf(t)},e.erfcinv=function(n){var o,r,s,a,i=0;if(n>=2)return-100;if(n<=0)return 100;for(a=n<1?n:2-n,o=-.70711*((2.30753+.27061*(s=t.sqrt(-2*t.log(a/2))))/(1+s*(.99229+.04481*s))-s);i<2;i++)o+=(r=e.erfc(o)-a)/(1.1283791670955126*t.exp(-o*o)-o*r);return n<1?o:-o},e.ibetainv=function(n,o,r){var s,a,i,l,c,u,m,p,d,f,g=o-1,h=r-1,y=0;if(n<=0)return 0;if(n>=1)return 1;for(o>=1&&r>=1?(i=n<.5?n:1-n,u=(2.30753+.27061*(l=t.sqrt(-2*t.log(i))))/(1+l*(.99229+.04481*l))-l,n<.5&&(u=-u),m=(u*u-3)/6,p=2/(1/(2*o-1)+1/(2*r-1)),d=u*t.sqrt(m+p)/p-(1/(2*r-1)-1/(2*o-1))*(m+5/6-2/(3*p)),u=o/(o+r*t.exp(2*d))):(s=t.log(o/(o+r)),a=t.log(r/(o+r)),u=n<(l=t.exp(o*s)/o)/(d=l+(c=t.exp(r*a)/r))?t.pow(o*d*n,1/o):1-t.pow(r*d*(1-n),1/r)),f=-e.gammaln(o)-e.gammaln(r)+e.gammaln(o+r);y<10;y++){if(0===u||1===u)return u;if((u-=l=(c=(e.ibeta(u,o,r)-n)/(l=t.exp(g*t.log(u)+h*t.log(1-u)+f)))/(1-.5*t.min(1,c*(g/u-h/(1-u)))))<=0&&(u=.5*(u+l)),u>=1&&(u=.5*(u+l+1)),t.abs(l)<1e-8*u&&y>0)break}return u},e.ibeta=function(n,o,r){var s=0===n||1===n?0:t.exp(e.gammaln(o+r)-e.gammaln(o)-e.gammaln(r)+o*t.log(n)+r*t.log(1-n));return!(n<0||n>1)&&(n<(o+1)/(o+r+2)?s*e.betacf(n,o,r)/o:1-s*e.betacf(1-n,r,o)/r)},e.randn=function(n,o){var r,s,a,i,l;if(o||(o=n),n)return e.create(n,o,function(){return e.randn()});do{r=e._random_fn(),s=1.7156*(e._random_fn()-.5),l=(a=r-.449871)*a+(i=t.abs(s)+.386595)*(.196*i-.25472*a)}while(l>.27597&&(l>.27846||s*s>-4*t.log(r)*r*r));return s/r},e.randg=function(n,o,r){var s,a,i,l,c,u,m=n;if(r||(r=o),n||(n=1),o)return(u=e.zeros(o,r)).alter(function(){return e.randg(n)}),u;n<1&&(n+=1),s=n-1/3,a=1/t.sqrt(9*s);do{do{l=1+a*(c=e.randn())}while(l<=0);l*=l*l,i=e._random_fn()}while(i>1-.331*t.pow(c,4)&&t.log(i)>.5*c*c+s*(1-l+t.log(l)));if(n==m)return s*l;do{i=e._random_fn()}while(0===i);return t.pow(i,1/m)*s*l},function(t){for(var n=0;n<t.length;n++)(function(t){e.fn[t]=function(){return e(e.map(this,function(n){return e[t](n)}))}})(t[n])}("gammaln gammafn factorial factorialln".split(" ")),function(t){for(var n=0;n<t.length;n++)(function(t){e.fn[t]=function(){return e(e[t].apply(null,arguments))}})(t[n])}("randn".split(" "))}(t,Math),function(e,t){function n(e,n,o,r){for(var s,a=0,i=1,l=1,c=1,u=0,m=0;t.abs((l-m)/l)>r;)m=l,i=c+(s=-(n+u)*(n+o+u)*e/(n+2*u)/(n+2*u+1))*i,l=(a=l+s*a)+(s=(u+=1)*(o-u)*e/(n+2*u-1)/(n+2*u))*l,a/=c=i+s*c,i/=c,l/=c,c=1;return l/n}function o(n,o,r){var s=[.9815606342467192,.9041172563704749,.7699026741943047,.5873179542866175,.3678314989981802,.1252334085114689],a=[.04717533638651183,.10693932599531843,.16007832854334622,.20316742672306592,.2334925365383548,.24914704581340277],i=.5*n;if(i>=8)return 1;var l,c=2*e.normal.cdf(i,0,1,1,0)-1;c=c>=t.exp(-50/r)?t.pow(c,r):0;for(var u=i,m=(8-i)/(l=n>3?2:3),p=u+m,d=0,f=r-1,g=1;g<=l;g++){for(var h=0,y=.5*(p+u),E=.5*(p-u),w=1;w<=12;w++){var v,_=y+E*(6<w?s[(v=12-w+1)-1]:-s[(v=w)-1]),C=_*_;if(C>60)break;var b=2*e.normal.cdf(_,0,1,1,0)*.5-2*e.normal.cdf(_,n,1,1,0)*.5;b>=t.exp(-30/f)&&(h+=b=a[v-1]*t.exp(-.5*C)*t.pow(b,f))}d+=h*=2*E*r/t.sqrt(2*t.PI),u=p,p+=m}return(c+=d)<=t.exp(-30/o)?0:(c=t.pow(c,o))>=1?1:c}!function(t){for(var n=0;n<t.length;n++)(function(t){e[t]=function e(t,n,o){return this instanceof e?(this._a=t,this._b=n,this._c=o,this):new e(t,n,o)},e.fn[t]=function(n,o,r){var s=e[t](n,o,r);return s.data=this,s},e[t].prototype.sample=function(n){var o=this._a,r=this._b,s=this._c;return n?e.alter(n,function(){return e[t].sample(o,r,s)}):e[t].sample(o,r,s)},function(n){for(var o=0;o<n.length;o++)(function(n){e[t].prototype[n]=function(o){var r=this._a,s=this._b,a=this._c;return o||0===o||(o=this.data),"number"!=typeof o?e.fn.map.call(o,function(o){return e[t][n](o,r,s,a)}):e[t][n](o,r,s,a)}})(n[o])}("pdf cdf inv".split(" ")),function(n){for(var o=0;o<n.length;o++)(function(n){e[t].prototype[n]=function(){return e[t][n](this._a,this._b,this._c)}})(n[o])}("mean median mode variance".split(" "))})(t[n])}("beta centralF cauchy chisquare exponential gamma invgamma kumaraswamy laplace lognormal noncentralt normal pareto studentt weibull uniform binomial negbin hypgeom poisson triangular tukey arcsine".split(" ")),e.extend(e.beta,{pdf:function(n,o,r){return n>1||n<0?0:1==o&&1==r?1:o<512&&r<512?t.pow(n,o-1)*t.pow(1-n,r-1)/e.betafn(o,r):t.exp((o-1)*t.log(n)+(r-1)*t.log(1-n)-e.betaln(o,r))},cdf:function(t,n,o){return t>1||t<0?1*(t>1):e.ibeta(t,n,o)},inv:function(t,n,o){return e.ibetainv(t,n,o)},mean:function(e,t){return e/(e+t)},median:function(t,n){return e.ibetainv(.5,t,n)},mode:function(e,t){return(e-1)/(e+t-2)},sample:function(t,n){var o=e.randg(t);return o/(o+e.randg(n))},variance:function(e,n){return e*n/(t.pow(e+n,2)*(e+n+1))}}),e.extend(e.centralF,{pdf:function(n,o,r){var s;return n<0?0:o<=2?0===n&&o<2?1/0:0===n&&2===o?1:1/e.betafn(o/2,r/2)*t.pow(o/r,o/2)*t.pow(n,o/2-1)*t.pow(1+o/r*n,-(o+r)/2):(s=o*n/(r+n*o),o*(r/(r+n*o))/2*e.binomial.pdf((o-2)/2,(o+r-2)/2,s))},cdf:function(t,n,o){return t<0?0:e.ibeta(n*t/(n*t+o),n/2,o/2)},inv:function(t,n,o){return o/(n*(1/e.ibetainv(t,n/2,o/2)-1))},mean:function(e,t){return t>2?t/(t-2):void 0},mode:function(e,t){return e>2?t*(e-2)/(e*(t+2)):void 0},sample:function(t,n){return 2*e.randg(t/2)/t/(2*e.randg(n/2)/n)},variance:function(e,t){if(!(t<=4))return 2*t*t*(e+t-2)/(e*(t-2)*(t-2)*(t-4))}}),e.extend(e.cauchy,{pdf:function(e,n,o){return o<0?0:o/(t.pow(e-n,2)+t.pow(o,2))/t.PI},cdf:function(e,n,o){return t.atan((e-n)/o)/t.PI+.5},inv:function(e,n,o){return n+o*t.tan(t.PI*(e-.5))},median:function(e){return e},mode:function(e){return e},sample:function(n,o){return e.randn()*t.sqrt(1/(2*e.randg(.5)))*o+n}}),e.extend(e.chisquare,{pdf:function(n,o){return n<0?0:0===n&&2===o?.5:t.exp((o/2-1)*t.log(n)-n/2-o/2*t.log(2)-e.gammaln(o/2))},cdf:function(t,n){return t<0?0:e.lowRegGamma(n/2,t/2)},inv:function(t,n){return 2*e.gammapinv(t,.5*n)},mean:function(e){return e},median:function(e){return e*t.pow(1-2/(9*e),3)},mode:function(e){return e-2>0?e-2:0},sample:function(t){return 2*e.randg(t/2)},variance:function(e){return 2*e}}),e.extend(e.exponential,{pdf:function(e,n){return e<0?0:n*t.exp(-n*e)},cdf:function(e,n){return e<0?0:1-t.exp(-n*e)},inv:function(e,n){return-t.log(1-e)/n},mean:function(e){return 1/e},median:function(e){return 1/e*t.log(2)},mode:function(){return 0},sample:function(n){return-1/n*t.log(e._random_fn())},variance:function(e){return t.pow(e,-2)}}),e.extend(e.gamma,{pdf:function(n,o,r){return n<0?0:0===n&&1===o?1/r:t.exp((o-1)*t.log(n)-n/r-e.gammaln(o)-o*t.log(r))},cdf:function(t,n,o){return t<0?0:e.lowRegGamma(n,t/o)},inv:function(t,n,o){return e.gammapinv(t,n)*o},mean:function(e,t){return e*t},mode:function(e,t){if(e>1)return(e-1)*t},sample:function(t,n){return e.randg(t)*n},variance:function(e,t){return e*t*t}}),e.extend(e.invgamma,{pdf:function(n,o,r){return n<=0?0:t.exp(-(o+1)*t.log(n)-r/n-e.gammaln(o)+o*t.log(r))},cdf:function(t,n,o){return t<=0?0:1-e.lowRegGamma(n,o/t)},inv:function(t,n,o){return o/e.gammapinv(1-t,n)},mean:function(e,t){return e>1?t/(e-1):void 0},mode:function(e,t){return t/(e+1)},sample:function(t,n){return n/e.randg(t)},variance:function(e,t){if(!(e<=2))return t*t/((e-1)*(e-1)*(e-2))}}),e.extend(e.kumaraswamy,{pdf:function(e,n,o){return 0===e&&1===n?o:1===e&&1===o?n:t.exp(t.log(n)+t.log(o)+(n-1)*t.log(e)+(o-1)*t.log(1-t.pow(e,n)))},cdf:function(e,n,o){return e<0?0:e>1?1:1-t.pow(1-t.pow(e,n),o)},inv:function(e,n,o){return t.pow(1-t.pow(1-e,1/o),1/n)},mean:function(t,n){return n*e.gammafn(1+1/t)*e.gammafn(n)/e.gammafn(1+1/t+n)},median:function(e,n){return t.pow(1-t.pow(2,-1/n),1/e)},mode:function(e,n){if(e>=1&&n>=1&&1!==e&&1!==n)return t.pow((e-1)/(e*n-1),1/e)},variance:function(){throw new Error("variance not yet implemented")}}),e.extend(e.lognormal,{pdf:function(e,n,o){return e<=0?0:t.exp(-t.log(e)-.5*t.log(2*t.PI)-t.log(o)-t.pow(t.log(e)-n,2)/(2*o*o))},cdf:function(n,o,r){return n<0?0:.5+.5*e.erf((t.log(n)-o)/t.sqrt(2*r*r))},inv:function(n,o,r){return t.exp(-1.4142135623730951*r*e.erfcinv(2*n)+o)},mean:function(e,n){return t.exp(e+n*n/2)},median:function(e){return t.exp(e)},mode:function(e,n){return t.exp(e-n*n)},sample:function(n,o){return t.exp(e.randn()*o+n)},variance:function(e,n){return(t.exp(n*n)-1)*t.exp(2*e+n*n)}}),e.extend(e.noncentralt,{pdf:function(n,o,r){return t.abs(r)<1e-14?e.studentt.pdf(n,o):t.abs(n)<1e-14?t.exp(e.gammaln((o+1)/2)-r*r/2-.5*t.log(t.PI*o)-e.gammaln(o/2)):o/n*(e.noncentralt.cdf(n*t.sqrt(1+2/o),o+2,r)-e.noncentralt.cdf(n,o,r))},cdf:function(n,o,r){var s=1e-14;if(t.abs(r)<s)return e.studentt.cdf(n,o);var a=!1;n<0&&(a=!0,r=-r);for(var i=e.normal.cdf(-r,0,1),l=s+1,c=l,u=n*n/(n*n+o),m=0,p=t.exp(-r*r/2),d=t.exp(-r*r/2-.5*t.log(2)-e.gammaln(1.5))*r;m<200||c>s||l>s;)c=l,m>0&&(p*=r*r/(2*m),d*=r*r/(2*(m+.5))),i+=.5*(l=p*e.beta.cdf(u,m+.5,o/2)+d*e.beta.cdf(u,m+1,o/2)),m++;return a?1-i:i}}),e.extend(e.normal,{pdf:function(e,n,o){return t.exp(-.5*t.log(2*t.PI)-t.log(o)-t.pow(e-n,2)/(2*o*o))},cdf:function(n,o,r){return.5*(1+e.erf((n-o)/t.sqrt(2*r*r)))},inv:function(t,n,o){return-1.4142135623730951*o*e.erfcinv(2*t)+n},mean:function(e){return e},median:function(e){return e},mode:function(e){return e},sample:function(t,n){return e.randn()*n+t},variance:function(e,t){return t*t}}),e.extend(e.pareto,{pdf:function(e,n,o){return e<n?0:o*t.pow(n,o)/t.pow(e,o+1)},cdf:function(e,n,o){return e<n?0:1-t.pow(n/e,o)},inv:function(e,n,o){return n/t.pow(1-e,1/o)},mean:function(e,n){if(!(n<=1))return n*t.pow(e,n)/(n-1)},median:function(e,n){return e*(n*t.SQRT2)},mode:function(e){return e},variance:function(e,n){if(!(n<=2))return e*e*n/(t.pow(n-1,2)*(n-2))}}),e.extend(e.studentt,{pdf:function(n,o){return o=o>1e100?1e100:o,1/(t.sqrt(o)*e.betafn(.5,o/2))*t.pow(1+n*n/o,-(o+1)/2)},cdf:function(n,o){var r=o/2;return e.ibeta((n+t.sqrt(n*n+o))/(2*t.sqrt(n*n+o)),r,r)},inv:function(n,o){var r=e.ibetainv(2*t.min(n,1-n),.5*o,.5);return r=t.sqrt(o*(1-r)/r),n>.5?r:-r},mean:function(e){return e>1?0:void 0},median:function(){return 0},mode:function(){return 0},sample:function(n){return e.randn()*t.sqrt(n/(2*e.randg(n/2)))},variance:function(e){return e>2?e/(e-2):e>1?1/0:void 0}}),e.extend(e.weibull,{pdf:function(e,n,o){return e<0||n<0||o<0?0:o/n*t.pow(e/n,o-1)*t.exp(-t.pow(e/n,o))},cdf:function(e,n,o){return e<0?0:1-t.exp(-t.pow(e/n,o))},inv:function(e,n,o){return n*t.pow(-t.log(1-e),1/o)},mean:function(t,n){return t*e.gammafn(1+1/n)},median:function(e,n){return e*t.pow(t.log(2),1/n)},mode:function(e,n){return n<=1?0:e*t.pow((n-1)/n,1/n)},sample:function(n,o){return n*t.pow(-t.log(e._random_fn()),1/o)},variance:function(n,o){return n*n*e.gammafn(1+2/o)-t.pow(e.weibull.mean(n,o),2)}}),e.extend(e.uniform,{pdf:function(e,t,n){return e<t||e>n?0:1/(n-t)},cdf:function(e,t,n){return e<t?0:e<n?(e-t)/(n-t):1},inv:function(e,t,n){return t+e*(n-t)},mean:function(e,t){return.5*(e+t)},median:function(t,n){return e.mean(t,n)},mode:function(){throw new Error("mode is not yet implemented")},sample:function(t,n){return t/2+n/2+(n/2-t/2)*(2*e._random_fn()-1)},variance:function(e,n){return t.pow(n-e,2)/12}}),e.extend(e.binomial,{pdf:function(n,o,r){return 0===r||1===r?o*r===n?1:0:e.combination(o,n)*t.pow(r,n)*t.pow(1-r,o-n)},cdf:function(o,r,s){var a,i=1e-10;if(o<0)return 0;if(o>=r)return 1;if(s<0||s>1||r<=0)return NaN;var l=s,c=(o=t.floor(o))+1,u=r-o,m=c+u,p=t.exp(e.gammaln(m)-e.gammaln(u)-e.gammaln(c)+c*t.log(l)+u*t.log(1-l));return a=l<(c+1)/(m+2)?p*n(l,c,u,i):1-p*n(1-l,u,c,i),t.round(1/i*(1-a))/(1/i)}}),e.extend(e.negbin,{pdf:function(n,o,r){return n===n>>>0&&(n<0?0:e.combination(n+o-1,o-1)*t.pow(1-r,n)*t.pow(r,o))},cdf:function(t,n,o){var r=0,s=0;if(t<0)return 0;for(;s<=t;s++)r+=e.negbin.pdf(s,n,o);return r}}),e.extend(e.hypgeom,{pdf:function(n,o,r,s){if(n!=n|0)return!1;if(n<0||n<r-(o-s))return 0;if(n>s||n>r)return 0;if(2*r>o)return 2*s>o?e.hypgeom.pdf(o-r-s+n,o,o-r,o-s):e.hypgeom.pdf(s-n,o,o-r,s);if(2*s>o)return e.hypgeom.pdf(r-n,o,r,o-s);if(r<s)return e.hypgeom.pdf(n,o,s,r);for(var a=1,i=0,l=0;l<n;l++){for(;a>1&&i<s;)a*=1-r/(o-i),i++;a*=(s-l)*(r-l)/((l+1)*(o-r-s+l+1))}for(;i<s;i++)a*=1-r/(o-i);return t.min(1,t.max(0,a))},cdf:function(n,o,r,s){if(n<0||n<r-(o-s))return 0;if(n>=s||n>=r)return 1;if(2*r>o)return 2*s>o?e.hypgeom.cdf(o-r-s+n,o,o-r,o-s):1-e.hypgeom.cdf(s-n-1,o,o-r,s);if(2*s>o)return 1-e.hypgeom.cdf(r-n-1,o,r,o-s);if(r<s)return e.hypgeom.cdf(n,o,s,r);for(var a=1,i=1,l=0,c=0;c<n;c++){for(;a>1&&l<s;){var u=1-r/(o-l);i*=u,a*=u,l++}a+=i*=(s-c)*(r-c)/((c+1)*(o-r-s+c+1))}for(;l<s;l++)a*=1-r/(o-l);return t.min(1,t.max(0,a))}}),e.extend(e.poisson,{pdf:function(n,o){return o<0||n%1!=0||n<0?0:t.pow(o,n)*t.exp(-o)/e.factorial(n)},cdf:function(t,n){var o=[],r=0;if(t<0)return 0;for(;r<=t;r++)o.push(e.poisson.pdf(r,n));return e.sum(o)},mean:function(e){return e},variance:function(e){return e},sampleSmall:function(n){var o=1,r=0,s=t.exp(-n);do{r++,o*=e._random_fn()}while(o>s);return r-1},sampleLarge:function(n){var o,r,s,a,i,l,c,u,m,p,d=n;for(a=t.sqrt(d),i=t.log(d),l=.02483*(c=.931+2.53*a)-.059,u=1.1239+1.1328/(c-3.4),m=.9277-3.6224/(c-2);;){if(r=t.random()-.5,s=t.random(),p=.5-t.abs(r),o=t.floor((2*l/p+c)*r+d+.43),p>=.07&&s<=m)return o;if(!(o<0||p<.013&&s>p)&&t.log(s)+t.log(u)-t.log(l/(p*p)+c)<=o*i-d-e.loggam(o+1))return o}},sample:function(e){return e<10?this.sampleSmall(e):this.sampleLarge(e)}}),e.extend(e.triangular,{pdf:function(e,t,n,o){return n<=t||o<t||o>n?NaN:e<t||e>n?0:e<o?2*(e-t)/((n-t)*(o-t)):e===o?2/(n-t):2*(n-e)/((n-t)*(n-o))},cdf:function(e,n,o,r){return o<=n||r<n||r>o?NaN:e<=n?0:e>=o?1:e<=r?t.pow(e-n,2)/((o-n)*(r-n)):1-t.pow(o-e,2)/((o-n)*(o-r))},inv:function(e,n,o,r){return o<=n||r<n||r>o?NaN:e<=(r-n)/(o-n)?n+(o-n)*t.sqrt(e*((r-n)/(o-n))):n+(o-n)*(1-t.sqrt((1-e)*(1-(r-n)/(o-n))))},mean:function(e,t,n){return(e+t+n)/3},median:function(e,n,o){return o<=(e+n)/2?n-t.sqrt((n-e)*(n-o))/t.sqrt(2):o>(e+n)/2?e+t.sqrt((n-e)*(o-e))/t.sqrt(2):void 0},mode:function(e,t,n){return n},sample:function(n,o,r){var s=e._random_fn();return s<(r-n)/(o-n)?n+t.sqrt(s*(o-n)*(r-n)):o-t.sqrt((1-s)*(o-n)*(o-r))},variance:function(e,t,n){return(e*e+t*t+n*n-e*t-e*n-t*n)/18}}),e.extend(e.arcsine,{pdf:function(e,n,o){return o<=n?NaN:e<=n||e>=o?0:2/t.PI*t.pow(t.pow(o-n,2)-t.pow(2*e-n-o,2),-.5)},cdf:function(e,n,o){return e<n?0:e<o?2/t.PI*t.asin(t.sqrt((e-n)/(o-n))):1},inv:function(e,n,o){return n+(.5-.5*t.cos(t.PI*e))*(o-n)},mean:function(e,t){return t<=e?NaN:(e+t)/2},median:function(e,t){return t<=e?NaN:(e+t)/2},mode:function(){throw new Error("mode is not yet implemented")},sample:function(n,o){return(n+o)/2+(o-n)/2*t.sin(2*t.PI*e.uniform.sample(0,1))},variance:function(e,n){return n<=e?NaN:t.pow(n-e,2)/8}}),e.extend(e.laplace,{pdf:function(e,n,o){return o<=0?0:t.exp(-t.abs(e-n)/o)/(2*o)},cdf:function(e,n,o){return o<=0?0:e<n?.5*t.exp((e-n)/o):1-.5*t.exp(-(e-n)/o)},mean:function(e){return e},median:function(e){return e},mode:function(e){return e},variance:function(e,t){return 2*t*t},sample:function(n,o){var r,s=e._random_fn()-.5;return n-o*((r=s)/t.abs(r))*t.log(1-2*t.abs(s))}}),e.extend(e.tukey,{cdf:function(n,r,s){var a=r,i=[.9894009349916499,.9445750230732326,.8656312023878318,.755404408355003,.6178762444026438,.45801677765722737,.2816035507792589,.09501250983763744],l=[.027152459411754096,.062253523938647894,.09515851168249279,.12462897125553388,.14959598881657674,.16915651939500254,.18260341504492358,.1894506104550685];if(n<=0)return 0;if(s<2||a<2)return NaN;if(!Number.isFinite(n))return 1;if(s>25e3)return o(n,1,a);var c,u=.5*s,m=u*t.log(s)-s*t.log(2)-e.gammaln(u),p=u-1,d=.25*s;c=s<=100?1:s<=800?.5:s<=5e3?.25:.125,m+=t.log(c);for(var f=0,g=1;g<=50;g++){for(var h=0,y=(2*g-1)*c,E=1;E<=16;E++){var w,v;8<E?(w=E-8-1,v=m+p*t.log(y+i[w]*c)-(i[w]*c+y)*d):(w=E-1,v=m+p*t.log(y-i[w]*c)+(i[w]*c-y)*d),v>=-30&&(h+=o(8<E?n*t.sqrt(.5*(i[w]*c+y)):n*t.sqrt(.5*(-i[w]*c+y)),1,a)*l[w]*t.exp(v))}if(g*c>=1&&h<=1e-14)break;f+=h}if(h>1e-14)throw new Error("tukey.cdf failed to converge");return f>1&&(f=1),f},inv:function(n,o,r){if(r<2||o<2)return NaN;if(n<0||n>1)return NaN;if(0===n)return 0;if(1===n)return 1/0;var s,a=function(e,n,o){var r=.5-.5*e,s=t.sqrt(t.log(1/(r*r))),a=s+((((-453642210148e-16*s-.204231210125)*s-.342242088547)*s-1)*s+.322232421088)/((((.0038560700634*s+.10353775285)*s+.531103462366)*s+.588581570495)*s+.099348462606);o<120&&(a+=(a*a*a+a)/o/4);var i=.8832-.2368*a;return o<120&&(i+=-1.214/o+1.208*a/o),a*(i*t.log(n-1)+1.4142)}(n,o,r),i=e.tukey.cdf(a,o,r)-n;s=i>0?t.max(0,a-1):a+1;for(var l,c=e.tukey.cdf(s,o,r)-n,u=1;u<50;u++)if(l=s-c*(s-a)/(c-i),i=c,a=s,l<0&&(l=0,c=-n),c=e.tukey.cdf(l,o,r)-n,s=l,t.abs(s-a)<1e-4)return l;throw new Error("tukey.inv failed to converge")}})}(t,Math),function(e,t){var n,o,r=Array.prototype.push,s=e.utils.isArray;function a(t){return s(t)||t instanceof e}e.extend({add:function(t,n){return a(n)?(a(n[0])||(n=[n]),e.map(t,function(e,t,o){return e+n[t][o]})):e.map(t,function(e){return e+n})},subtract:function(t,n){return a(n)?(a(n[0])||(n=[n]),e.map(t,function(e,t,o){return e-n[t][o]||0})):e.map(t,function(e){return e-n})},divide:function(t,n){return a(n)?(a(n[0])||(n=[n]),e.multiply(t,e.inv(n))):e.map(t,function(e){return e/n})},multiply:function(t,n){var o,r,s,i,l,c,u,m;if(void 0===t.length&&void 0===n.length)return t*n;if(l=t.length,c=t[0].length,u=e.zeros(l,s=a(n)?n[0].length:c),m=0,a(n)){for(;m<s;m++)for(o=0;o<l;o++){for(i=0,r=0;r<c;r++)i+=t[o][r]*n[r][m];u[o][m]=i}return 1===l&&1===m?u[0][0]:u}return e.map(t,function(e){return e*n})},outer:function(t,n){return e.multiply(t.map(function(e){return[e]}),[n])},dot:function(t,n){a(t[0])||(t=[t]),a(n[0])||(n=[n]);for(var o,r,s=1===t[0].length&&1!==t.length?e.transpose(t):t,i=1===n[0].length&&1!==n.length?e.transpose(n):n,l=[],c=0,u=s.length,m=s[0].length;c<u;c++){for(l[c]=[],o=0,r=0;r<m;r++)o+=s[c][r]*i[c][r];l[c]=o}return 1===l.length?l[0]:l},pow:function(n,o){return e.map(n,function(e){return t.pow(e,o)})},exp:function(n){return e.map(n,function(e){return t.exp(e)})},log:function(n){return e.map(n,function(e){return t.log(e)})},abs:function(n){return e.map(n,function(e){return t.abs(e)})},norm:function(e,n){var o=0,r=0;for(isNaN(n)&&(n=2),a(e[0])&&(e=e[0]);r<e.length;r++)o+=t.pow(t.abs(e[r]),n);return t.pow(o,1/n)},angle:function(n,o){return t.acos(e.dot(n,o)/(e.norm(n)*e.norm(o)))},aug:function(e,t){var n,o=[];for(n=0;n<e.length;n++)o.push(e[n].slice());for(n=0;n<o.length;n++)r.apply(o[n],t[n]);return o},inv:function(t){for(var n,o=t.length,r=t[0].length,s=e.identity(o,r),a=e.gauss_jordan(t,s),i=[],l=0;l<o;l++)for(i[l]=[],n=r;n<a[0].length;n++)i[l][n-r]=a[l][n];return i},det:function e(t){if(2===t.length)return t[0][0]*t[1][1]-t[0][1]*t[1][0];for(var n=0,o=0;o<t.length;o++){for(var r=[],s=1;s<t.length;s++){r[s-1]=[];for(var a=0;a<t.length;a++)a<o?r[s-1][a]=t[s][a]:a>o&&(r[s-1][a-1]=t[s][a])}var i=o%2?-1:1;n+=e(r)*t[0][o]*i}return n},gauss_elimination:function(n,o){var r,s,a,i,l=0,c=0,u=n.length,m=n[0].length,p=1,d=0,f=[];for(r=(n=e.aug(n,o))[0].length,l=0;l<u;l++){for(s=n[l][l],c=l,i=l+1;i<m;i++)s<t.abs(n[i][l])&&(s=n[i][l],c=i);if(c!=l)for(i=0;i<r;i++)a=n[l][i],n[l][i]=n[c][i],n[c][i]=a;for(c=l+1;c<u;c++)for(p=n[c][l]/n[l][l],i=l;i<r;i++)n[c][i]=n[c][i]-p*n[l][i]}for(l=u-1;l>=0;l--){for(d=0,c=l+1;c<=u-1;c++)d+=f[c]*n[l][c];f[l]=(n[l][r-1]-d)/n[l][l]}return f},gauss_jordan:function(n,o){var r,s,a,i=e.aug(n,o),l=i.length,c=i[0].length,u=0;for(s=0;s<l;s++){var m=s;for(a=s+1;a<l;a++)t.abs(i[a][s])>t.abs(i[m][s])&&(m=a);var p=i[s];for(i[s]=i[m],i[m]=p,a=s+1;a<l;a++)for(u=i[a][s]/i[s][s],r=s;r<c;r++)i[a][r]-=i[s][r]*u}for(s=l-1;s>=0;s--){for(u=i[s][s],a=0;a<s;a++)for(r=c-1;r>s-1;r--)i[a][r]-=i[s][r]*i[a][s]/u;for(i[s][s]/=u,r=l;r<c;r++)i[s][r]/=u}return i},triaUpSolve:function(t,n){var o,r=t[0].length,s=e.zeros(1,r)[0],a=!1;return null!=n[0].length&&(n=n.map(function(e){return e[0]}),a=!0),e.arange(r-1,-1,-1).forEach(function(a){o=e.arange(a+1,r).map(function(e){return s[e]*t[a][e]}),s[a]=(n[a]-e.sum(o))/t[a][a]}),a?s.map(function(e){return[e]}):s},triaLowSolve:function(t,n){var o,r=t[0].length,s=e.zeros(1,r)[0],a=!1;return null!=n[0].length&&(n=n.map(function(e){return e[0]}),a=!0),e.arange(r).forEach(function(r){o=e.arange(r).map(function(e){return t[r][e]*s[e]}),s[r]=(n[r]-e.sum(o))/t[r][r]}),a?s.map(function(e){return[e]}):s},lu:function(t){var n,o=t.length,r=e.identity(o),s=e.zeros(t.length,t[0].length);return e.arange(o).forEach(function(e){s[0][e]=t[0][e]}),e.arange(1,o).forEach(function(a){e.arange(a).forEach(function(o){n=e.arange(o).map(function(e){return r[a][e]*s[e][o]}),r[a][o]=(t[a][o]-e.sum(n))/s[o][o]}),e.arange(a,o).forEach(function(o){n=e.arange(a).map(function(e){return r[a][e]*s[e][o]}),s[a][o]=t[n.length][o]-e.sum(n)})}),[r,s]},cholesky:function(n){var o,r=n.length,s=e.zeros(n.length,n[0].length);return e.arange(r).forEach(function(a){o=e.arange(a).map(function(e){return t.pow(s[a][e],2)}),s[a][a]=t.sqrt(n[a][a]-e.sum(o)),e.arange(a+1,r).forEach(function(t){o=e.arange(a).map(function(e){return s[a][e]*s[t][e]}),s[t][a]=(n[a][t]-e.sum(o))/s[a][a]})}),s},gauss_jacobi:function(n,o,r,s){for(var a,i,l,c,u=0,m=0,p=n.length,d=[],f=[],g=[];u<p;u++)for(d[u]=[],f[u]=[],g[u]=[],m=0;m<p;m++)u>m?(d[u][m]=n[u][m],f[u][m]=g[u][m]=0):u<m?(f[u][m]=n[u][m],d[u][m]=g[u][m]=0):(g[u][m]=n[u][m],d[u][m]=f[u][m]=0);for(l=e.multiply(e.multiply(e.inv(g),e.add(d,f)),-1),i=e.multiply(e.inv(g),o),a=r,c=e.add(e.multiply(l,r),i),u=2;t.abs(e.norm(e.subtract(c,a)))>s;)a=c,c=e.add(e.multiply(l,a),i),u++;return c},gauss_seidel:function(n,o,r,s){for(var a,i,l,c,u,m=0,p=n.length,d=[],f=[],g=[];m<p;m++)for(d[m]=[],f[m]=[],g[m]=[],a=0;a<p;a++)m>a?(d[m][a]=n[m][a],f[m][a]=g[m][a]=0):m<a?(f[m][a]=n[m][a],d[m][a]=g[m][a]=0):(g[m][a]=n[m][a],d[m][a]=f[m][a]=0);for(c=e.multiply(e.multiply(e.inv(e.add(g,d)),f),-1),l=e.multiply(e.inv(e.add(g,d)),o),i=r,u=e.add(e.multiply(c,r),l),m=2;t.abs(e.norm(e.subtract(u,i)))>s;)i=u,u=e.add(e.multiply(c,i),l),m+=1;return u},SOR:function(n,o,r,s,a){for(var i,l,c,u,m,p=0,d=n.length,f=[],g=[],h=[];p<d;p++)for(f[p]=[],g[p]=[],h[p]=[],i=0;i<d;i++)p>i?(f[p][i]=n[p][i],g[p][i]=h[p][i]=0):p<i?(g[p][i]=n[p][i],f[p][i]=h[p][i]=0):(h[p][i]=n[p][i],f[p][i]=g[p][i]=0);for(u=e.multiply(e.inv(e.add(h,e.multiply(f,a))),e.subtract(e.multiply(h,1-a),e.multiply(g,a))),c=e.multiply(e.multiply(e.inv(e.add(h,e.multiply(f,a))),o),a),l=r,m=e.add(e.multiply(u,r),c),p=2;t.abs(e.norm(e.subtract(m,l)))>s;)l=m,m=e.add(e.multiply(u,l),c),p++;return m},householder:function(n){for(var o,r,s,a,i=n.length,l=n[0].length,c=0,u=[],m=[];c<i-1;c++){for(o=0,a=c+1;a<l;a++)o+=n[a][c]*n[a][c];for(o=(n[c+1][c]>0?-1:1)*t.sqrt(o),r=t.sqrt((o*o-n[c+1][c]*o)/2),(u=e.zeros(i,1))[c+1][0]=(n[c+1][c]-o)/(2*r),s=c+2;s<i;s++)u[s][0]=n[s][c]/(2*r);m=e.subtract(e.identity(i,l),e.multiply(e.multiply(u,e.transpose(u)),2)),n=e.multiply(m,e.multiply(n,m))}return n},QR:(n=e.sum,o=e.arange,function(r){var s,a,i,l=r.length,c=r[0].length,u=e.zeros(c,c);for(r=e.copy(r),a=0;a<c;a++){for(u[a][a]=t.sqrt(n(o(l).map(function(e){return r[e][a]*r[e][a]}))),s=0;s<l;s++)r[s][a]=r[s][a]/u[a][a];for(i=a+1;i<c;i++)for(u[a][i]=n(o(l).map(function(e){return r[e][a]*r[e][i]})),s=0;s<l;s++)r[s][i]=r[s][i]-r[s][a]*u[a][i]}return[r,u]}),lstsq:function(t,n){var o=!1;void 0===n[0].length&&(n=n.map(function(e){return[e]}),o=!0);var r=e.QR(t),s=r[0],a=r[1],i=t[0].length,l=e.slice(s,{col:{end:i}}),c=function(t){var n=(t=e.copy(t)).length,o=e.identity(n);return e.arange(n-1,-1,-1).forEach(function(n){e.sliceAssign(o,{row:n},e.divide(e.slice(o,{row:n}),t[n][n])),e.sliceAssign(t,{row:n},e.divide(e.slice(t,{row:n}),t[n][n])),e.arange(n).forEach(function(r){var s=e.multiply(t[r][n],-1),a=e.slice(t,{row:r}),i=e.multiply(e.slice(t,{row:n}),s);e.sliceAssign(t,{row:r},e.add(a,i));var l=e.slice(o,{row:r}),c=e.multiply(e.slice(o,{row:n}),s);e.sliceAssign(o,{row:r},e.add(l,c))})}),o}(e.slice(a,{row:{end:i}})),u=e.transpose(l);void 0===u[0].length&&(u=[u]);var m=e.multiply(e.multiply(c,u),n);return void 0===m.length&&(m=[[m]]),o?m.map(function(e){return e[0]}):m},jacobi:function(n){for(var o,r,s,a,i,l,c,u=1,m=n.length,p=e.identity(m,m),d=[];1===u;){for(i=n[0][1],s=0,a=1,o=0;o<m;o++)for(r=0;r<m;r++)o!=r&&i<t.abs(n[o][r])&&(i=t.abs(n[o][r]),s=o,a=r);for(l=n[s][s]===n[a][a]?n[s][a]>0?t.PI/4:-t.PI/4:t.atan(2*n[s][a]/(n[s][s]-n[a][a]))/2,(c=e.identity(m,m))[s][s]=t.cos(l),c[s][a]=-t.sin(l),c[a][s]=t.sin(l),c[a][a]=t.cos(l),p=e.multiply(p,c),n=e.multiply(e.multiply(e.inv(c),n),c),u=0,o=1;o<m;o++)for(r=1;r<m;r++)o!=r&&t.abs(n[o][r])>.001&&(u=1)}for(o=0;o<m;o++)d.push(n[o][o]);return[p,d]},rungekutta:function(e,t,n,o,r,s){var a,i,l;if(2===s)for(;o<=n;)r+=((a=t*e(o,r))+(i=t*e(o+t,r+a)))/2,o+=t;if(4===s)for(;o<=n;)r+=((a=t*e(o,r))+2*(i=t*e(o+t/2,r+a/2))+2*(l=t*e(o+t/2,r+i/2))+t*e(o+t,r+l))/6,o+=t;return r},romberg:function(e,n,o,r){for(var s,a,i,l,c,u=0,m=(o-n)/2,p=[],d=[],f=[];u<r/2;){for(c=e(n),i=n,l=0;i<=o;i+=m,l++)p[l]=i;for(s=p.length,i=1;i<s-1;i++)c+=(i%2!=0?4:2)*e(p[i]);c=m/3*(c+e(o)),f[u]=c,m/=2,u++}for(a=f.length,s=1;1!==a;){for(i=0;i<a-1;i++)d[i]=(t.pow(4,s)*f[i+1]-f[i])/(t.pow(4,s)-1);a=d.length,f=d,d=[],s++}return f},richardson:function(e,n,o,r){function s(e,t){for(var n,o=0,r=e.length;o<r;o++)e[o]===t&&(n=o);return n}for(var a,i,l,c,u,m=t.abs(o-e[s(e,o)+1]),p=0,d=[],f=[];r>=m;)a=s(e,o+r),i=s(e,o),d[p]=(n[a]-2*n[i]+n[2*i-a])/(r*r),r/=2,p++;for(c=d.length,l=1;1!=c;){for(u=0;u<c-1;u++)f[u]=(t.pow(4,l)*d[u+1]-d[u])/(t.pow(4,l)-1);c=f.length,d=f,f=[],l++}return d},simpson:function(e,t,n,o){for(var r,s=(n-t)/o,a=e(t),i=[],l=t,c=0,u=1;l<=n;l+=s,c++)i[c]=l;for(r=i.length;u<r-1;u++)a+=(u%2!=0?4:2)*e(i[u]);return s/3*(a+e(n))},hermite:function(e,t,n,o){for(var r,s=e.length,a=0,i=0,l=[],c=[],u=[],m=[];i<s;i++){for(l[i]=1,r=0;r<s;r++)i!=r&&(l[i]*=(o-e[r])/(e[i]-e[r]));for(c[i]=0,r=0;r<s;r++)i!=r&&(c[i]+=1/(e[i]-e[r]));u[i]=(1-2*(o-e[i])*c[i])*(l[i]*l[i]),m[i]=(o-e[i])*(l[i]*l[i]),a+=u[i]*t[i]+m[i]*n[i]}return a},lagrange:function(e,t,n){for(var o,r,s=0,a=0,i=e.length;a<i;a++){for(r=t[a],o=0;o<i;o++)a!=o&&(r*=(n-e[o])/(e[a]-e[o]));s+=r}return s},cubic_spline:function(t,n,o){for(var r,s,a=t.length,i=0,l=[],c=[],u=[],m=[],p=[],d=[];i<a-1;i++)m[i]=t[i+1]-t[i];for(u[0]=0,i=1;i<a-1;i++)u[i]=3/m[i]*(n[i+1]-n[i])-3/m[i-1]*(n[i]-n[i-1]);for(i=1;i<a-1;i++)l[i]=[],c[i]=[],l[i][i-1]=m[i-1],l[i][i]=2*(m[i-1]+m[i]),l[i][i+1]=m[i],c[i][0]=u[i];for(s=e.multiply(e.inv(l),c),r=0;r<a-1;r++)p[r]=(n[r+1]-n[r])/m[r]-m[r]*(s[r+1][0]+2*s[r][0])/3,d[r]=(s[r+1][0]-s[r][0])/(3*m[r]);for(r=0;r<a&&!(t[r]>o);r++);return n[r-=1]+(o-t[r])*p[r]+e.sq(o-t[r])*s[r]+(o-t[r])*e.sq(o-t[r])*d[r]},gauss_quadrature:function(){throw new Error("gauss_quadrature not yet implemented")},PCA:function(t){var n,o,r,s,a,i=t.length,l=t[0].length,c=0,u=[],m=[],p=[],d=[],f=[],g=[],h=[];for(c=0;c<i;c++)u[c]=e.sum(t[c])/l;for(c=0;c<l;c++)for(f[c]=[],n=0;n<i;n++)f[c][n]=t[n][c]-u[n];for(f=e.transpose(f),c=0;c<i;c++)for(g[c]=[],n=0;n<i;n++)g[c][n]=e.dot([f[c]],[f[n]])/(l-1);for(a=(r=e.jacobi(g))[0],m=r[1],h=e.transpose(a),c=0;c<m.length;c++)for(n=c;n<m.length;n++)m[c]<m[n]&&(o=m[c],m[c]=m[n],m[n]=o,p=h[c],h[c]=h[n],h[n]=p);for(s=e.transpose(f),c=0;c<i;c++)for(d[c]=[],n=0;n<s.length;n++)d[c][n]=e.dot([h[c]],[s[n]]);return[t,m,h,d]}}),function(t){for(var n=0;n<t.length;n++)(function(t){e.fn[t]=function(n,o){var r=this;return o?(setTimeout(function(){o.call(r,e.fn[t].call(r,n))},15),this):"number"==typeof e[t](this,n)?e[t](this,n):e(e[t](this,n))}})(t[n])}("add divide multiply subtract dot pow exp log abs norm angle".split(" "))}(t,Math),function(e,t){var n=[].slice,o=e.utils.isNumber,r=e.utils.isArray;function s(e,n,o,r){if(e>1||o>1||e<=0||o<=0)throw new Error("Proportions should be greater than 0 and less than 1");var s=(e*n+o*r)/(n+r);return(e-o)/t.sqrt(s*(1-s)*(1/n+1/r))}e.extend({zscore:function(){var t=n.call(arguments);return o(t[1])?(t[0]-t[1])/t[2]:(t[0]-e.mean(t[1]))/e.stdev(t[1],t[2])},ztest:function(){var o,s=n.call(arguments);return r(s[1])?(o=e.zscore(s[0],s[1],s[3]),1===s[2]?e.normal.cdf(-t.abs(o),0,1):2*e.normal.cdf(-t.abs(o),0,1)):s.length>2?(o=e.zscore(s[0],s[1],s[2]),1===s[3]?e.normal.cdf(-t.abs(o),0,1):2*e.normal.cdf(-t.abs(o),0,1)):(o=s[0],1===s[1]?e.normal.cdf(-t.abs(o),0,1):2*e.normal.cdf(-t.abs(o),0,1))}}),e.extend(e.fn,{zscore:function(e,t){return(e-this.mean())/this.stdev(t)},ztest:function(n,o,r){var s=t.abs(this.zscore(n,r));return 1===o?e.normal.cdf(-s,0,1):2*e.normal.cdf(-s,0,1)}}),e.extend({tscore:function(){var o=n.call(arguments);return 4===o.length?(o[0]-o[1])/(o[2]/t.sqrt(o[3])):(o[0]-e.mean(o[1]))/(e.stdev(o[1],!0)/t.sqrt(o[1].length))},ttest:function(){var r,s=n.call(arguments);return 5===s.length?(r=t.abs(e.tscore(s[0],s[1],s[2],s[3])),1===s[4]?e.studentt.cdf(-r,s[3]-1):2*e.studentt.cdf(-r,s[3]-1)):o(s[1])?(r=t.abs(s[0]),1==s[2]?e.studentt.cdf(-r,s[1]-1):2*e.studentt.cdf(-r,s[1]-1)):(r=t.abs(e.tscore(s[0],s[1])),1==s[2]?e.studentt.cdf(-r,s[1].length-1):2*e.studentt.cdf(-r,s[1].length-1))}}),e.extend(e.fn,{tscore:function(e){return(e-this.mean())/(this.stdev(!0)/t.sqrt(this.cols()))},ttest:function(n,o){return 1===o?1-e.studentt.cdf(t.abs(this.tscore(n)),this.cols()-1):2*e.studentt.cdf(-t.abs(this.tscore(n)),this.cols()-1)}}),e.extend({anovafscore:function(){var o,r,s,a,i,l,c,u,m=n.call(arguments);if(1===m.length){for(i=new Array(m[0].length),c=0;c<m[0].length;c++)i[c]=m[0][c];m=i}for(r=new Array,c=0;c<m.length;c++)r=r.concat(m[c]);for(s=e.mean(r),o=0,c=0;c<m.length;c++)o+=m[c].length*t.pow(e.mean(m[c])-s,2);for(o/=m.length-1,l=0,c=0;c<m.length;c++)for(a=e.mean(m[c]),u=0;u<m[c].length;u++)l+=t.pow(m[c][u]-a,2);return o/(l/(r.length-m.length))},anovaftest:function(){var t,r,s,a,i=n.call(arguments);if(o(i[0]))return 1-e.centralF.cdf(i[0],i[1],i[2]);var l=e.anovafscore(i);for(t=i.length-1,s=0,a=0;a<i.length;a++)s+=i[a].length;return r=s-t-1,1-e.centralF.cdf(l,t,r)},ftest:function(t,n,o){return 1-e.centralF.cdf(t,n,o)}}),e.extend(e.fn,{anovafscore:function(){return e.anovafscore(this.toArray())},anovaftes:function(){var t,n=0;for(t=0;t<this.length;t++)n+=this[t].length;return e.ftest(this.anovafscore(),this.length-1,n-this.length)}}),e.extend({qscore:function(){var r,s,a,i,l,c=n.call(arguments);return o(c[0])?(r=c[0],s=c[1],a=c[2],i=c[3],l=c[4]):(r=e.mean(c[0]),s=e.mean(c[1]),a=c[0].length,i=c[1].length,l=c[2]),t.abs(r-s)/(l*t.sqrt((1/a+1/i)/2))},qtest:function(){var t,o=n.call(arguments);3===o.length?(t=o[0],o=o.slice(1)):7===o.length?(t=e.qscore(o[0],o[1],o[2],o[3],o[4]),o=o.slice(5)):(t=e.qscore(o[0],o[1],o[2]),o=o.slice(3));var r=o[0],s=o[1];return 1-e.tukey.cdf(t,s,r-s)},tukeyhsd:function(t){for(var n=e.pooledstdev(t),o=t.map(function(t){return e.mean(t)}),r=t.reduce(function(e,t){return e+t.length},0),s=[],a=0;a<t.length;++a)for(var i=a+1;i<t.length;++i){var l=e.qtest(o[a],o[i],t[a].length,t[i].length,n,r,t.length);s.push([[a,i],l])}return s}}),e.extend({normalci:function(){var o,r=n.call(arguments),s=new Array(2);return o=4===r.length?t.abs(e.normal.inv(r[1]/2,0,1)*r[2]/t.sqrt(r[3])):t.abs(e.normal.inv(r[1]/2,0,1)*e.stdev(r[2])/t.sqrt(r[2].length)),s[0]=r[0]-o,s[1]=r[0]+o,s},tci:function(){var o,r=n.call(arguments),s=new Array(2);return o=4===r.length?t.abs(e.studentt.inv(r[1]/2,r[3]-1)*r[2]/t.sqrt(r[3])):t.abs(e.studentt.inv(r[1]/2,r[2].length-1)*e.stdev(r[2],!0)/t.sqrt(r[2].length)),s[0]=r[0]-o,s[1]=r[0]+o,s},significant:function(e,t){return e<t}}),e.extend(e.fn,{normalci:function(t,n){return e.normalci(t,n,this.toArray())},tci:function(t,n){return e.tci(t,n,this.toArray())}}),e.extend(e.fn,{oneSidedDifferenceOfProportions:function(t,n,o,r){var a=s(t,n,o,r);return e.ztest(a,1)},twoSidedDifferenceOfProportions:function(t,n,o,r){var a=s(t,n,o,r);return e.ztest(a,2)}})}(t,Math),t.models=function(){function e(e,n){var o=e.length,r=n[0].length-1,s=o-r-1,a=t.lstsq(n,e),i=t.multiply(n,a.map(function(e){return[e]})).map(function(e){return e[0]}),l=t.subtract(e,i),c=t.mean(e),u=t.sum(i.map(function(e){return Math.pow(e-c,2)})),m=t.sum(e.map(function(e,t){return Math.pow(e-i[t],2)})),p=u+m;return{exog:n,endog:e,nobs:o,df_model:r,df_resid:s,coef:a,predict:i,resid:l,ybar:c,SST:p,SSE:u,SSR:m,R2:u/p}}function n(n){var o,r,s=(o=n.exog,r=o[0].length,t.arange(r).map(function(n){var s=t.arange(r).filter(function(e){return e!==n});return e(t.col(o,n).map(function(e){return e[0]}),t.col(o,s))})),a=Math.sqrt(n.SSR/n.df_resid),i=s.map(function(e){var t=e.SST,n=e.R2;return a/Math.sqrt(t*(1-n))}),l=n.coef.map(function(e,t){return(e-0)/i[t]}),c=l.map(function(e){var o=t.studentt.cdf(e,n.df_resid);return 2*(o>.5?1-o:o)}),u=t.studentt.inv(.975,n.df_resid),m=n.coef.map(function(e,t){var n=u*i[t];return[e-n,e+n]});return{se:i,t:l,p:c,sigmaHat:a,interval95:m}}return{ols:function(o,r){var s=e(o,r),a=n(s),i=function(e){var n,o,r,s=e.R2/e.df_model/((1-e.R2)/e.df_resid);return{F_statistic:s,pvalue:1-(n=s,o=e.df_model,r=e.df_resid,t.beta.cdf(n/(r/o+n),o/2,r/2))}}(s),l=1-(1-s.R2)*((s.nobs-1)/s.df_resid);return s.t=a,s.f=i,s.adjust_R2=l,s}}}(),t.extend({buildxmatrix:function(){for(var e=new Array(arguments.length),n=0;n<arguments.length;n++){e[n]=[1].concat(arguments[n])}return t(e)},builddxmatrix:function(){for(var e=new Array(arguments[0].length),n=0;n<arguments[0].length;n++){e[n]=[1].concat(arguments[0][n])}return t(e)},buildjxmatrix:function(e){for(var n=new Array(e.length),o=0;o<e.length;o++)n[o]=e[o];return t.builddxmatrix(n)},buildymatrix:function(e){return t(e).transpose()},buildjymatrix:function(e){return e.transpose()},matrixmult:function(e,n){var o,r,s,a,i;if(e.cols()==n.rows()){if(n.rows()>1){for(a=[],o=0;o<e.rows();o++)for(a[o]=[],r=0;r<n.cols();r++){for(i=0,s=0;s<e.cols();s++)i+=e.toArray()[o][s]*n.toArray()[s][r];a[o][r]=i}return t(a)}for(a=[],o=0;o<e.rows();o++)for(a[o]=[],r=0;r<n.cols();r++){for(i=0,s=0;s<e.cols();s++)i+=e.toArray()[o][s]*n.toArray()[r];a[o][r]=i}return t(a)}},regress:function(e,n){var o=t.xtranspxinv(e),r=e.transpose(),s=t.matrixmult(t(o),r);return t.matrixmult(s,n)},regresst:function(e,n,o){var r=t.regress(e,n),s={anova:{}},a=t.jMatYBar(e,r);s.yBar=a;var i=n.mean();s.anova.residuals=t.residuals(n,a),s.anova.ssr=t.ssr(a,i),s.anova.msr=s.anova.ssr/(e[0].length-1),s.anova.sse=t.sse(n,a),s.anova.mse=s.anova.sse/(n.length-(e[0].length-1)-1),s.anova.sst=t.sst(n,i),s.anova.mst=s.anova.sst/(n.length-1),s.anova.r2=1-s.anova.sse/s.anova.sst,s.anova.r2<0&&(s.anova.r2=0),s.anova.fratio=s.anova.msr/s.anova.mse,s.anova.pvalue=t.anovaftest(s.anova.fratio,e[0].length-1,n.length-(e[0].length-1)-1),s.anova.rmse=Math.sqrt(s.anova.mse),s.anova.r2adj=1-s.anova.mse/s.anova.mst,s.anova.r2adj<0&&(s.anova.r2adj=0),s.stats=new Array(e[0].length);for(var l,c,u,m=t.xtranspxinv(e),p=0;p<r.length;p++)l=Math.sqrt(s.anova.mse*Math.abs(m[p][p])),c=Math.abs(r[p]/l),u=t.ttest(c,n.length-e[0].length-1,o),s.stats[p]=[r[p],l,c,u];return s.regress=r,s},xtranspx:function(e){return t.matrixmult(e.transpose(),e)},xtranspxinv:function(e){var n=t.matrixmult(e.transpose(),e);return t.inv(n)},jMatYBar:function(e,n){var o=t.matrixmult(e,n);return new t(o)},residuals:function(e,n){return t.matrixsubtract(e,n)},ssr:function(e,t){for(var n=0,o=0;o<e.length;o++)n+=Math.pow(e[o]-t,2);return n},sse:function(e,t){for(var n=0,o=0;o<e.length;o++)n+=Math.pow(e[o]-t[o],2);return n},sst:function(e,t){for(var n=0,o=0;o<e.length;o++)n+=Math.pow(e[o]-t,2);return n},matrixsubtract:function(e,n){for(var o=new Array(e.length),r=0;r<e.length;r++){o[r]=new Array(e[r].length);for(var s=0;s<e[r].length;s++)o[r][s]=e[r][s]-n[r][s]}return t(o)}}),t.jStat=t,t)},829(e,t,n){"use strict";n.d(t,{pd:()=>y,zV:()=>w,RJ:()=>p,ps:()=>g,B9:()=>v});var o,r=n(328),s=n(389),a=n(82),i=n(572);function l(e,t,n=!1,o=!1){if(e.length<=1||t.length<=1)throw new Error(`StatisticsError: Wrong sample size; expected at least 2, got ${Math.min(e.length,t.length)})`);const r=i.mean(e),s=i.mean(t),a=i.variance(e),l=i.variance(t),c=e.length,u=t.length;let m,p,d;if(n){const e=a/c,t=l/u,n=(r-s)/Math.sqrt(e+t);p=i.normal.pdf(n,0,1),m=1-p,d=2*(p<m?p:m)}else if(o){const e=c+u-2,t=(a*(c-1)+l*(u-1))/e,n=Math.sqrt(c*u/(c+u))*(r-s)/t;m=1-i.studentt.cdf(n,e),p=i.studentt.cdf(n,e),d=2*(p<m?p:m)}else{const e=a/c,t=l/u,n=(r-s)/Math.sqrt(e+t),o=Math.pow(e+t,2)/(Math.pow(e,2)/(c-1)+Math.pow(t,2)/(u-1));p=i.studentt.cdf(n,o),m=1-p,d=2*(p<m?p:m)}return{"p-value":d,"Mean difference":r-s,"p-value more":m,"p-value less":p}}!function(e){e.indexesOf=function(e,t){const n=[];for(let o=0;o<e.length;o++)t(e[o])&&n.push(o);return n},e.genRange=function(e,t,n=!1){const o=t-e+(n?0:1),r=new Int32Array(o);for(let t=0;t<o;++t)r[t]=e+t;return r},e.argSort=function(e,t=!1){const n=t?(e,t)=>t[0]-e[0]:(e,t)=>e[0]-t[0];return e.map((e,t)=>[e,t]).sort(n).map(e=>e[1])}}(o||(o={}));const c={"+":(e,t)=>e+t,"-":(e,t)=>e-t,"*":(e,t)=>e*t,"/":(e,t)=>e/t,min:(e,t)=>e<t?e:t,max:(e,t)=>e>t?e:t};var u=n(641),m=n(252);function p(e,t){return"true"===e.getTag("proteomics.de_complete")||(r.shell.warning(t),!1)}function d(e,t,n){const o=[];for(const r of t){const t=e.columns.byName(r);t&&!t.isNone(n)&&o.push(t.get(n))}return o}function f(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t/e.length}function g(e,t,n,r,s,i=u.M5,m=u.Dx){const p=e.rowCount,g=new Float32Array(p),h=new Float32Array(p),y=new Float32Array(p);g.fill(a.FLOAT_NULL),h.fill(a.FLOAT_NULL),y.fill(a.FLOAT_NULL);const E=[],w=[];for(let o=0;o<p;o++){const r=d(e,t,o),s=d(e,n,o);if(r.length<2||s.length<2)continue;g[o]=f(s)-f(r);const a=l(r,s)["p-value"];h[o]=a,E.push(o),w.push(a)}if(w.length>0){const[,e]=function(e,t=.05,n="n",r=!1){const s=e.length;let a,i,l=0;var u,m;r?(i=new Int32Array(s).fill(0).map((e,t)=>t),a=e):(i=function(e){const t=Array.from(e);return Int32Array.from(o.argSort(t))}(e),u=i,m=e,a=Float32Array.from(m).map((e,t)=>m[u[t]]));let p=function(e){const t=e.length;return Float32Array.from(e).map((e,n)=>(n+1)/t)}(a);if(["n","negcorr"].includes(n))l=function(e){let t=0;for(let n=0;n<e;++n)t+=1/(n+1);return t}(s),p=function(e,t,n="*"){return Float32Array.from(e).map((e,o)=>c[n](e,t))}(p,l,"/");else if(!["i","indep","p","poscorr"].includes(n))throw new Error("only indep and negcorr implemented");const d=new Array(s).fill(!1);let f=-1;for(let e=0;e<s;++e)a[e]<=p[e]*t&&(f=e);if(f>=0)for(let e=0;e<f;++e)d[e]=!0;let g=function(e,t,n="*"){return Float32Array.from(e).map((e,o)=>c[n](e,t[o]))}(a,p,"/");g=function(e){const t=e.length,n=Float32Array.from(e);for(let o=0;o<t;++o)n[o]=e.slice(0,o+1).reduce((e,t,n,o)=>c.min(e,t));return n}(g.reverse()).reverse();for(let e=0;e<s;++e)g[e]>1&&(g[e]=1);if(!r){const e=function(e,t){const n=Float32Array.from(e);for(let o=0;o<t.length;++o)n[t[o]]=e[o];return n}(g,i),t=function(e,t){const n=Array.from(e);for(let o=0;o<t.length;++o)n[t[o]]=e[o];return n}(d,i);return[t,e]}return[d,g]}(new Float32Array(w),m,"i");for(let t=0;t<E.length;t++)y[E[t]]=e[t]}const v=e.columns.addNewFloat("log2FC"),_=e.columns.addNewFloat("p-value"),C=e.columns.addNewFloat("adj.p-value");v.init(e=>g[e]),_.init(e=>h[e]),C.init(e=>y[e]),e.columns.addNewBool("significant").init(e=>{const t=y[e],n=g[e];return t!==a.FLOAT_NULL&&n!==a.FLOAT_NULL&&Math.abs(n)>=i&&t<=m}),v.semType=u.iu.LOG2FC,_.semType=u.iu.P_VALUE,C.semType=u.iu.P_VALUE,e.setTag("proteomics.de_complete","true"),e.fireValuesChanged();const b=E.length;return{tested:b,untestable:e.rowCount-b}}function h(e,t,n){const o=[...t,...n],r=[];for(let t=0;t<o.length;t++){const n=e.columns.byName(o[t]).getRawData(),s=new Float32Array(n.length);s.set(n),r.push(a.Column.fromFloat32Array(`s${t+1}`,s))}return a.DataFrame.fromColumns(r)}function y(e,t){const n=e.rowCount,o=t.rowCount,r=t.columns.byName("log2FC").getRawData(),s=t.columns.byName("p.value").getRawData(),i=t.columns.byName("adj.p.value").getRawData(),l=t.columns.byName("significant"),c=t.col("row"),m=new Int32Array(o);if(c){const e=c.getRawData();for(let t=0;t<o;t++)m[t]=(0|e[t])-1}else for(let e=0;e<o;e++)m[e]=e;const p=new Float32Array(n);p.fill(a.FLOAT_NULL);const d=new Float32Array(n);d.fill(a.FLOAT_NULL);const f=new Float32Array(n);f.fill(a.FLOAT_NULL);const g=new Uint8Array(n);let h=0;for(let e=0;e<o;e++){const t=m[e];if(t<0||t>=n)continue;p[t]=r[e],d[t]=s[e],f[t]=i[e];const o=l.get(e);!0!==o&&1!==o&&"1"!==o&&"TRUE"!==o||(g[t]=1,h++)}const y=a.Column.fromFloat32Array("log2FC",p),E=a.Column.fromFloat32Array("p-value",d),w=a.Column.fromFloat32Array("adj.p-value",f);return e.columns.addNewBool("significant").init(e=>1===g[e]),y.semType=u.iu.LOG2FC,E.semType=u.iu.P_VALUE,w.semType=u.iu.P_VALUE,e.columns.add(y),e.columns.add(E),e.columns.add(w),h}async function E(e,t,n,o,s){const a=h(e,t,n),i=y(e,await r.functions.call("Proteomics:LimmaDE",{exprDf:a,nGroup1:t.length,fcThreshold:o,pThreshold:s}));return e.setTag("proteomics.de_complete","true"),e.fireValuesChanged(),i}function w(e,t){return`${e} vs ${t}`}function v(e,t){const n=(0,m.f)(e);if(!n)return void r.shell.warning("Please annotate experimental groups first (Proteomics | Annotate Experiment)");if("true"===e.getTag("proteomics.de_complete"))return void r.shell.warning("Differential expression already performed");const o=n.group1,i=n.group2,l=s.divText(`Group 1: ${o.name} (${o.columns.length} samples), Group 2: ${i.name} (${i.columns.length} samples)`),c=[`${i.name} vs ${o.name}`,`${o.name} vs ${i.name}`],p=s.input.choice("Comparison",{value:w(o.name,i.name),items:c,nullable:!1}),d=s.div();d.style.cssText="font-style:italic; color:#888; font-size:12px; margin-bottom:8px;";const f=()=>{const e=p.value===c[1],t=e?o.name:i.name,n=e?i.name:o.name;d.textContent=`Positive log2FC = higher in ${t}, Negative log2FC = higher in ${n}`};p.onChanged.subscribe(f),f();const v=s.input.choice("Method",{value:"limma",items:["limma","DEqMS","t-test"],nullable:!1});v.setTooltip("limma: moderated t-test; DEqMS: peptide-count-weighted variance; t-test: client-side Welch's t-test");const _=e.columns.toList().find(e=>"Unique peptides"===e.name||"Peptides"===e.name)??void 0,C=s.input.column("Peptide count column",{table:e,value:_,filter:e=>e.type===a.COLUMN_TYPE.INT||e.type===a.COLUMN_TYPE.FLOAT,nullable:!1});C.setTooltip("Column with peptide/spectra counts per protein");const b=C.root;b.style.display="none",v.onChanged.subscribe(()=>{b.style.display="DEqMS"===v.value?"":"none"});const T=s.input.float("|log2FC| threshold",{value:u.M5});T.setTooltip("Minimum absolute fold change for significance");const P=s.input.float("Adj. p-value threshold",{value:u.Dx});P.setTooltip("Maximum adjusted p-value for significance"),s.dialog("Differential Expression").add(l).add(p).add(d).add(v).add(C).add(T).add(P).onOK(async()=>{const n=T.value??u.M5,s=P.value??u.Dx,l=v.value,m=p.value===c[1],d=m?o.columns:i.columns,f=m?i.columns:o.columns,w=(m?o.name:i.name,m?i.name:o.name,a.TaskBarProgressIndicator.create(`Running ${l} analysis...`));try{if("t-test"===l){const t=g(e,f,d,0,0,n,s);e.setTag("proteomics.de_method","t-test"),r.shell.info(`DE complete (t-test): ${t.tested} proteins tested, ${t.untestable} untestable`)}else if("DEqMS"===l){const t=C.value;if(!t)return void r.shell.error("Please select a peptide count column for DEqMS");try{const o=await async function(e,t,n,o,s,i){const l=h(e,t,n),c=a.DataFrame.create(e.rowCount),u=c.columns.addNewInt("count");for(let t=0;t<e.rowCount;t++)u.set(t,o.isNone(t)?1:Math.round(o.get(t)));const m=y(e,await r.functions.call("Proteomics:DeqmsDE",{exprDf:l,nGroup1:t.length,peptideDf:c,fcThreshold:s,pThreshold:i}));return e.setTag("proteomics.de_complete","true"),e.setTag("proteomics.de_method","deqms"),e.fireValuesChanged(),m}(e,f,d,t,n,s);e.setTag("proteomics.de_method","deqms"),r.shell.info(`DE complete (DEqMS): ${o} significant proteins`)}catch(t){console.warn("DEqMS failed, trying limma:",t),w.update(50,"DEqMS unavailable, trying limma..."),r.shell.warning("DEqMS unavailable, trying limma...");try{const t=await E(e,f,d,n,s);e.setTag("proteomics.de_method","limma"),r.shell.info(`DE complete (limma fallback): ${t} significant proteins`)}catch(t){console.warn("Limma DE also failed, using client-side fallback:",t),w.update(75,"Server-side DE unavailable, using client-side t-test..."),r.shell.warning("R environment unavailable — using client-side t-test");const o=g(e,f,d,0,0,n,s);e.setTag("proteomics.de_method","t-test"),r.shell.info(`DE complete (t-test): ${o.tested} proteins tested, ${o.untestable} untestable`)}}}else try{const t=await E(e,f,d,n,s);e.setTag("proteomics.de_method","limma"),r.shell.info(`DE complete (limma): ${t} significant proteins`)}catch(t){w.update(50,"Limma unavailable, using client-side t-test..."),r.shell.warning("R environment unavailable — using client-side t-test"),console.warn("Limma DE failed, using client-side fallback:",t);const o=g(e,f,d,0,0,n,s);e.setTag("proteomics.de_method","t-test"),r.shell.info(`DE complete (t-test): ${o.tested} proteins tested, ${o.untestable} untestable`)}}finally{w.close()}t&&t()}).show()}},989(e,t,n){"use strict";n.d(t,{J:()=>c,N:()=>u});var o=n(328),r=n(389),s=n(82),a=n(304),i=n(641),l=n(230);function c(e,t,n){const o=(0,a.I)(e);if(!o.log2fc||!o.pValue)throw new Error("No log2FC or adjusted p-value columns found. Run Differential Expression first.");const r=o.geneName??o.proteinId;if(!r)throw new Error("No gene-name or protein-ID column found to export.");const s=new Map;for(let t=0;t<e.rowCount;t++){const e=r.get(t);e&&s.set(t,String(e))}const i=o.log2fc.getRawData(),c=o.pValue.getRawData(),{upGenes:u,downGenes:m,background:p}=(0,l.Bx)(s,i,c,t,n),d=e=>/[",\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e,f=["gene,list"];for(const e of u)f.push(`${d(e)},up`);for(const e of m)f.push(`${d(e)},down`);for(const e of p)f.push(`${d(e)},background`);return{csv:f.join("\n"),counts:{up:u.length,down:m.length,background:p.length}}}function u(e){const t=(0,a.I)(e);if(!t.log2fc||!t.pValue)return void o.shell.warning("No log2FC or p-value columns found. Run Differential Expression first.");const n=r.input.float("|log2FC| threshold",{value:i.M5});n.setTooltip("Minimum absolute fold change for a gene to count as up/down.");const u=r.input.float("Adj. p-value threshold",{value:i.Dx});u.setTooltip("Maximum adjusted p-value for a gene to count as up/down.");const m=r.divText(""),p=()=>{const o=(0,l.bM)(e,n.value??i.M5,u.value??i.Dx,t.log2fc,t.pValue);m.textContent=`${o.significant} of ${o.total.toLocaleString()} proteins significant`};p(),n.onChanged.subscribe(p),u.onChanged.subscribe(p),r.dialog("Export Enrichment Inputs").add(m).add(n).add(u).onOK(()=>{const t=n.value??i.M5,r=u.value??i.Dx,{csv:a,counts:l}=c(e,t,r),m=e.name?`${e.name} — enrichment inputs`:"enrichment inputs";s.Utils.download(`${m}.csv`,a,"text/csv"),o.shell.info(`Exported ${l.up} up, ${l.down} down, ${l.background} background genes.`)}).show()}},230(e,t,n){"use strict";n.d(t,{AB:()=>E,Ae:()=>p.Ae,Bx:()=>v,D9:()=>C,Mz:()=>w,_W:()=>y,bM:()=>_,pG:()=>b,zy:()=>h});var o=n(328),r=n(389),s=n(82),a=n(498),i=n(304),l=n(641),c=n(897),u=n(829),m=n(252),p=n(935);const d="https://biit.cs.ut.ee/gprofiler";async function f(e,t,n=3e4){const r=o.dapi.fetchProxy(e,t),s=new Promise((e,t)=>setTimeout(()=>t(new Error("g:Profiler API request timed out. The service may be temporarily unavailable.")),n)),a=await Promise.race([r,s]);if(!a.ok)throw new Error(`g:Profiler API returned status ${a.status}`);return a}async function g(e,t,n,o,r=l.Dx){const s=await f(`${d}/api/gost/profile/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({organism:n,query:e,sources:o,user_threshold:r,significance_threshold_method:"fdr",domain_scope:"custom",background:t,all_results:!0,ordered:!1,no_evidences:!1,combined:!1,measure_underrepresentation:!1,no_iea:!1,numeric_ns:"",output:"json"})}),a=await s.json();return a.result?Array.isArray(a.result)&&a.result.length>0&&a.result[0]?.result?a.result[0].result:Array.isArray(a.result)?a.result:[]:[]}const h=["localization","cellular component organization","transport","cellular process","biological process","metabolic process"],y=["actin","vesicle","endocytosis","cytoskeleton"];function E(e,t=15){if(0===e.length)return{kept:[],stats:{total:0,kept:0,droppedParents:0,cappedAtN:t}};const n=e.filter(e=>"GO:BP"===e.source),o=e.filter(e=>"GO:BP"!==e.source);let r=0;const s=[];if(n.length>0){const e=[...n].sort((e,t)=>e.p_value-t.p_value);for(const n of e){const e=(n.name??"").toLowerCase();if(h.some(t=>e.includes(t))&&s.some(e=>y.some(t=>(e.name??"").toLowerCase().includes(t))))r++;else if(s.push(n),s.length>=t)break}}const a=[...o].sort((e,t)=>e.p_value-t.p_value).slice(0,t),i=[...s,...a].sort((e,t)=>e.p_value-t.p_value);return{kept:i,stats:{total:e.length,kept:i.length,droppedParents:r,cappedAtN:t}}}function w(e,t,n=l.Dx,o){const r=e.length,a=s.DataFrame.create(r);a.name="Enrichment Results";const i=e.map(e=>{if(!e.intersections)return"";const n=[],o=Math.min(t.length,e.intersections.length);for(let r=0;r<o;r++)e.intersections[r]&&e.intersections[r].length>0&&n.push(t[r]);return n.join(", ")}),c=a.columns.addNewString("Source"),u=a.columns.addNewString("Term ID"),m=a.columns.addNewString("Term Name"),p=a.columns.addNewFloat("FDR"),d=a.columns.addNewInt("Gene Count"),f=a.columns.addNewFloat("Gene Ratio"),g=a.columns.addNewString("Intersection");c.init(t=>e[t].source),u.init(t=>e[t].native),m.init(t=>e[t].name),p.init(t=>e[t].p_value),d.init(t=>e[t].intersection_size),f.init(t=>e[t].precision),g.init(e=>i[e]);const h=p.getRawData();return a.columns.addNewBool("Significant").init(e=>h[e]!==s.FLOAT_NULL&&h[e]<=n),o&&a.columns.addNewString("Direction").init(()=>o),p.setTag("color-coding-type","Linear"),p.setTag("color-coding-linear",'{"0":"#2ecc71","0.05":"#f39c12","1":"#e74c3c"}'),a.setTag("proteomics.enrichment","true"),a}function v(e,t,n,o,r){const a=new Set,i=new Set,l=new Set;for(const[c,u]of e){l.add(u);const e=t[c],m=n[c];e!==s.FLOAT_NULL&&m!==s.FLOAT_NULL&&m<=r&&Math.abs(e)>=o&&(e>0?a.add(u):e<0&&i.add(u))}return{upGenes:[...a],downGenes:[...i],background:[...l]}}function _(e,t,n,o,r){const a=e.rowCount,i=o.getRawData(),l=r.getRawData();let c=0;for(let e=0;e<a;e++){const o=i[e],r=l[e];o!==s.FLOAT_NULL&&r!==s.FLOAT_NULL&&Math.abs(o)>=t&&r<=n&&c++}return{significant:c,total:a}}async function C(e,t,n,o,r,s=!0,c=15){const u=(0,i.I)(e);if(!u.proteinId)throw new Error("No protein ID column found");if(!u.log2fc||!u.pValue)throw new Error("No log2FC or adjusted p-value columns found. Run Differential Expression first.");let m,p=0,h=0,y=0;if(u.geneName){m=new Map;const t=u.geneName;for(let n=0;n<e.rowCount;n++){const e=t.get(n);e&&m.set(n,e)}p=m.size,h=e.rowCount,y=h-p}else{const t=new Map;for(let n=0;n<e.rowCount;n++){const e=u.proteinId.get(n),o=(0,a.S6)(e);o&&(t.has(o)||t.set(o,[]),t.get(o).push(n))}const n=[...t.keys()],r=await async function(e,t="hsapiens"){const n=await f(`${d}/api/convert/convert/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({organism:t,query:e,target:"ENSG",numeric_ns:"",output:"json"})});return(await n.json()).result??[]}(n,o),s=new Map;for(const e of r)e.incoming&&e.name&&"N/A"!==e.name&&!s.has(e.incoming)&&s.set(e.incoming,e.name);m=new Map;for(const[e,n]of t){const t=s.get(e);if(t)for(const e of n)m.set(e,t)}const i=new Array(e.rowCount).fill("");for(const[e,t]of m)i[e]=t;const c=e.columns.addNewString("Gene Symbol (mapped)");c.semType=l.iu.GENE_SYMBOL,c.init(e=>i[e]),p=s.size,h=n.length,y=h-p}const _=u.log2fc.getRawData(),C=u.pValue.getRawData(),{upGenes:b,downGenes:T,background:P}=v(m,_,C,t,n);if(0===b.length&&0===T.length)throw new Error("No significant proteins found with the given thresholds");const S=[];let N=null,A=null;if(b.length>0){let e=await g(b,P,o,r,n);if(s){const t=E(e,c);e=t.kept,N=t.stats}S.push(w(e,b,n,"Up"))}if(T.length>0){let e=await g(T,P,o,r,n);if(s){const t=E(e,c);e=t.kept,A=t.stats}S.push(w(e,T,n,"Down"))}let x=S[0];for(let e=1;e<S.length;e++)x=x.append(S[e]);x.name=e.name?`${e.name} — Enrichment`:"Enrichment Results",x.setTag("proteomics.enrichment","true");const D=x.col("FDR");if(D&&(D.setTag("color-coding-type","Linear"),D.setTag("color-coding-linear",'{"0":"#2ecc71","0.05":"#f39c12","1":"#e74c3c"}')),s){const e=(N?.total??0)+(A?.total??0),t=(N?.kept??0)+(A?.kept??0),n=(N?.droppedParents??0)+(A?.droppedParents??0);t<e&&(x.setTag("proteomics.enrichment_smart_filtered","true"),x.setTag("proteomics.enrichment_smart_filtered_kept",String(t)),x.setTag("proteomics.enrichment_smart_filtered_total",String(e)),x.setTag("proteomics.enrichment_smart_filtered_dropped_parents",String(n)),x.setTag("proteomics.enrichment_smart_filtered_cap",String(c)))}return{enrichmentDf:x,mapped:p,total:h,unmapped:y}}function b(e){if(!(0,u.RJ)(e,"Run Differential Expression first"))return;const t=(0,i.I)(e);if(!t.log2fc||!t.pValue)return void o.shell.warning("No log2FC or p-value columns found");const n=r.input.float("|log2FC| threshold",{value:l.M5});n.setTooltip("Minimum absolute fold change for significance");const a=r.input.float("Adj. p-value threshold",{value:l.Dx});a.setTooltip("Maximum adjusted p-value for significance");const d=(0,p.X3)((0,m.Di)(e)??(0,p.Vr)(e)),f=r.input.choice("Organism",{value:d??"Homo sapiens (Human)",items:p.Ae.map(e=>e.display),nullable:!1}),g=r.input.bool("GO: Biological Process",{value:!0}),h=r.input.bool("GO: Molecular Function",{value:!0}),y=r.input.bool("GO: Cellular Component",{value:!0}),E=r.input.bool("KEGG Pathways",{value:!0}),w=r.input.bool("Reactome Pathways",{value:!0}),v=r.input.bool("WikiPathways",{value:!0}),b=r.input.bool("Apply smart pathway filter",{value:!0});b.setTooltip("Drops generic GO parent terms when more specific child terms are present; caps each source at top-N by FDR. Recommended for cleaner results; uncheck for raw g:Profiler output.");const T=r.input.int("Max terms per source",{value:15,min:1});T.setTooltip("Upper bound on terms kept per enrichment source (top-N by FDR). Applies only when the smart pathway filter is on.");const P=()=>T.enabled=b.value??!0;b.onChanged.subscribe(P),P();const S=r.divText(""),N=()=>{const o=n.value??l.M5,r=a.value??l.Dx,s=_(e,o,r,t.log2fc,t.pValue),i=s.total.toLocaleString();S.textContent=`${s.significant} of ${i} proteins are significant with these thresholds`};N(),n.onChanged.subscribe(N),a.onChanged.subscribe(N),r.dialog("Enrichment Analysis").add(S).add(n).add(a).add(f).add(g).add(h).add(y).add(E).add(w).add(v).add(b).add(T).onOK(async()=>{const t=s.TaskBarProgressIndicator.create("Running enrichment analysis...");try{const t=n.value??l.M5,r=a.value??l.Dx,s=f.value,i=p.Ae.find(e=>e.display===s),u=i?.code??"hsapiens";(0,m.Np)(e,u);const d=[];if(g.value&&d.push("GO:BP"),h.value&&d.push("GO:MF"),y.value&&d.push("GO:CC"),E.value&&d.push("KEGG"),w.value&&d.push("REAC"),v.value&&d.push("WP"),0===d.length)return void o.shell.warning("Please select at least one enrichment source");const _=await C(e,t,r,u,d,b.value??!0,T.value??15),P=_.total>0?(_.mapped/_.total*100).toFixed(1):"0.0";o.shell.info(`${_.mapped}/${_.total} proteins mapped (${P}%). ${_.unmapped} unmapped.`),(0,c.q6)(_.enrichmentDf,e)}catch(e){o.shell.error(`Enrichment analysis failed: ${e.message}`)}finally{t.close()}}).show()}},252(e,t,n){"use strict";n.d(t,{$Y:()=>u,Di:()=>d,Np:()=>p,XX:()=>g,Yf:()=>f,applyAnnotation:()=>h,f:()=>m});var o=n(328),r=n(389),s=n(353),a=n.n(s),i=n(641),l=n(655),c=n(935);function u(e,t){e.setTag("proteomics.groups",JSON.stringify(t))}function m(e){const t=e.getTag("proteomics.groups");if(!t)return null;try{return JSON.parse(t)}catch{return null}}function p(e,t){e.setTag("proteomics.organism",t)}function d(e){return e.getTag("proteomics.organism")||void 0}function f(e,t){const n=function(e){const t=(0,l.getRunMeta)(e);if(t)return t;const n=e.getTag("proteomics.spc_run_meta_seed");if(n)try{return JSON.parse(n)}catch{return}}(e),o=m(e);if(!o)return{group1Name:"Control",group1Cols:[],group2Name:"Treatment",group2Cols:[],instrumentId:n?.instrument_id,acquisitionDatetime:n?.acquisition_datetime};const r=new Set(t),s=t=>t.filter(e=>r.has(e)).map(t=>e.col(t)).filter(e=>null!==e);return{group1Name:o.group1.name||"Control",group1Cols:s(o.group1.columns),group2Name:o.group2.name||"Treatment",group2Cols:s(o.group2.columns),instrumentId:n?.instrument_id,acquisitionDatetime:n?.acquisition_datetime}}function g(e){const t=e.columns.toList().filter(e=>e.semType===i.iu.INTENSITY&&e.name.startsWith("log2(")).map(e=>e.name),n=f(e,t),s=r.input.string("Group 1 Name",{value:n.group1Name}),l=r.input.columns("Group 1",{table:e,available:t,value:n.group1Cols}),u=r.input.string("Group 2 Name",{value:n.group2Name}),m=r.input.columns("Group 2",{table:e,available:t,value:n.group2Cols}),p=r.input.string("Instrument",{value:n.instrumentId??"",tooltipText:"Free-text identifier for the instrument that ran this analysis (e.g. QExactive-01). Used to group runs in the SPC dashboard."}),g=r.input.date("Acquisition datetime",{value:n.acquisitionDatetime?a()(n.acquisitionDatetime):null,tooltipText:"When the samples were acquired on the instrument. Used to order runs on the SPC trend chart — not the file-import time."}),y=r.input.choice("Organism",{value:(0,c.X3)(d(e)??(0,c.Vr)(e))??"Homo sapiens (Human)",items:c.Ae.map(e=>e.display),nullable:!1,tooltipText:"Species for enrichment (g:Profiler) and UniProt subcellular-location lookup. Auto-detected from the data when available."});r.dialog("Annotate Experiment").add(s).add(l).add(u).add(m).add(y).add(p).add(g).onOK(()=>{const t=l.value??[],n=m.value??[];if(0===t.length||0===n.length)return void o.shell.warning("Select at least one column per group");const r={group1:{name:s.value,columns:t.map(e=>e.name)},group2:{name:u.value,columns:n.map(e=>e.name)}},a=(p.value??"").trim(),i=g.value,d=i&&"function"==typeof i.toISOString||i instanceof Date?i.toISOString():"";h(e,{group1:r.group1,group2:r.group2,organism:(0,c.$S)(y.value??void 0),runMeta:a.length>0||d.length>0?{instrument_id:a,acquisition_datetime:d}:void 0}),o.shell.info(`Groups assigned: ${t.length} + ${n.length} samples`)}).show()}function h(e,t){u(e,{group1:t.group1,group2:t.group2}),t.organism&&p(e,t.organism),t.runMeta&&(0,l.setRunMeta)(e,t.runMeta)}},47(e,t,n){"use strict";n.d(t,{Mx:()=>u,Q2:()=>p,U0:()=>c,UN:()=>f,fX:()=>m,p4:()=>d});var o=n(328),r=n(389),s=n(82),a=n(641),i=n(252);function l(e,t){const n=Math.random(),o=Math.random();return e+t*(Math.sqrt(-2*Math.log(n))*Math.cos(2*Math.PI*o))}function c(e,t,n=1.8,o=.3){let r=0;for(const a of t){const t=e.col(a);if(!t)continue;if(t.type!==s.COLUMN_TYPE.FLOAT)continue;const i=t.stats.avg,c=t.stats.stdev;if(isNaN(i)||isNaN(c)||0===c)continue;const u=i-n*c,m=o*c,p=t.getRawData();for(let t=0;t<e.rowCount;t++)p[t]===s.FLOAT_NULL&&(p[t]=l(u,m),r++)}return e.fireValuesChanged(),e.setTag("proteomics.imputed","true"),r}function u(e,t,n=10){const o=t.map(t=>e.col(t)).filter(e=>null!=e&&e.type===s.COLUMN_TYPE.FLOAT);if(0===o.length)return 0;const r=o.map(e=>e.getRawData()),a=e.rowCount,i=o.length,l=[],c=[];for(let e=0;e<a;e++){const t=new Float64Array(i),n=[];for(let r=0;r<i;r++){const s=o[r].isNone(e);n.push(s),t[r]=s?0:o[r].get(e)}l.push(t),c.push(n)}const u=new Float64Array(i);for(let e=0;e<i;e++){let t=0,n=0;for(let o=0;o<a;o++)c[o][e]||(t+=l[o][e],n++);u[e]=n>0?t/n:NaN}const m=[];for(let e=0;e<a;e++)c[e].some(e=>e)&&m.push(e);const p=s.TaskBarProgressIndicator.create("kNN imputation...");let d=0;try{for(let e=0;e<m.length;e++){const t=m[e];if(p.update(Math.round(e/m.length*100),`Row ${e+1}/${m.length}`),!c[t].some(e=>!e)){for(let e=0;e<i;e++)c[t][e]&&isFinite(u[e])&&(r[e][t]=u[e],d++);continue}const o=[];for(let e=0;e<a;e++){if(e===t)continue;let n=0,r=0;for(let o=0;o<i;o++)if(!c[t][o]&&!c[e][o]){const s=l[t][o]-l[e][o];n+=s*s,r++}r>0&&o.push({row:e,dist:Math.sqrt(n/r)})}o.sort((e,t)=>e.dist-t.dist);const s=o.slice(0,n);for(let e=0;e<i;e++){if(!c[t][e])continue;let n=0,o=0;for(const t of s)c[t.row][e]||(n+=l[t.row][e],o++);const a=o>0?n/o:u[e];isFinite(a)&&(r[e][t]=a,d++)}}}finally{p.close()}return e.fireValuesChanged(),e.setTag("proteomics.imputed","true"),d}function m(e,t){let n=0;for(const o of t){const t=e.col(o);if(!t||t.type!==s.COLUMN_TYPE.FLOAT)continue;const r=t.getRawData();for(let t=0;t<e.rowCount;t++)r[t]===s.FLOAT_NULL&&(r[t]=0,n++)}return e.fireValuesChanged(),e.setTag("proteomics.imputed","true"),n}function p(e,t){let n=0;for(const o of t){const t=e.col(o);if(!t||t.type!==s.COLUMN_TYPE.FLOAT)continue;const r=t.stats.avg;if(isNaN(r))continue;const a=t.getRawData();for(let t=0;t<e.rowCount;t++)a[t]===s.FLOAT_NULL&&(a[t]=r,n++)}return e.fireValuesChanged(),e.setTag("proteomics.imputed","true"),n}function d(e,t){let n=0;for(const o of t){const t=e.col(o);if(!t||t.type!==s.COLUMN_TYPE.FLOAT)continue;const r=t.stats.med;if(isNaN(r))continue;const a=t.getRawData();for(let t=0;t<e.rowCount;t++)a[t]===s.FLOAT_NULL&&(a[t]=r,n++)}return e.fireValuesChanged(),e.setTag("proteomics.imputed","true"),n}function f(e){if("true"===e.getTag("proteomics.imputed"))return void o.shell.warning("Missing values already imputed");const t=e.columns.toList().filter(e=>e.semType===a.iu.INTENSITY&&e.name.startsWith("log2(")).map(e=>e.name),n=t.map(t=>e.col(t)),l=r.input.choice("Method",{value:"MinProb",items:["MinProb","kNN","Zero","Mean","Median"],nullable:!1}),f=r.input.columns("Intensity columns",{table:e,available:t,value:n}),g=r.input.float("Downshift",{value:1.8});g.setTooltip("Standard deviations to shift left from mean (Perseus default: 1.8)");const h=r.input.float("Width",{value:.3});h.setTooltip("Fraction of standard deviation for imputation distribution (Perseus default: 0.3)");const y=r.div([g.root,h.root]),E=r.input.int("k (neighbors)",{value:10}),w=r.div([E.root]);w.style.display="none",l.onChanged.subscribe(()=>{const e=l.value;y.style.display="MinProb"===e?"":"none",w.style.display="kNN"===e?"":"none"});const v=r.input.int("Min valid values per group",{value:2}),_=r.divText("");_.style.cssText="font-size:12px; color:#888; margin-bottom:8px;";const C=()=>{const t=v.value??0,n=(0,i.f)(e);if(0===t||!n)return void(_.textContent=`Will keep all ${e.rowCount} proteins`);const o=n.group1.columns.map(t=>e.col(t)).filter(e=>null!=e),r=n.group2.columns.map(t=>e.col(t)).filter(e=>null!=e);let s=0;for(let n=0;n<e.rowCount;n++){let e=0;for(const t of o)t.isNone(n)||e++;let a=0;for(const e of r)e.isNone(n)||a++;(e>=t||a>=t)&&s++}const a=e.rowCount-s;_.textContent=`Will keep ${s}/${e.rowCount} proteins (${a} removed)`};v.onChanged.subscribe(C),C(),r.dialog("Impute Missing Values").add(l).add(f).add(y).add(w).add(v).add(_).onOK(()=>{const t=f.value.map(e=>e.name),n=l.value,r=v.value??0,a=(0,i.f)(e);if(r>0&&a){const t=a.group1.columns.map(t=>e.col(t)).filter(e=>null!=e),n=a.group2.columns.map(t=>e.col(t)).filter(e=>null!=e),i=s.BitSet.create(e.rowCount);for(let o=0;o<e.rowCount;o++){let e=0;for(const n of t)n.isNone(o)||e++;let s=0;for(const e of n)e.isNone(o)||s++;e<r&&s<r&&i.set(o,!0)}const l=i.trueCount;l>0&&(e.rows.removeWhere(e=>i.get(e.idx)),o.shell.info(`Filtered: removed ${l} proteins below threshold`))}let y=0;try{switch(n){case"MinProb":y=c(e,t,g.value,h.value);break;case"kNN":y=u(e,t,E.value);break;case"Zero":y=m(e,t);break;case"Mean":y=p(e,t);break;case"Median":y=d(e,t)}}catch(e){return void o.shell.error(`Imputation failed: ${e?.message??e}. Valid-values filter was already applied; data remains filtered but un-imputed.`)}o.shell.info(`Imputed ${y} missing values across ${t.length} columns (${n})`)}).show()}},871(e,t,n){"use strict";n.d(t,{DA:()=>c,IZ:()=>l,Kb:()=>u,ye:()=>i});var o=n(328),r=n(389),s=n(641),a=n(954);function i(e){return e.columns.toList().filter(e=>e.semType===s.iu.INTENSITY&&!e.name.startsWith("log2(")).map(e=>e.name)}function l(e,t){for(const n of t){const t=e.col(n),o=e.col(`log2(${n})`);if(t&&o)for(let n=0;n<e.rowCount;n++){if(t.isNone(n)||o.isNone(n))continue;const e=Number(t.get(n)),r=Number(o.get(n));if(e>0&&Number.isFinite(r)){if(Math.abs(r-Math.log2(e))<1e-4)return"transform";if(Math.abs(r-e)<1e-4)return"copy"}}}return"unknown"}function c(e,t){const n=i(e);if(0===n.length)return!1;if(l(e,n)===(t?"copy":"transform"))return!1;for(const t of n){const n=`log2(${t})`;e.col(n)&&e.columns.remove(n)}t?(0,a.l3)(e,n):(0,a.Kh)(e,n);for(const t of["proteomics.normalized","proteomics.imputed","proteomics.de_complete","proteomics.de_method"])e.setTag(t,"");return!0}function u(e){const t=i(e);if(0===t.length)return void o.shell.warning("No intensity columns found — nothing to rescale.");const n=l(e,t),s=(0,a.eY)(e,t),u=r.input.bool("Data is already log2-transformed",{value:"copy"===n,tooltipText:"On: intensities are used as-is. Off: a log2 transform is applied. Flip this if fold changes look wildly off — the import heuristic can misread small-magnitude raw intensities as already-log2."}),m=r.divText(`Auto-detection: ${s.message}.`+("unknown"!==n?` Currently applied: ${"copy"===n?"used as-is (no transform)":"log2-transformed"}.`:""));m.style.cssText="font-style:italic;color:#888;margin:4px 0;font-size:12px;max-width:420px;";const p=["proteomics.normalized","proteomics.imputed","proteomics.de_complete"].some(t=>"true"===e.getTag(t)),d=r.divText("Normalize / Impute / Differential Expression have already run. Changing the scale resets those steps — re-run them from Analyze.");d.style.cssText="color:#b26a00;margin:4px 0;font-size:12px;max-width:420px;",d.style.display=p?"":"none",r.dialog("Set Log2 Scale").add(u).add(m).add(d).onOK(()=>{c(e,u.value)?o.shell.info(u.value?"Intensities are now used as-is (no log2 transform). Re-run analysis steps.":"Intensities are now log2-transformed. Re-run analysis steps."):o.shell.info("Scale unchanged.")}).show()}},350(e,t,n){"use strict";n.d(t,{Nx:()=>u,VD:()=>c,aj:()=>l,v5:()=>m});var o=n(328),r=n(389),s=n(82),a=n(641),i=n(715);function l(e,t){for(const n of t){const t=e.col(n);if(!t)continue;if(t.type!==s.COLUMN_TYPE.FLOAT){console.warn(`medianNormalize: skipping non-float column "${n}" (type=${t.type})`);continue}const o=t.stats.med;if(isNaN(o))continue;const r=t.getRawData();for(let e=0;e<r.length;e++)t.isNone(e)||(r[e]-=o)}e.fireValuesChanged(),e.setTag("proteomics.normalized","true")}function c(e,t){if(t.length<2)return;const n=t.map(t=>e.col(t)).filter(e=>null!=e&&e.type===s.COLUMN_TYPE.FLOAT);if(n.length<2)return;const o=e.rowCount,r=[];for(const e of n){const t=e.getRawData(),n=[];for(let t=0;t<o;t++)e.isNone(t)||n.push(t);n.sort((e,n)=>t[e]-t[n]),r.push({indices:n,raw:t})}const a=Math.max(...r.map(e=>e.indices.length));if(0===a)return;const i=new Float64Array(a);for(let e=0;e<a;e++){let t=0,n=0;for(const o of r){if(0===o.indices.length)continue;const r=e/(a-1)*(o.indices.length-1),s=Math.floor(r),i=Math.min(Math.ceil(r),o.indices.length-1),l=r-s;t+=(1-l)*o.raw[o.indices[s]]+l*o.raw[o.indices[i]],n++}i[e]=t/n}for(const e of r){const t=e.indices.length;if(0!==t)for(let n=0;n<t;n++){const o=1===a?0:n/(t-1)*(a-1),r=Math.floor(o),s=Math.min(Math.ceil(o),a-1),l=o-r,c=(1-l)*i[r]+l*i[s];e.raw[e.indices[n]]=c}}e.fireValuesChanged(),e.setTag("proteomics.normalized","true")}async function u(e,t){try{const n=[],r=[];for(const o of t)if(o.startsWith("log2(")&&o.endsWith(")")){const t=o.slice(5,-1);e.col(t)&&(n.push(t),r.push(o))}if(0===n.length)return t.length<2?void o.shell.warning("Cannot normalize — VSN needs raw intensity columns and quantile fallback needs at least 2 columns"):(o.shell.warning("No raw intensity columns found for VSN — using quantile normalization"),void c(e,t));const a=s.DataFrame.create(e.rowCount);for(let t=0;t<n.length;t++){const o=e.col(n[t]).getRawData();a.columns.addNewFloat(`s${t+1}`).init(e=>o[e])}const i=await o.functions.call("Proteomics:VsnNormalize",{exprDf:a});for(let t=0;t<r.length;t++){const n=e.col(r[t]),o=i.col(`s${t+1}`),a=n.getRawData(),l=o.getRawData();for(let t=0;t<e.rowCount;t++)l[t]!==s.FLOAT_NULL&&(a[t]=l[t])}e.fireValuesChanged(),e.setTag("proteomics.normalized","true")}catch(n){if(console.warn("VSN normalization failed, using quantile fallback:",n),t.length<2)return void o.shell.warning("VSN failed and quantile fallback needs at least 2 columns — data left unnormalized");o.shell.warning("R environment unavailable — using quantile normalization"),c(e,t)}}function m(e){if("true"===e.getTag("proteomics.normalized"))return void o.shell.warning("Data already normalized");const t=e.columns.toList().filter(e=>e.semType===a.iu.INTENSITY&&e.name.startsWith("log2(")).map(e=>e.name),n=t.map(t=>e.col(t)),m=r.div([],{style:{background:"#FFF3CD",border:"1px solid #FFEEBA",color:"#856404",padding:"8px",margin:"4px 0",borderRadius:"4px",display:"true"===e.getTag("proteomics.preNormalized")?"":"none"}});m.textContent="This data may be pre-normalized (Spectronaut). Additional normalization may distort results.";const p=r.input.choice("Method",{value:"Median Centering",items:["Median Centering","Quantile","VSN"],nullable:!1}),d=r.input.columns("Intensity columns",{table:e,available:t,value:n}),f=r.div([],{style:{width:"100%",height:"250px",border:"1px solid #ddd",marginTop:"8px"}});function g(){f.innerHTML="";const t=d.value.map(e=>e.name);if(0===t.length)return;const n=e.clone(null,t),o=p.value;"Median Centering"===o?l(n,t):"Quantile"===o&&c(n,t);const r=(0,i.j4)(n,t),a=s.Viewer.boxPlot(r,{valueColumnName:"Intensity",categoryColumnName:"Sample"});a.root.style.width="100%",a.root.style.height="220px",f.appendChild(a.root)}p.onChanged.subscribe(()=>g()),d.onChanged.subscribe(()=>g()),g(),r.dialog("Normalize").add(m).add(p).add(d).add(f).onOK(async()=>{const t=d.value.map(e=>e.name),n=p.value;"Median Centering"===n?l(e,t):"Quantile"===n?c(e,t):"VSN"===n&&await u(e,t),o.shell.info(`Normalized ${t.length} columns (${n})`)}).show()}},883(e,t,n){"use strict";n.d(t,{$G:()=>S,OI:()=>P,loadBaseline:()=>w,loadRuns:()=>E,oF:()=>C,readRunsMeta:()=>h,saveBaseline:()=>v,upsertRun:()=>y});var o=n(328),r=n(82);const s=["run_id","instrument_id","acquisition_datetime","run_label","median_intensity","missing_pct","control_corr","protein_count","status","rules_tripped","source_project_id","source_df_name","computed_at"],a="spc.runs.schema_version";function i(e){return e&&e.root?e.root:"System:AppData/Proteomics/spc"}function l(e){return`${i(e)}/runs.csv`}function c(e){return`${i(e)}/runs-meta.json`}function u(e,t){return`${i(t)}/baseline-${function(e){if(null==e)return"unnamed";let t=String(e).replace(/[^A-Za-z0-9._-]+/g,"-").replace(/-{2,}/g,"-").replace(/^[-.]+|[-.]+$/g,"").slice(0,64).replace(/[-.]+$/g,"");return 0===t.length&&(t="unnamed"),t}(e)}.json`}function m(e){return e.indexOf(",")<0&&e.indexOf('"')<0&&e.indexOf("\n")<0?e:'"'+e.replace(/"/g,'""')+'"'}function p(e){const t=[];let n=0;for(;n<e.length;)if('"'===e[n]){n++;let o="";for(;n<e.length;)if('"'===e[n]){if('"'!==e[n+1]){n++;break}o+='"',n+=2}else o+=e[n],n++;t.push(o),","===e[n]&&n++}else{let o="";for(;n<e.length&&","!==e[n];)o+=e[n],n++;t.push(o),","===e[n]&&n++}return t}function d(e){return[e.run_id,e.instrument_id,e.acquisition_datetime,e.run_label,String(e.median_intensity),String(e.missing_pct),String(e.control_corr),String(e.protein_count),e.status,JSON.stringify(e.rules_tripped),null==e.source_project_id?"":e.source_project_id,e.source_df_name,e.computed_at].map(m).join(",")}function f(e){const t=t=>e[(e=>s.indexOf(e))(t)]??"";let n=[];try{const e=t("rules_tripped");e&&(n=JSON.parse(e))}catch{}const o=t("source_project_id");return{run_id:t("run_id"),instrument_id:t("instrument_id"),acquisition_datetime:t("acquisition_datetime"),run_label:t("run_label"),median_intensity:Number(t("median_intensity")),missing_pct:Number(t("missing_pct")),control_corr:Number(t("control_corr")),protein_count:Number(t("protein_count")),status:t("status"),rules_tripped:n,source_project_id:0===o.length?null:o,source_df_name:t("source_df_name"),computed_at:t("computed_at")}}async function g(e){const t=l(e);if(!await o.dapi.files.exists(t))return[];const n=function(e){const t=[],n=e.split("\n").filter(e=>e.length>0);for(const e of n)t.push(p(e));return t}(await o.dapi.files.readAsText(t));return n.length<=1?[]:n.slice(1).map(f)}async function h(e){const t=c(e);if(!await o.dapi.files.exists(t))return{};try{return JSON.parse(await o.dapi.files.readAsText(t))}catch(e){return console.warn(`[spc-storage] failed to parse ${t}: ${e}`),{}}}async function y(e,t){const n=await g(t),r=n.findIndex(t=>t.instrument_id===e.instrument_id&&t.acquisition_datetime===e.acquisition_datetime);let i;r>=0?(i={...n[r],...e,run_id:n[r].run_id,rules_tripped:e.rules_tripped,source_project_id:e.source_project_id},n[r]=i):(i={run_id:e.run_id??("undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"r-"+Math.random().toString(16).slice(2)+"-"+Date.now().toString(16)),instrument_id:e.instrument_id,acquisition_datetime:e.acquisition_datetime,run_label:e.run_label,median_intensity:e.median_intensity,missing_pct:e.missing_pct,control_corr:e.control_corr,protein_count:e.protein_count,status:e.status,rules_tripped:e.rules_tripped,source_project_id:e.source_project_id,source_df_name:e.source_df_name,computed_at:e.computed_at},n.push(i)),await o.dapi.files.writeAsText(l(t),function(e){const t=[s.map(m).join(",")];for(const n of e)t.push(d(n));return t.join("\n")+"\n"}(n));const u=await async function(e){return(await h(e))[a]??null}(t);return"1"!==u&&await async function(e,t){const n=await h(t);n[a]=e,await async function(e,t){await o.dapi.files.writeAsText(c(t),JSON.stringify(e,null,2))}(n,t)}("1",t),i}async function E(e,t){const n=await g(t),o=e?n.filter(t=>t.instrument_id===e):n;return o.sort((e,t)=>e.acquisition_datetime.localeCompare(t.acquisition_datetime)),o}async function w(e,t){const n=u(e,t);if(!await o.dapi.files.exists(n))return null;try{return JSON.parse(await o.dapi.files.readAsText(n))}catch(e){return console.warn(`[spc-storage] failed to parse baseline at ${n}: ${e}`),null}}async function v(e,t,n){await o.dapi.files.writeAsText(u(e,n),JSON.stringify(t,null,2))}function _(e){const t=e.length;if(0===t)return{mean:NaN,sd:NaN};let n=0;for(const t of e)n+=t;const o=n/t;let r=0;for(const t of e){const e=t-o;r+=e*e}return{mean:o,sd:t>1?Math.sqrt(r/(t-1)):0}}function C(e,t=2){const n=e.slice(),o=[],r=[];if(n.length<3)return{retained_run_ids:n.map(e=>e.run_id),excluded_run_ids:[],iteration_trace:[]};for(let e=1;e<=t;e++){const t=n.map(e=>e.value).filter(e=>Number.isFinite(e)),{mean:s,sd:a}=_(t);if(!Number.isFinite(a)||0===a)break;const i=[];for(let e=n.length-1;e>=0;e--){const t=n[e].value;if(!Number.isFinite(t))continue;const r=(t-s)/a;Math.abs(r)>3&&(i.push(n[e]),o.push(n[e]),n.splice(e,1))}if(0===i.length)break;r.push({iter:e,dropped:i.map(e=>e.run_id)})}return{retained_run_ids:n.map(e=>e.run_id),excluded_run_ids:o.map(e=>e.run_id),iteration_trace:r}}const b=["median_intensity","missing_pct","control_corr","protein_count"];function T(e){const t=e.filter(e=>Number.isFinite(e));if(t.length<2)return{mean:NaN,sd:NaN};const{mean:n,sd:o}=_(t);return{mean:n,sd:o}}function P(e){const t={};for(const n of b)t[n]=T(e.map(e=>e[n]));return t}function S(e){const t=t=>e.map(t),n=[r.Column.fromStrings("run_id",t(e=>e.run_id)),r.Column.fromStrings("instrument_id",t(e=>e.instrument_id)),r.Column.fromList(r.COLUMN_TYPE.DATE_TIME,"acquisition_datetime",t(e=>Date.parse(e.acquisition_datetime))),r.Column.fromStrings("run_label",t(e=>e.run_label)),r.Column.fromFloat32Array("median_intensity",new Float32Array(t(e=>e.median_intensity))),r.Column.fromFloat32Array("missing_pct",new Float32Array(t(e=>e.missing_pct))),r.Column.fromFloat32Array("control_corr",new Float32Array(t(e=>e.control_corr))),r.Column.fromFloat32Array("protein_count",new Float32Array(t(e=>e.protein_count))),r.Column.fromStrings("status",t(e=>e.status)),r.Column.fromStrings("rules_tripped",t(e=>JSON.stringify(e.rules_tripped))),r.Column.fromStrings("source_project_id",t(e=>e.source_project_id??"")),r.Column.fromStrings("source_df_name",t(e=>e.source_df_name)),r.Column.fromStrings("computed_at",t(e=>e.computed_at))];return r.DataFrame.fromColumns(n)}},655(e,t,n){"use strict";n.d(t,{Mj:()=>o,assertSpcEligible:()=>i,classifyStatus:()=>E,computeIterativeBaseline:()=>v,computeSpcMetrics:()=>m,defaultRulesEnabled:()=>p,evaluateNelsonRules:()=>h,getRunMeta:()=>a,kY:()=>d,recoverSpcMetricsFromColumn:()=>C,setRunMeta:()=>s,setSpcStatus:()=>_,uV:()=>y});const o=3.267,r="~spc_metrics_meta";function s(e,t){e.setTag("proteomics.spc_run_meta",JSON.stringify(t))}function a(e){const t=e.getTag("proteomics.spc_run_meta");if(!t)return null;try{return JSON.parse(t)}catch{return null}}function i(e){if("spectronaut-candidates"===e.getTag("proteomics.source"))throw new Error("SPC requires per-sample intensities. Re-import this analysis from the Spectronaut PG report (not the Candidates report) to compute SPC.")}function l(e,t){if(e.isNone(t))return!0;const n=e.get(t);return!("number"!=typeof n||!Number.isNaN(n))}function c(e,t){const n=e.length;if(n<3)return NaN;let o=0,r=0;for(let s=0;s<n;s++)o+=e[s],r+=t[s];const s=o/n,a=r/n;let i=0,l=0,c=0;for(let o=0;o<n;o++){const n=e[o]-s,r=t[o]-a;i+=n*r,l+=n*n,c+=r*r}const u=Math.sqrt(l*c);return 0===u?NaN:i/u}function u(e,t){const n=[];for(const o of t){const t=e.col(o);null!==t&&n.push(t)}return n}function m(e,t,n){const o=u(e,t.group1.columns),r=u(e,t.group2.columns),s=o.concat(r),a=t.group1.columns.length+t.group2.columns.length,i=[],m=e.rowCount;let p=0,d=0,f=0;for(let e=0;e<m;e++){let t=!1;for(const n of s)d++,l(n,e)?p++:(i.push(n.get(e)),t=!0);t&&f++}const g=function(e){if(0===e.length)return NaN;const t=e.slice().sort((e,t)=>e-t),n=t.length,o=Math.floor(n/2);return n%2==0?(t[o-1]+t[o])/2:t[o]}(i),h=0===d?NaN:p/d*100;let y=NaN;if(o.length>=2){let e=0,t=0;for(let n=0;n<o.length;n++)for(let r=n+1;r<o.length;r++){const s=o[n],a=o[r],i=[],u=[];for(let e=0;e<m;e++)l(s,e)||l(a,e)||(i.push(s.get(e)),u.push(a.get(e)));const p=c(i,u);Number.isNaN(p)||(e+=p,t++)}y=0===t?NaN:e/t}return{median_intensity:g,missing_pct:h,control_corr:y,protein_count:f,sample_count:a,computed_at:(new Date).toISOString()}}function p(){return{nelson_1:!0,nelson_2:!1,nelson_3:!1,nelson_4:!1,nelson_5:!0,nelson_6:!1,nelson_7:!1,nelson_8:!1}}function d(){const e={nelson_1:!0,nelson_2:!1,nelson_3:!1,nelson_4:!1,nelson_5:!0,nelson_6:!1,nelson_7:!1,nelson_8:!1};return{median_intensity:{...e},missing_pct:{...e},control_corr:{...e},protein_count:{...e}}}const f={nelson_1:function(e){const t=e.z.length-1;return Math.abs(e.z[t])>3},nelson_2:function(e){if(e.series.length<9)return!1;const t=e.series.slice(-9),n=t.every(t=>t>e.mean),o=t.every(t=>t<e.mean);return n||o},nelson_3:function(e){if(e.series.length<6)return!1;const t=e.series.slice(-6);let n=!0,o=!0;for(let e=1;e<6;e++)t[e]>t[e-1]||(n=!1),t[e]<t[e-1]||(o=!1);return n||o},nelson_4:function(e){if(e.series.length<14)return!1;const t=e.series.slice(-14).map(t=>t>e.mean?1:t<e.mean?-1:0);for(let e=1;e<t.length;e++){if(0===t[e]||0===t[e-1])return!1;if(t[e]===t[e-1])return!1}return!0},nelson_5:function(e){if(e.z.length<3){const t=e.z;if(t.length<2)return!1;const n=t.filter(e=>e>2).length,o=t.filter(e=>e<-2).length;return n>=2||o>=2}const t=e.z.slice(-3),n=t.filter(e=>e>2).length,o=t.filter(e=>e<-2).length;return n>=2||o>=2},nelson_6:function(e){if(e.z.length<5)return!1;const t=e.z.slice(-5),n=t.filter(e=>e>1).length,o=t.filter(e=>e<-1).length;return n>=4||o>=4},nelson_7:function(e){return!(e.z.length<15)&&e.z.slice(-15).every(e=>Math.abs(e)<1)},nelson_8:function(e){return!(e.z.length<8)&&e.z.slice(-8).every(e=>Math.abs(e)>1)}},g=["nelson_1","nelson_2","nelson_3","nelson_4","nelson_5","nelson_6","nelson_7","nelson_8"];function h(e,t,n,o,r){if(0===e.length||!Number.isFinite(n)||0===n)return{status:"pass",rulesTripped:[]};const s=e.map(e=>(e-t)/n),a={series:e,z:s,mean:t,sd:n},i=[];for(const e of g)o[e]&&f[e](a)&&i.push(r?`${e}@${r}`:e);return{status:E(i),rulesTripped:i}}function y(e,t,n,o){const r=[],s=["median_intensity","missing_pct","control_corr","protein_count"];for(const a of s){const s=e[a];if(!Number.isFinite(s))continue;const i=h(t[a].concat([s]),n[a].mean,n[a].sd,o[a],a);for(const e of i.rulesTripped)r.push(e)}return{status:E(r),rulesTripped:r}}function E(e){if(0===e.length)return"pass";for(const t of e)if(t.startsWith("nelson_1@")||"nelson_1"===t)return"out_of_control";return"flagged"}function w(e){const t=e.length;if(0===t)return{mean:NaN,sd:NaN};let n=0;for(const t of e)n+=t;const o=n/t;let r=0;for(const t of e){const e=t-o;r+=e*e}return{mean:o,sd:t>1?Math.sqrt(r/(t-1)):0}}function v(e,t){const n=new Set;for(let t=0;t<e.length;t++)n.add(t);const o=[];let r=NaN,s=NaN;if(!t)return({mean:r,sd:s}=w(e)),{mean:r,sd:s,includedCount:e.length,excludedIndices:[],iterationTrace:o};for(let t=1;t<=2;t++){const a=w(Array.from(n).map(t=>e[t]));if(r=a.mean,s=a.sd,!Number.isFinite(s)||0===s)break;const i=[];for(const t of n){const n=(e[t]-r)/s;Math.abs(n)>3&&i.push(t)}if(0===i.length)break;for(const e of i)n.delete(e);o.push({iter:t,dropped:i});const l=Array.from(n).map(t=>e[t]);({mean:r,sd:s}=w(l))}const a=[];for(let t=0;t<e.length;t++)n.has(t)||a.push(t);return{mean:r,sd:s,includedCount:n.size,excludedIndices:a,iterationTrace:o}}function _(e,t,n){e.setTag("proteomics.spc_metrics",JSON.stringify(t)),e.setTag("proteomics.spc_status",n.status),e.setTag("proteomics.spc_rules_tripped",JSON.stringify(n.rulesTripped));const o=function(e,t){return e.columns.contains(t)&&e.columns.remove(t),e.columns.addNewString(t)}(e,r),s=JSON.stringify({metrics:t,status:n.status,rulesTripped:n.rulesTripped});0!==e.rowCount&&o.set(0,s)}function C(e){if(!e.columns.contains(r))return null;const t=e.col(r);if(!t||0===e.rowCount)return null;const n=t.get(0);if("string"!=typeof n||0===n.length)return null;try{const e=JSON.parse(n);return e&&e.metrics?e.metrics:null}catch{return null}}},623(e,t,n){"use strict";n.d(t,{JO:()=>u,Jn:()=>s,Kf:()=>w,Pd:()=>h,ZF:()=>l,er:()=>m,n0:()=>y,y:()=>c});var o=n(328);const r={Nucleus:["nucleus","nuclear","nucleoplasm","chromatin","nucleolus","nuclear envelope","nuclear membrane","nuclear pore","nuclear speck","cajal body","nuclear body"],Cytoplasm:["cytoplasm","cytosol","cytoplasmic","cytoskeleton","microtubule","actin","intermediate filament","sarcomere","myofibril","z disc","z disk","spindle","centriole","centrosome","cilium","flagellum","stress fiber"],Mitochondria:["mitochondria","mitochondrial","mitochondrion","mitochondrial matrix","mitochondrial membrane","mitochondrial inner membrane","mitochondrial outer membrane","mitochondrial intermembrane space"],ER:["endoplasmic reticulum","sarcoplasmic reticulum","rough endoplasmic reticulum","smooth endoplasmic reticulum","er-golgi intermediate compartment","ergic"],Golgi:["golgi","trans-golgi","golgi apparatus","golgi membrane","cis-golgi","trans-golgi network","tgn"],"Plasma Membrane":["plasma membrane","cell membrane","cell surface","tight junction","gap junction","adherens junction","desmosome","focal adhesion","cell junction","synapse","postsynaptic","presynaptic","neuromuscular junction"],Lysosome:["lysosome","lysosomal","vacuole","lysosomal membrane","autophagosome","phagosome"],Peroxisome:["peroxisome","peroxisomal","glyoxysome"],Ribosome:["ribosome","ribosomal","ribosomal protein","polysome"],Extracellular:["extracellular","secreted","extracellular space","extracellular matrix","basement membrane","basal lamina","collagen","ecm"],Vesicles:["vesicle","endosome","transport vesicle","secretory vesicle","early endosome","late endosome","recycling endosome","clathrin-coated vesicle","coated vesicle"]},s={Nucleus:4278190080|parseInt("FF6B6B",16),Cytoplasm:4278190080|parseInt("ECDC44",16),Mitochondria:4278190080|parseInt("45B7D1",16),ER:4278190080|parseInt("96CEB4",16),Golgi:4278190080|parseInt("FAAFFE",16),"Plasma Membrane":4278190080|parseInt("DDA0DD",16),Lysosome:4278190080|parseInt("F39C12",16),Peroxisome:4278190080|parseInt("E17055",16),Ribosome:4278190080|parseInt("A29BFE",16),Extracellular:4278190080|parseInt("FD79A8",16),Vesicles:4278190080|parseInt("FDCB6E",16),Unknown:4278190080|parseInt("CCCCCC",16)};function a(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i(e){if(!e)return null;const t=e.toLowerCase();let n=null,o=1/0;for(const e of Object.keys(r))for(const s of r[e]){const r=new RegExp("\\b"+a(s)+"\\b","i").exec(t);r&&r.index<o&&(o=r.index,n=e)}return n}function l(e,t){const n=null==t?"":t;let o=i(null==e?"":e);return o||(o=i(n),o||"Unknown")}function c(e){const t=new Map,n=new Map,o=new Map,r=e.trim().split("\n");for(let e=1;e<r.length;e++){const s=r[e];if(!s)continue;const a=s.split("\t"),i=(a[0]??"").trim();if(!i)continue;const c=a[1]??"",u=a[2]??"",m="reviewed"===(a[3]??"").toLowerCase(),p=(a[4]??"").trim(),d=l(c,u);t.has(i)?m&&"Unknown"!==d?(t.set(i,d),o.set(i,!0)):"Unknown"===t.get(i)&&"Unknown"!==d&&(t.set(i,d),o.set(i,m)):(t.set(i,d),o.set(i,m)),!p||n.has(i)&&!m||n.set(i,p)}return{locByAcc:t,geneByAcc:n,reviewedByAcc:o}}const u={hsapiens:9606,mmusculus:10090,rnorvegicus:10116,scerevisiae:4932,ecoli:562,drerio:7955,dmelanogaster:7227,athaliana:3702,celegans:6239},m="proteomics-subcell-loc",p="13-04-1",d="__schema_v",f=new Set([...Object.keys(r),"Unknown"]);function g(e,t){const n=[];for(let o=0;o<e.length;o+=t)n.push(e.slice(o,o+t));return n}async function h(e,t,n){const o=new Array(e.length);let r=0;const s=Math.min(Math.max(1,t),e.length||1),a=[];for(let t=0;t<s;t++)a.push((async()=>{for(;;){const t=r++;if(t>=e.length)return;o[t]=await n(e[t],t)}})());return await Promise.all(a),o}async function y(e,t,n){const r=[...new Set(e.filter(e=>e&&e.length>0))],s=await async function(){try{const e=await o.dapi.userDataStorage.get(m)??{};return e[d]!==p?{[d]:p}:e}catch{return{[d]:p}}}(),a=new Map,i=[];for(const e of r){const t=s[e];void 0!==t&&f.has(t)?a.set(e,t):i.push(e)}const y=new Map,E={},w=function(e){const t=e?u[e]:void 0;return t?` AND (taxonomy_id:${t})`:""}(t),v=async()=>{if(0!==Object.keys(E).length)try{await o.dapi.userDataStorage.put(m,{...s,...E,[d]:p})}catch(e){console.warn(`Subcellular-location cache write failed: ${e?.message??e}`)}},_=setInterval(()=>{v().catch(()=>{})},5e3);try{const e=g(i,100),t=e.length;let s=0;await h(e,6,async e=>{const r=e.map(e=>`accession:${e}`).join(" OR "),i=`https://rest.uniprot.org/uniprotkb/stream?query=(${encodeURIComponent(r)})&fields=accession,cc_subcellular_location,go_c,reviewed,gene_primary&format=tsv`;try{const e=await o.dapi.fetchProxy(i);if(!e.ok)return void console.warn(`UniProt stream returned status ${e.status}; continuing`);const{locByAcc:t,geneByAcc:n}=c(await e.text());for(const[e,n]of t)a.set(e,n),E[e]=n;for(const[e,t]of n)y.set(e,t)}catch(e){console.warn(`UniProt stream batch failed: ${e?.message??e}; continuing`)}s++,n?.(s,t,"fetch-acc")});const u=new Map;for(const e of i){const t=a.get(e)??"Unknown",n=y.get(e);"Unknown"===t&&n&&(u.has(n)||u.set(n,[]),u.get(n).push(e))}const m=g([...u.keys()],20),p=m.length;let d=0;await h(m,6,async e=>{const t=e.map(e=>`gene_exact:${e}`).join(" OR "),r=`https://rest.uniprot.org/uniprotkb/stream?query=(${encodeURIComponent(t)}) AND (reviewed:true)${encodeURIComponent(w)}&fields=accession,gene_primary,cc_subcellular_location,go_c&format=tsv`;try{const e=await o.dapi.fetchProxy(r);if(!e.ok)return void console.warn(`UniProt gene fallback returned status ${e.status}; continuing`);const t=(await e.text()).trim().split("\n");for(let e=1;e<t.length;e++){const n=t[e].split("\t"),o=(n[1]??"").trim(),r=l(n[2]??"",n[3]??"");if(o&&"Unknown"!==r)for(const e of u.get(o)??[])a.set(e,r),E[e]=r}}catch(e){console.warn(`UniProt gene fallback batch failed: ${e?.message??e}; continuing`)}d++,n?.(d,p,"fetch-gene")});for(const e of r)a.has(e)||a.set(e,"Unknown"),void 0===E[e]&&(E[e]=a.get(e))}finally{clearInterval(_),await v()}const C=new Map;for(const e of r)C.set(e,a.get(e)??"Unknown");return C}const E=new Map;async function w(e){if(E.has(e))return E.get(e)??null;const t=`https://rest.uniprot.org/uniprotkb/${encodeURIComponent(e)}.json?fields=accession,protein_name,gene_names,organism_name,cc_function,go`;try{const n=await o.dapi.fetchProxy(t);if(!n.ok)return console.warn(`UniProt fetch for ${e} returned status ${n.status}`),E.set(e,null),null;const r=await n.json();return E.set(e,r),r}catch(t){return console.warn(`UniProt fetch for ${e} failed:`,t?.message??t),null}}},110(e,t,n){"use strict";n.d(t,{_package:()=>J,dockComparisonFilterIfMultiContrast:()=>oe,openCandidatesAnalysisView:()=>re,sniffIsPrecursor:()=>ee});var o=n(328),r=n(389),s=n(82),a=n(713),i=n(312),l=n(53),c=n(86),u=n(119),m=n(641),p=n(304);const d=["primary protein id","pg.proteingroups","protein id","uniprot","accession"];function f(e,t=0){if(0===e.rowCount||t<0||t>=e.rowCount)return;const n=(0,p.k)(e,m.iu.PROTEIN_ID,d);n&&(e.currentCell=e.cell(t,n.name),o.shell.windows.showContextPanel=!0,async function(){const e=["Proteomics","UniProt"];for(let t=0;t<12;t++){await new Promise(e=>setTimeout(e,250));try{const t=document.querySelector('[d4-title="semantic meta.Proteomics-ProteinId"]');if(!t)continue;let n=!0;for(const o of e){const e=Array.from(t.querySelectorAll(".d4-accordion-pane-header")).find(e=>e.textContent?.trim()===o);e?e.classList.contains("expanded")||(e.click(),n=!1):n=!1}if(n)return}catch{}}}())}var g=n(954),h=n(117);function y(){s.Utils.openFile({accept:".csv,.tsv,.txt",open:e=>{const t=new FileReader;t.onload=()=>{try{const n=t.result,a=(0,g.T6)(n);!function(e,t){const n=(0,g.q2)(e),a=(0,g.YL)(e),i=(0,g.WI)(e),l=r.input.column("Protein ID",{table:e,filter:e=>e.type===s.COLUMN_TYPE.STRING,value:n??void 0}),c=r.input.column("Gene Name (optional)",{table:e,filter:e=>e.type===s.COLUMN_TYPE.STRING,value:a??void 0,nullable:!0}),u=e.columns.toList().filter(e=>e.type===s.COLUMN_TYPE.FLOAT||e.type===s.COLUMN_TYPE.INT||e.type===s.COLUMN_TYPE.BIG_INT).map(e=>e.name),p=r.input.columns("Intensity Columns",{table:e,available:u,value:i.map(t=>e.col(t)).filter(e=>null!=e)}),d=(0,g.eY)(e,i),y=r.input.bool("Log2 Transform",{value:!d.isLog2}),E=r.divText(d.message);E.style.cssText="font-style:italic;color:#888;margin-bottom:8px;font-size:12px;";const w=document.createElement("div");function v(){const t=[],n=l.value;n&&t.push(n.name);const o=c.value;o&&t.push(o.name);const a=(p.value??[]).map(e=>e.name);if(t.push(...a),0!==t.length)try{const n=s.BitSet.create(e.rowCount,e=>e<5),o=e.clone(n,t),a=s.Viewer.grid(o);w.innerHTML="";const i=r.divText(`Preview: ${t.length} columns, 5 rows`);i.style.cssText="font-size:11px;color:#888;padding:2px 4px;",a.root.style.cssText="width:100%;height:180px;",w.appendChild(i),w.appendChild(a.root)}catch{w.innerHTML='<div style="padding:8px;color:#888">Unable to generate preview</div>'}else w.innerHTML='<div style="padding:8px;color:#888">Select columns to preview</div>'}w.style.cssText="border:1px solid #ddd;margin-top:8px;width:100%;",l.onChanged.subscribe(()=>v()),c.onChanged.subscribe(()=>v()),p.onChanged.subscribe(()=>{(function(){const t=(p.value??[]).map(e=>e.name);if(0===t.length)return void(E.textContent="Select intensity columns");const n=(0,g.eY)(e,t);E.textContent=n.message,y.value=!n.isLog2})(),v()}),v(),r.dialog("Import Generic Matrix").add(l).add(c).add(p).add(y).add(r.div([E])).add(w).onOK(async()=>{const n=l.value;if(!n)return void o.shell.warning("Please select a Protein ID column");const r=(p.value??[]).map(e=>e.name);if(0===r.length)return void o.shell.warning("Please select at least one intensity column");n.semType=m.iu.PROTEIN_ID;const s=c.value;s&&(s.semType=m.iu.GENE_SYMBOL),y.value?(0,g.Kh)(e,r):(0,g.l3)(e,r),(0,g.wK)(e,n.name,"Primary Protein ID",m.iu.PROTEIN_ID),s&&(0,g.wK)(e,s.name,"Primary Gene Name",m.iu.GENE_SYMBOL),e.setTag("proteomics.source","generic"),await(0,h.rv)(e),e.name=t.replace(/\.[^.]+$/,""),o.shell.addTableView(e),o.shell.info(`Imported ${e.rowCount} proteins from ${t}`),f(e)}).show()}(s.DataFrame.fromCsv(n,{delimiter:a}),e.name)}catch(e){o.shell.error("Failed to parse file: "+e.message)}},t.readAsText(e)}})}var E=n(252),w=n(935),v=n(655),_=n(883),C=n(350),b=n(871),T=n(989),P=n(47),S=n(829),N=n(70),A=n(623);async function x(e,t){const n=t?.topN??50,o=t?.labelCol??"Gene Name";if("true"!==e.getTag("proteomics.de_complete"))throw new Error("Differential expression must be run first");const r=(0,E.f)(e);if(!r)throw new Error("Experimental groups must be annotated first");const a=e.col("adj.p-value");if(!a)throw new Error("adj.p-value column not found");const i=[];for(let t=0;t<e.rowCount;t++)a.isNone(t)||i.push({idx:t,pVal:a.get(t)});i.sort((e,t)=>e.pVal-t.pVal);const l=new Set;for(let e=0;e<Math.min(n,i.length);e++)l.add(i[e].idx);const c=s.BitSet.create(e.rowCount);for(const e of l)c.set(e,!0);const u=e.clone(c),d=[...r.group1.columns,...r.group2.columns],f=[];for(const t of d){const n=`_zscore_${t}`;f.push(n);const o=e.col(t);if(!o)continue;const r=o.getRawData();let a=0,i=0,l=0;for(let t=0;t<e.rowCount;t++){const e=r[t];e!==s.FLOAT_NULL&&(a+=e,i+=e*e,l++)}const c=l>0?a/l:0,m=l>1?(i-a*a/l)/(l-1):0,p=Math.sqrt(m),d=u.col(t);if(!d)continue;const g=d.getRawData();u.columns.addNewFloat(n).init(e=>{return g[e]===s.FLOAT_NULL?s.FLOAT_NULL:(t=g[e],(n=p)>0?(t-c)/n:0);var t,n})}const g=u.plot.grid();for(let e=0;e<g.columns.length;e++){const t=g.columns.byIndex(e);t&&(t.visible=!1)}const h=(0,p.k)(u,m.iu.GENE_SYMBOL,[o.toLowerCase(),"gene symbol"])??(0,p.k)(u,m.iu.PROTEIN_ID,["protein id","majority protein id","accession"]);if(h){const e=g.columns.byName(h.name);e&&(e.visible=!0)}const y=r.group1.columns.map(e=>`_zscore_${e}`),w=r.group2.columns.map(e=>`_zscore_${e}`);for(const e of[...y,...w]){const t=g.columns.byName(e);t&&(t.visible=!0)}let v=!1;const _=s.TaskBarProgressIndicator.create("Calculating distance matrix...");try{const e=s.Func.find({package:"Dendrogram",name:"hierarchicalClustering"})[0];if(!e)throw new Error("Dendrogram package not installed (hierarchicalClustering not found)");if(4!==e.inputs.length)throw new Error(`Dendrogram.hierarchicalClustering signature changed (expected 4 inputs, got ${e.inputs.length})`);await e.apply({df:g,colNameList:f,distance:"euclidean",linkage:"complete"}),v=!0}catch(e){console.warn(`Dendrogram clustering unavailable, falling back to significance-based row ordering: ${e?.message??e}`)}finally{_.close()}if(!v){const e=u.col("adj.p-value")?"adj.p-value":u.col("adj.p.value")?"adj.p.value":null;e&&g.sort([e])}return g.props.isHeatmap=!0,g.props.isGrid=!1,t?.title&&g.setOptions({title:t.title}),g}const D=["#2196F3","#FF5722"];function L(e,t,n=64){const o=e.length;if(o<3)return null;let r=0,s=0;for(let n=0;n<o;n++)r+=e[n],s+=t[n];r/=o,s/=o;let a=0,i=0,l=0;for(let n=0;n<o;n++){const o=e[n]-r,c=t[n]-s;a+=o*o,i+=o*c,l+=c*c}a/=o-1,i/=o-1,l/=o-1;const c=a+l,u=a*l-i*i,m=Math.sqrt(Math.max(c*c/4-u,0)),p=c/2+m,d=c/2-m;if(p<=0||d<=0)return null;let f;f=Math.abs(i)>1e-12?Math.atan2(p-a,i):a>=l?0:Math.PI/2;const g=Math.sqrt(5.991*p),h=Math.sqrt(5.991*d),y=[],E=Math.cos(f),w=Math.sin(f);for(let e=0;e<n;e++){const t=2*Math.PI*e/n,o=g*Math.cos(t),a=h*Math.sin(t),i=r+E*o-w*a,l=s+w*o+E*a;y.push([i,l])}return y}function F(e,t,n,o){const{pcaDf:r,varianceExplained:a}=function(e,t,n,o=2){const r=t.length,a=e.rowCount,i=[],l=new Array(a).fill(0),c=new Array(a).fill(0);for(const n of t){const t=e.col(n);if(t)for(let e=0;e<a;e++)t.isNone(e)||(l[e]+=t.get(e),c[e]++)}for(let e=0;e<a;e++)l[e]=c[e]>0?l[e]/c[e]:0;for(const n of t){const t=e.col(n),o=new Array(a);for(let e=0;e<a;e++)!t||t.isNone(e)?o[e]=l[e]:o[e]=t.get(e);i.push(o)}const u=new Array(a).fill(0);for(let e=0;e<a;e++){for(let t=0;t<r;t++)u[e]+=i[t][e];u[e]/=r}for(let e=0;e<r;e++)for(let t=0;t<a;t++)i[e][t]-=u[t];const m=function(e,t,n){const o=[];for(let r=0;r<n;r++){const n=new Array(t);for(let o=0;o<t;o++)n[o]=e[o][r];o.push(n)}return o}(i,r,a),p=function(e,t,n,o,r){const s=[];for(let a=0;a<n;a++){const n=new Array(r).fill(0);for(let s=0;s<o;s++){const o=e[a][s];for(let e=0;e<r;e++)n[e]+=o*t[s][e]}s.push(n)}return s}(i,m,r,a,r),d=a>1?a-1:1;for(let e=0;e<r;e++)for(let t=0;t<r;t++)p[e][t]/=d;const{eigenvalues:f,eigenvectors:g}=function(e,t){const n=e.map(e=>[...e]),o=[];for(let e=0;e<t;e++){const n=new Array(t).fill(0);n[e]=1,o.push(n)}let r=!1;for(let e=0;e<100;e++){let e=0,s=0,a=1;for(let o=0;o<t;o++)for(let r=o+1;r<t;r++)Math.abs(n[o][r])>e&&(e=Math.abs(n[o][r]),s=o,a=r);if(e<1e-10){r=!0;break}const i=(n[a][a]-n[s][s])/(2*n[s][a]),l=Math.sign(i)/(Math.abs(i)+Math.sqrt(i*i+1)),c=1/Math.sqrt(l*l+1),u=l*c,m=n[s][s],p=n[a][a],d=n[s][a];n[s][s]=c*c*m-2*u*c*d+u*u*p,n[a][a]=u*u*m+2*u*c*d+c*c*p,n[s][a]=0,n[a][s]=0;for(let e=0;e<t;e++)if(e!==s&&e!==a){const t=n[e][s],o=n[e][a];n[e][s]=c*t-u*o,n[s][e]=n[e][s],n[e][a]=u*t+c*o,n[a][e]=n[e][a]}for(let e=0;e<t;e++){const t=o[e][s],n=o[e][a];o[e][s]=c*t-u*n,o[e][a]=u*t+c*n}}r||console.warn(`PCA Jacobi did not converge in 100 iterations (n=${t}); results may be approximate`);const s=new Array(t);for(let e=0;e<t;e++)s[e]=n[e][e];const a=Array.from({length:t},(e,t)=>t);a.sort((e,t)=>s[t]-s[e]);const i=a.map(e=>s[e]),l=[];for(let e=0;e<t;e++){const n=new Array(t);for(let r=0;r<t;r++)n[r]=o[e][a[r]];l.push(n)}return{eigenvalues:i,eigenvectors:l}}(p,r),h=[];for(let e=0;e<r;e++){const t=[];for(let n=0;n<Math.min(o,r);n++){const o=f[n]>0?Math.sqrt(f[n]):0;t.push(g[e][n]*o)}h.push(t)}const y=f.reduce((e,t)=>e+Math.max(t,0),0),E=[];for(let e=0;e<Math.min(o,r);e++){const t=y>0?Math.max(f[e],0)/y*100:0;E.push(Math.round(10*t)/10)}const w=E.length>0&&isFinite(E[0])?E[0]:0,v=r>=2?`PC1 (${w}%)`:"PC1",_=E.length>=2&&isFinite(E[1])?E[1]:0,C=o>=2&&E.length>=2&&r>=2?`PC2 (${_}%)`:"PC2",b=[s.Column.fromStrings("SampleName",t),s.Column.fromFloat32Array(v,new Float32Array(h.map(e=>e[0])))];if(o>=2){const e=s.Column.fromFloat32Array(C,new Float32Array(h.map(e=>e.length>1?e[1]:0)));b.push(e)}const T=t.map(e=>n.group1.columns.includes(e)?n.group1.name:n.group2.columns.includes(e)?n.group2.name:"Unknown"),P=s.Column.fromStrings("Group",T);b.push(P);const S=s.DataFrame.fromColumns(b);return S.name="PCA",{pcaDf:S,varianceExplained:E}}(e,t,n),i=r.columns.toList().find(e=>e.name.startsWith("PC1"))?.name,l=r.columns.toList().find(e=>e.name.startsWith("PC2"))?.name;if(!i||!l)throw new Error("PCA did not produce PC1/PC2 columns — too few samples?");const c=r.plot.scatter({x:i,y:l,color:"Group"});c.props.labelColumnNames=["SampleName"],c.props.displayLabels="Always";try{const e=r.col(i),t=r.col(l),o=r.col("Group"),s=[n.group1.name,n.group2.name];for(let n=0;n<s.length;n++){const a=s[n],u=[],m=[];for(let n=0;n<r.rowCount;n++)o.get(n)===a&&(u.push(e.get(n)),m.push(t.get(n)));const p=L(u,m);if(p){const e=D[n%D.length],t={type:"area",area:p,fillColor:e,opacity:.15,outlineColor:e,outlineWidth:1,x:i,y:l};c.meta.annotationRegions?.add(t)}}}catch(e){console.warn("PCA: could not add confidence ellipses:",e?.message??e)}return o&&c.setOptions({title:o}),{viewer:c,pcaDf:r}}var I=n(715);const M=["M","A","MA_trend","CV_group1","meanInt_group1","CV_group2","meanInt_group2"];function O(e){const t=s.TaskBarProgressIndicator.create("Creating QC dashboard...");try{const t=(0,E.f)(e);if(!t)return void o.shell.warning("Annotate experimental groups first (Proteomics | Annotate Experiment)");for(const t of M)e.columns.contains(t)&&e.columns.remove(t);const n=(0,I.Hc)(e);if(0===n.length)return void o.shell.warning("No log2 intensity columns found");(0,I.iQ)(e,t),(0,I.Pq)(e),(0,I.JZ)(e,t.group1.columns,"CV_group1","meanInt_group1"),(0,I.JZ)(e,t.group2.columns,"CV_group2","meanInt_group2");const r=o.shell.tv;if(!r)return void o.shell.warning("No table view open");const a={xColumnName:"A",yColumnName:"M",title:"MA Plot",markerDefaultSize:2};if("true"===e.getTag("proteomics.de_complete"))try{const t=(0,N.EO)(e,m.M5,m.Dx);a.colorColumnName=t}catch(e){}const i=r.addViewer(s.VIEWER.SCATTER_PLOT,a),l="${M} = 0";e.meta.formulaLines.items=e.meta.formulaLines.items.filter(e=>e.formula!==l),e.meta.formulaLines.addLine({formula:l,color:"#888888",width:1,visible:!0});const c=r.addViewer(s.VIEWER.SCATTER_PLOT,{xColumnName:"A",yColumnName:"MA_trend",title:"MA Trend",markerDefaultSize:1}),u=r.addViewer(s.VIEWER.SCATTER_PLOT,{xColumnName:"meanInt_group1",yColumnName:"CV_group1",title:"CV Plot",markerDefaultSize:2}),p=r.addViewer(s.VIEWER.CORR_PLOT,{xColumnNames:n,yColumnNames:n,title:"Sample Correlation"}),d=(0,I.ho)(e,n),f=s.Viewer.grid(d);f.props.allowColSelection=!1;const g=(0,I.rA)(e,n,t),h=s.Viewer.barChart(g,{splitColumnName:"Sample",valueColumnName:"MissingPct",stackColumnName:"Group"}),y=(0,I.j4)(e,n),w=s.Viewer.boxPlot(y,{valueColumnName:"Intensity",categoryColumnName:"Sample"}),v=r.dockManager,_=v.dock(i,s.DOCK_TYPE.RIGHT,null,"MA Plot",.75);v.dock(c,s.DOCK_TYPE.FILL,_,"MA Trend"),v.dock(u,s.DOCK_TYPE.FILL,_,"CV Plot");const C=v.dock(p,s.DOCK_TYPE.DOWN,_,"Sample Correlation",.5);v.dock(w,s.DOCK_TYPE.FILL,C,"Intensity Distributions"),v.dock(h,s.DOCK_TYPE.FILL,C,"Missing % per Sample"),v.dock(f,s.DOCK_TYPE.FILL,C,"Missing Values");const b=e=>{try{const t=v.findNode(e.root);t?.parent&&t.parent.container.setActiveChild(t.container)}catch{}};b(i),b(p)}finally{t.close()}}var R=n(589),G=n(644),k=n(498),$=n(771);function B(e){if(null==e)return"unknown date";try{if(e instanceof Date)return Number.isNaN(e.getTime())?"unknown date":e.toISOString().slice(0,10);const t=new Date(e);return Number.isNaN(t.getTime())?"unknown date":t.toISOString().slice(0,10)}catch{return"unknown date"}}function U(e,t){const n=r.divText(e);n.style.fontWeight="600",n.style.fontSize="12px",n.style.color="#666";const o=r.divText(t);o.style.marginBottom="8px";const s=r.div([n,o]);return s.style.marginBottom="6px",s}var j=n(807),V=n(637);var q=n(649),Y=n(230),z=n(897);const H=["Import","Annotate Experiment...","Analyze","Visualize","Share"];var Q=function(e,t,n,o){var r,s=arguments.length,a=s<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,o);else for(var i=e.length-1;i>=0;i--)(r=e[i])&&(a=(s<3?r(a):s>3?r(t,n,a):r(t,n))||a);return s>3&&a&&Object.defineProperty(t,n,a),a},W=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},K=function(e,t){return function(n,o){t(n,o,e)}};const J=new s.Package;function Z(e,t){return"spectronaut-candidates"!==e.getTag("proteomics.source")||(o.shell.warning(`${t} needs per-sample intensities, but this table is a Spectronaut Candidates report (one row per protein per comparison — pre-computed DE only). Import the matching Spectronaut Report (Proteomics | Import | Spectronaut Report) to enable per-sample analyses, or stick to Volcano / Enrichment / UniProt panel on this one.`),!1)}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","treeBrowser","polyfill"].forEach(e=>{o.decorators[e]||(o.decorators[e]=function(e){return function(e,t,n){}})});const X=["EG.ModifiedPeptide","FG.Charge","PEP.StrippedSequence"];async function ee(e){const t=e.stream().pipeThrough(new TextDecoderStream("utf-8")).getReader();try{let e="";const n=1048576;for(;e.indexOf("\n")<0&&e.length<n;){const{value:n,done:o}=await t.read();if(o)break;e+=n}const o=e.indexOf("\n");let r=o>=0?e.slice(0,o):e;return r.endsWith("\r")&&(r=r.slice(0,-1)),X.some(e=>r.includes(e))}finally{await t.cancel()}}let te=[];function ne(e){if((0,E.Di)(e))return;const t=(0,w.Vr)(e);t&&(0,E.Np)(e,t)}function oe(e,t){const n=c.g.reduce((e,n)=>e??t.col(n),null);if(!n)return!1;const o=new Set;for(let e=0;e<t.rowCount;e++){const t=n.get(e);"string"==typeof t&&t.length>0&&o.add(t)}if(o.size<=1)return!1;const r=(0,p.k)(t,m.iu.DISPLAY_NAME,["display name"]),i=(0,p.k)(t,m.iu.SOURCE_ID,["source id"]),l=(0,p.k)(t,m.iu.PROTEIN_ID,["primary protein id","protein id","uniprot","accession"]),u=[n.name];r&&u.push(r.name),i&&u.push(i.name),!r&&l&&u.push(l.name);const d=s.Viewer.filters(t,{columnNames:u,showBoolCombinedFilter:!1,showHeader:!0,showSearchBox:!0});e.dockManager.dock(d,s.DOCK_TYPE.RIGHT,null,"Filters",.3);for(const e of te)e.unsubscribe();te=[];const f=s.BitSet.create(t.rowCount);f.copyFrom(t.filter);let g=!1;return te.push(t.onFilterChanged.pipe((0,a.debounceTime)(100)).subscribe(()=>{if(g)return;const n=[];for(let e=0;e<t.rowCount;e++)t.filter.get(e)&&n.push(e);if(n.length===t.rowCount)return void f.copyFrom(t.filter);g=!0;try{t.filter.copyFrom(f)}finally{g=!1}t.selection.setAll(!1,!1);for(const e of n)t.selection.set(e,!0,!1);t.selection.fireChanged();const o=(()=>{for(const t of e.viewers)if(t.type===s.VIEWER.SCATTER_PLOT&&"negLog10P"===t.props.yColumnName)return t;return null})();o&&(0,N.XC)(t,o,(0,N.m2)(t),n)})),!0}function re(e){const t=o.shell.addTableView(e);o.shell.info(`Imported ${e.rowCount} candidates from Spectronaut`);try{t.addViewer((0,N.gO)(e))}catch(e){o.shell.warning(`Imported, but could not auto-open the volcano: ${e?.message??e}. Open it via Proteomics | Visualize | Volcano Plot.`)}return oe(t,e),f(e),t}class se{static async initProteomics(){}static async buildProteomicsTopMenu(){const e={importSpectronautCandidates:()=>se.importSpectronautCandidates(),importSpectronaut:()=>se.importSpectronaut(),importMaxQuant:()=>se.importMaxQuant(),importFragPipe:()=>se.importFragPipe(),importGenericMatrix:()=>se.importGenericMatrix(),annotateExperiment:()=>se.annotateExperiment(),setLog2Scale:()=>se.setLog2Scale(),normalize:()=>se.normalizeProteomics(),impute:()=>se.imputeMissingValues(),differentialExpression:()=>se.differentialExpression(),enrichmentAnalysis:()=>se.enrichmentAnalysis(),exportEnrichmentInputs:()=>se.exportEnrichmentInputs(),computeSpcStatus:()=>se.computeSpcStatus(),showVolcanoPlot:()=>se.showVolcanoPlot(),showHeatmap:()=>se.showHeatmap(),showPcaPlot:()=>se.showPcaPlot(),showGroupMeanCorrelation:()=>se.showGroupMeanCorrelation(),showQcDashboard:()=>se.showQcDashboard(),showSpcDashboard:()=>se.showSpcDashboard(),enrichmentCharts:()=>se.enrichmentCharts(),showAllVisualizations:()=>se.showAllVisualizations(),shareAnalysisForReview:()=>se.shareAnalysisForReview()},t=new WeakSet,n=n=>{n?.type!==s.VIEW_TYPE.TABLE_VIEW||t.has(n)||setTimeout(()=>{if(!t.has(n))try{(function(e,t){if(!(n=e.dataFrame)||!n.getTag("proteomics.source"))return!1;var n;const o=e.ribbonMenu.group("Proteomics");for(const e of H)try{o.remove(e)}catch{}const r={isEnabled:()=>function(e){return e&&"spectronaut-candidates"===e.getTag("proteomics.source")?"Not applicable to a Spectronaut Candidates file — it already carries computed differential expression and has no per-sample intensities. Use Volcano Plot, Enrichment Analysis or the UniProt panel, or import the matching Spectronaut Report for sample-level analyses.":null}(e.dataFrame)},s=o.group("Import");s.item("Spectronaut Candidates...",t.importSpectronautCandidates),s.item("Spectronaut Report...",t.importSpectronaut),s.item("MaxQuant...",t.importMaxQuant),s.item("FragPipe...",t.importFragPipe),s.item("Generic Matrix...",t.importGenericMatrix),o.item("Annotate Experiment...",t.annotateExperiment,null,r);const a=o.group("Analyze");a.item("Set Log2 Scale...",t.setLog2Scale,null,r),a.item("Normalize...",t.normalize,null,r),a.item("Impute Missing Values...",t.impute,null,r),a.item("Differential Expression...",t.differentialExpression,null,r),a.item("Enrichment Analysis...",t.enrichmentAnalysis),a.item("Export Enrichment Inputs...",t.exportEnrichmentInputs),a.item("Compute SPC Status",t.computeSpcStatus,null,r);const i=o.group("Visualize");return i.item("Volcano Plot...",t.showVolcanoPlot),i.item("Heatmap...",t.showHeatmap,null,r),i.item("PCA...",t.showPcaPlot,null,r),i.item("Group-Mean Correlation...",t.showGroupMeanCorrelation,null,r),i.item("QC Dashboard...",t.showQcDashboard,null,r),i.item("SPC Dashboard...",t.showSpcDashboard),i.item("Enrichment Charts...",t.enrichmentCharts),i.item("Show All Visualizations...",t.showAllVisualizations,null,r),o.group("Share").item("Share Analysis for Review...",t.shareAnalysisForReview),!0})(n,e)&&t.add(n)}catch{}},50)};try{for(const e of o.shell.views)n(e)}catch{}o.events.onViewAdded.subscribe(n),o.events.onCurrentViewChanged.subscribe(()=>n(o.shell.v))}static async importSpectronautCandidates(){s.Utils.openFile({accept:".tsv,.txt,.csv",open:async e=>{try{const t=await e.text(),n=await(0,c.R)(t);n.name=e.name.replace(/\.[^.]+$/,""),ne(n),re(n)}catch(e){o.shell.error(`Failed to import Spectronaut Candidates file: ${e?.message??e}`)}}})}static async importSpectronaut(){s.Utils.openFile({accept:".tsv,.txt,.csv",open:async e=>{try{const t=await ee(e)?await(0,l.A)(e):await(0,l.parseSpectronautText)(await e.text());t.name=e.name.replace(/\.[^.]+$/,""),ne(t),o.shell.addTableView(t),o.shell.info(`Imported ${t.rowCount} protein groups from Spectronaut`),f(t)}catch(e){o.shell.error(`Failed to import Spectronaut file: ${e?.message??e}`),o.shell.warning("If this is a very large precursor-level Spectronaut report that fails to stream in-browser, pre-aggregate it to the importable protein-group shape with the bundled duckdb fallback: tools/spectronaut-aggregate.sh <input.tsv>, then re-import the resulting file. See files/demo/README.md for usage.")}}})}static async importMaxQuant(){s.Utils.openFile({accept:".txt,.tsv",open:async e=>{try{const t=await e.text(),n=await(0,i.E)(t);n.name=e.name.replace(/\.[^.]+$/,""),ne(n),o.shell.addTableView(n),o.shell.info(`Imported ${n.rowCount} protein groups`),f(n)}catch(e){o.shell.error(`Failed to import MaxQuant file: ${e?.message??e}`)}}})}static async importFragPipe(){s.Utils.openFile({accept:".tsv,.txt",open:async e=>{try{const t=await e.text(),n=await(0,u.p)(t);n.name=e.name.replace(/\.[^.]+$/,""),ne(n),o.shell.addTableView(n),o.shell.info(`Imported ${n.rowCount} protein groups from FragPipe`),f(n)}catch(e){o.shell.error(`Failed to import FragPipe file: ${e?.message??e}`)}}})}static async importGenericMatrix(){y()}static async annotateExperiment(){const e=o.shell.tv?.dataFrame;e?Z(e,"Annotate Experiment")&&(0,E.XX)(e):o.shell.warning("No table open")}static async setLog2Scale(){const e=o.shell.tv?.dataFrame;e?Z(e,"Set Log2 Scale")&&(0,b.Kb)(e):o.shell.warning("No table open")}static async normalizeProteomics(){const e=o.shell.tv?.dataFrame;e?Z(e,"Normalize")&&(0,C.v5)(e):o.shell.warning("No table open")}static async imputeMissingValues(){const e=o.shell.tv?.dataFrame;e?Z(e,"Impute Missing Values")&&(0,P.UN)(e):o.shell.warning("No table open")}static async differentialExpression(){const e=o.shell.tv,t=e?.dataFrame;e&&t?Z(t,"Differential Expression")&&(0,S.B9)(t,()=>{const n=(0,N.gO)(t);e.addViewer(n)}):o.shell.warning("No table open")}static async computeSpcStatus(){const e=o.shell.tv,t=e?.dataFrame;if(!e||!t)return void o.shell.warning("Open an analyzed file first, then run Compute SPC Status.");if("spectronaut-candidates"===t.getTag("proteomics.source"))return void o.shell.warning("SPC requires per-sample intensities. Re-import this analysis from the Spectronaut PG report (not the Candidates report) to compute SPC.");const n=(0,v.getRunMeta)(t);if(!n||!n.instrument_id||!n.acquisition_datetime)return void o.shell.warning("Open Annotate Experiment to set instrument + acquisition datetime.");const r=(0,E.f)(t);if(!r)return void o.shell.warning("Annotate experimental groups first (Proteomics → Annotate Experiment) — SPC needs Group 1 to compute control-replicate correlation.");r.group1.columns.length<2&&o.shell.info("Group 1 has fewer than 2 samples — control-replicate correlation can't be computed. The other three metrics will still be recorded.");const a=s.TaskBarProgressIndicator.create("Computing SPC status...");try{const e=(0,v.computeSpcMetrics)(t,r,n),s=await(0,_.loadBaseline)(n.instrument_id),a=await(0,_.loadRuns)(n.instrument_id),i=a.find(e=>e.acquisition_datetime===n.acquisition_datetime),l=i?.status??null;let c;if(null===s)c={status:"pass",rulesTripped:[]},o.shell.info(`No baseline locked for ${n.instrument_id} yet — recorded as pass. Define a baseline once at least 4 runs have been computed.`);else{const t={median_intensity:a.map(e=>e.median_intensity),missing_pct:a.map(e=>e.missing_pct),control_corr:a.map(e=>e.control_corr),protein_count:a.map(e=>e.protein_count)};c=(0,v.uV)(e,t,s.metrics,s.rules_enabled??(0,v.kY)())}(0,v.setSpcStatus)(t,e,c);const u={instrument_id:n.instrument_id,acquisition_datetime:n.acquisition_datetime,run_label:t.name,median_intensity:e.median_intensity,missing_pct:e.missing_pct,control_corr:e.control_corr,protein_count:e.protein_count,status:c.status,rules_tripped:c.rulesTripped,source_project_id:null,source_df_name:t.name,computed_at:e.computed_at};await(0,_.upsertRun)(u),null!==l?o.shell.info(`Updated SPC for ${t.name} (previous status: ${l}).`):"pass"===c.status?o.shell.info(`SPC computed: ${t.name} — status: pass.`):"flagged"===c.status?o.shell.info(`SPC computed: ${t.name} — flagged on ${c.rulesTripped.length} rule(s): ${c.rulesTripped.join(", ")}.`):o.shell.info(`SPC computed: ${t.name} — OUT OF CONTROL on ${c.rulesTripped.length} rule(s): ${c.rulesTripped.join(", ")}.`)}finally{a.close()}}static async showVolcanoPlot(){const e=o.shell.tv,t=e?.dataFrame;e&&t?(0,S.RJ)(t,"Run Differential Expression first (Proteomics | Analyze | Differential Expression)")&&await se.volcanoOptions():o.shell.warning("No table open")}static async volcanoOptions(e){const t=o.shell.tv,n=t?.dataFrame;if(!t||!n)return void o.shell.warning("No table open");if(!(0,S.RJ)(n,"Run Differential Expression first (Proteomics | Analyze | Differential Expression)"))return;let a=e;if(!a)for(const e of t.viewers)if(e.type===s.VIEWER.SCATTER_PLOT&&"negLog10P"===e.props.yColumnName){a=e;break}const i=a?(0,N.ur)(n,a):{metric:"adj.p-value",colorDim:"significance"},l=null!=n.col("p-value"),c=l?i.metric:"adj.p-value",u=r.input.choice("Significance metric",{value:c,items:l?["adj.p-value","p-value"]:["adj.p-value"],nullable:!1});u.setTooltip(l?"Y axis, classification and threshold line all switch together":"p-value column not present — only adj.p-value is available");const p=r.input.choice("Color by",{value:i.colorDim,items:["significance","location"],nullable:!1});p.setTooltip("significance = Enriched in g1 / Enriched in g2 / Not significant; location = UniProt subcellular location");const d=r.input.int("Label top N points",{value:(0,N.m2)(n),min:0});d.setTooltip("How many of the most significant proteins get name labels. 0 = none. Labels no longer touch your row selection.");const f=(0,N.GE)(n),g=r.input.float("X-axis max (|log2FC|)",{value:f.xMax??void 0,min:0,nullable:!0});g.setTooltip("Pin the X axis to ±this |log2FC|. Leave empty to auto-scale. Set the same value on two volcanoes to compare them side-by-side.");const h=r.input.float("Y-axis max (−log10 p)",{value:f.yMax??void 0,min:0,nullable:!0});h.setTooltip("Pin the Y axis to 0…this −log10(p). Leave empty to auto-scale. Set the same value on two volcanoes to compare them side-by-side."),r.dialog("Volcano Options").add(u).add(p).add(d).add(g).add(h).onOK(async()=>{const e=u.value??"adj.p-value",r="location"===p.value?"location":"significance";if((0,N.S6)(n,g.value??null,h.value??null),a||(a=(0,N.gO)(n,{topNLabels:0}),t.addViewer(a)),"location"===r&&!n.col(N.fQ)){const e=await o.dapi.userDataStorage.get(A.er).catch(()=>null);0===(e?Object.keys(e).filter(e=>"__schema_v"!==e).length:0)?o.shell.info("Fetching subcellular locations from UniProt — may take a minute or two on first use without cache; subsequent toggles use the cache."):o.shell.info("Resolving subcellular locations from cache.")}const i="location"===r?"Classifying subcellular locations…":"Updating volcano…",l=s.TaskBarProgressIndicator.create(i),c="location"===r;c&&(0,N.DI)(a,i);const f=(e,t,n)=>{const o="fetch-acc"===n?"Fetching subcellular locations":"fetch-gene"===n?"Resolving by gene name":"init-column"===n||"location"===r?"Classifying subcellular locations":"Updating volcano",s=t>0?Math.round(e/t*100):0;if(l.update(s,`${o}: ${e}/${t}`),c){const n=t>1?`${e}/${t} (${s}%)`:"";(0,N.Bb)(a,o,n)}};try{await(0,N.nj)(n,a,e,r,m.M5,m.Dx,f),(0,N.XC)(n,a,d.value??(0,N.m2)(n))}catch(e){o.shell.error(`Volcano update failed: ${e?.message??e}`)}finally{l.close(),c&&a&&(0,N.kX)(a)}}).show()}static async showHeatmap(){const e=o.shell.tv,t=e?.dataFrame;if(!e||!t)return void o.shell.warning("No table open");if(!Z(t,"Heatmap"))return;if(!(0,S.RJ)(t,"Run Differential Expression first (Proteomics | Analyze | Differential Expression)"))return;const n=r.input.int("Top N proteins",{value:50,min:1});n.setTooltip("How many of the most significant proteins (by adj. p-value) to show."),r.dialog("Heatmap Options").add(n).onOK(async()=>{const o=n.value??50,r=s.TaskBarProgressIndicator.create("Creating heatmap...");try{const n=await x(t,{topN:o,title:`Heatmap: Top ${o} DE Proteins`});e.addViewer(n)}finally{r.close()}}).show()}static async showPcaPlot(){const e=o.shell.tv,t=e?.dataFrame;if(!e||!t)return void o.shell.warning("No table open");if(!Z(t,"PCA"))return;const n=(0,E.f)(t);if(!n)return void o.shell.warning("Annotate experimental groups first (Proteomics | Annotate Experiment)");const r=[...n.group1.columns,...n.group2.columns],{viewer:s,pcaDf:a}=F(t,r,n,"PCA: All Groups");a.name=`PCA: ${t.name}`,o.shell.addTableView(a).addViewer(s)}static async showGroupMeanCorrelation(){const e=o.shell.tv,t=e?.dataFrame;if(!e||!t)return void o.shell.warning("No table open");if(!(0,S.RJ)(t,"Run Differential Expression first (Proteomics | Analyze | Differential Expression)"))return;if(!(0,E.f)(t))return void o.shell.warning("Annotate experimental groups first (Proteomics | Annotate Experiment)");const n=(0,G.Z7)(t);e.addViewer(n)}static async showQcDashboard(){const e=o.shell.tv,t=e?.dataFrame;e&&t?Z(t,"QC Dashboard")&&O(t):o.shell.warning("No table open")}static async showSpcDashboard(){await(0,R.r9)()}static async showAllVisualizations(){const e=o.shell.tv,t=e?.dataFrame;if(!e||!t)return void o.shell.warning("No table open");if(!Z(t,"Show All Visualizations"))return;if(!(0,S.RJ)(t,"Run Differential Expression first"))return;const n=(0,E.f)(t),r=(0,N.gO)(t);e.addViewer(r);const a=s.TaskBarProgressIndicator.create("Creating heatmap...");try{const n=await x(t,{title:"Heatmap: Top 50 DE Proteins"});e.addViewer(n)}finally{a.close()}if(n){const e=[...n.group1.columns,...n.group2.columns],{viewer:r,pcaDf:s}=F(t,e,n,"PCA: All Groups");s.name=`PCA: ${t.name}`,o.shell.addTableView(s).addViewer(r)}}static async enrichmentAnalysis(){const e=o.shell.tv?.dataFrame;e?(0,Y.pG)(e):o.shell.warning("No table open")}static async exportEnrichmentInputs(){const e=o.shell.tv?.dataFrame;e?(0,S.RJ)(e,"Run Differential Expression first (Proteomics | Analyze | Differential Expression)")&&(0,T.N)(e):o.shell.warning("No table open")}static async enrichmentCharts(){const e=o.shell.tv,t=e?.dataFrame;if(!t)return void o.shell.warning("No table open");if("true"!==t.getTag("proteomics.enrichment"))return void o.shell.warning("Run Enrichment Analysis first (Proteomics | Enrichment Analysis)");const n=o.shell.tables.filter(e=>"true"===e.getTag("proteomics.de_complete"));if(0===n.length)return o.shell.warning("No protein table with DE results found. Enrichment charts will open without volcano linking."),void(0,z.q6)(t,t);n.length>1&&o.shell.warning(`Multiple protein tables with DE results found; linking enrichment to "${n[0].name}"`),(0,z.q6)(t,n[0])}static async proteomicsDemo(){await async function(){const e=s.TaskBarProgressIndicator.create("Loading proteomics demo…");try{e.update(5,"Importing HYE benchmark (Spectronaut DIA)…");const t=await J.files.readAsText("demo/spectronaut-hye-demo.tsv"),n=await(0,l.parseSpectronautText)(t);n.name="HYE benchmark";const r=o.shell.addTableView(n),a=(0,E.f)(n);if(!a)return void o.shell.warning("Demo: expected two auto-annotated conditions — opened the table without running differential expression.");const i=[...a.group1.columns,...a.group2.columns];e.update(40,"Imputing missing values (KNN)…"),(0,P.Mx)(n,i),n.setTag("proteomics.imputed","true"),e.update(60,"Differential expression (t-test)…"),(0,S.ps)(n,a.group1.columns,a.group2.columns,a.group1.name,a.group2.name),n.setTag("proteomics.de_method","t-test"),e.update(78,"Building volcano and heatmap…");const c=(0,N.gO)(n);r.dockManager.dock(c,s.DOCK_TYPE.RIGHT,null,"Volcano",.5);const u=await x(n,{title:"Heatmap: Top 50 DE Proteins"});r.dockManager.dock(u,s.DOCK_TYPE.DOWN,null,"Heatmap",.45),e.update(90,"Building QC dashboard tab…"),o.shell.addTableView(n).name="HYE benchmark — QC",O(n),o.shell.v=r,f(n,function(e){const t=e.col("adj.p-value"),n=e.col("significant");if(!t)return 0;let o=-1,r=1/0;for(let s=0;s<e.rowCount;s++){if(n&&!n.get(s))continue;if(t.isNone(s))continue;const e=t.get(s);e<r&&(r=e,o=s)}return o<0?0:o}(n)),e.update(100,"Done"),o.shell.info("Proteomics demo: HYE benchmark analyzed end to end (import → impute → differential expression). Yeast and E. coli proteins shift abundance between the two conditions, so the volcano separates the genuinely differential proteins from the constant human background. QC charts are on the second tab; the top hit is selected for its UniProt panel.")}finally{e.close()}}()}static async proteomicsEnrichmentDemo(){await async function(){const e=s.TaskBarProgressIndicator.create("Loading enrichment demo…");try{e.update(10,"Loading human DE result…");const t=await J.files.readAsText("demo/enrichment-demo.csv"),n=s.DataFrame.fromCsv(t);n.name="Treatment vs Control (human)";const r=(e,t)=>{const o=n.col(e);o&&(o.semType=t)};r("Protein ID",m.iu.PROTEIN_ID),r("Gene",m.iu.GENE_SYMBOL),r("log2FC",m.iu.LOG2FC),r("p-value",m.iu.P_VALUE),r("adj.p-value",m.iu.P_VALUE),n.setTag("proteomics.source","generic"),n.setTag("proteomics.de_method","precomputed"),n.setTag("proteomics.de_complete","true"),(0,E.$Y)(n,{group1:{name:"Treatment",columns:[]},group2:{name:"Control",columns:[]}});const a=o.shell.addTableView(n),i=(0,N.gO)(n);a.dockManager.dock(i,s.DOCK_TYPE.RIGHT,null,"Volcano",.5),f(n,0),e.update(45,"Running g:Profiler enrichment (GO / KEGG / Reactome)…");try{const{enrichmentDf:t,mapped:r,total:s}=await(0,Y.D9)(n,m.M5,m.Dx,"hsapiens",["GO:BP","GO:MF","GO:CC","KEGG","REAC","WP"],!0);e.update(90,"Opening enrichment charts…"),(0,z.q6)(t,n).name=`${n.name} — Enrichment`,o.shell.v=a,o.shell.info(`Enrichment demo: ${t.rowCount} over-represented terms across ${r}/${s} genes. Up-regulated proteins are enriched for cell-cycle / mitosis; down-regulated for oxidative phosphorylation. Select a term row to highlight its proteins on the volcano.`)}catch(e){o.shell.warning(`Enrichment demo: g:Profiler enrichment could not run (${e?.message??e}). The DE table and volcano are open — retry via Proteomics | Enrichment Analysis once the service is reachable.`)}e.update(100,"Done")}finally{e.close()}}()}static uniprotPanelWidget(e){return(0,k.ku)(e)}static async shareAnalysisForReview(){const e=o.shell.tv;let t=e?.dataFrame;if(t){if("true"!==t.getTag("proteomics.de_complete")){const e=o.shell.tables.filter(e=>"true"===e.getTag("proteomics.de_complete"));if(0===e.length)return void(0,S.RJ)(t,"Run Differential Expression first (Proteomics | Analyze | Differential Expression)");e.length>1&&o.shell.warning(`Multiple analyzed tables open; sharing "${e[0].name}".`),t=e[0]}await async function(e){if("true"!==e.getTag($.$y))return void o.shell.warning("Run Differential Expression first.");const t=await o.dapi.groups.list(),n=s.Group.defaultGroupsIds?.["All users"],a=(t??[]).filter(e=>!(null==e||e.hidden||e.personal||n&&e.id===n));if(0===a.length)return void o.shell.warning("No teams available to share with. Ask an admin to create a reviewer team.");const i=new Map;for(const e of a){const t=e.friendlyName??e.name??"";t&&!i.has(t)&&i.set(t,e)}const l=Array.from(i.keys()),c=r.input.string("Target",{value:""});c.setTooltip("Free text — your team's name for this target (e.g., MYH7-DMD, muscle-atrophy panel)");const u=r.input.choice("Share with team",{value:l[0],items:l,nullable:!1}),m=r.input.textArea?r.input.textArea("Note for reviewers",{value:""}):r.input.string("Note for reviewers",{value:""}),p=r.input.bool("Verify published dashboard",{value:(0,V.Cb)()});p.setTooltip("Re-open the shared dashboard after publishing to confirm it survives a reload. On = safer (recommended for client deliverables); off = faster share.");const d=r.div();d.style.cssText="background:#fff3cd; padding:8px; border-radius:4px; margin-bottom:8px; display:none;";const f=r.div();f.style.cssText="background:#f0f0f0; padding:8px; border-radius:4px; margin:8px 0; font-family: monospace; font-size:11px;";let g=null;const h=async()=>{const e=(c.value??"").trim(),t=u.value,n=t?i.get(t)??null:null,o=e?(0,$.fz)(e):"<no-target>",s=(new Date).toISOString().slice(0,10);if(e&&n)try{g=await(0,$.T7)(e,n)}catch{g=null}else g=null;const a=(e=>{if(!e)return 0;const t=/-v(\d+)-/.exec(e);if(!t)return 0;const n=parseInt(t[1],10);return Number.isFinite(n)?n:0})(g?g.name:null),l=a>0?a+1:1;g?(d.textContent=`⚠ This will share as v${l} and supersede "${g.name}". The previous version stays available for reference.`,d.style.display="block"):d.style.display="none";const m=`${(0,V.sK)()}-${o}-v${l}-${s}`,p=n?n.friendlyName??n.name??"<unnamed team>":"<pick a team>",h=g?`Will supersede "${g.name}" (v${l})`:"New share";f.innerHTML="",f.appendChild(r.divText(`Project: ${m}`)),f.appendChild(r.divText(`Will be visible to: ${p}`)),f.appendChild(r.divText(`Status: ${h}`)),f.appendChild(r.divText(`Date: ${s}`))};c.onChanged.subscribe(()=>{h()}),u.onChanged.subscribe(()=>{h()}),await h(),r.dialog("Share Analysis for Review").add(c).add(u).add(m).add(p).add(d).add(f).onOK(async()=>{const t=(c.value??"").trim();if(!t)return void o.shell.warning("Target is required.");const n=u.value?i.get(u.value):null;if(!n)return void o.shell.warning("Pick a team to share with.");const r={target:t,reviewerGroup:n,note:m.value??"",priorVersion:g,verify:p.value??!0};try{const t=await(0,j.M)(e,r),s=n.friendlyName??n.name??"(unnamed team)";o.shell.info(`Shared as ${t.name} with team ${s}.`)}catch(e){o.shell.error(`Share failed: ${e?.message??String(e)}`)}}).show()}(t)}else o.shell.warning("No table open")}static publishedAnalysisPanelWidget(e){return function(e){const t=(0,k.xh)(e);if(null==t)return new s.Widget(r.div());if(!(0,$.HF)(t))return new s.Widget(r.div());const n=(0,$.M4)(t);if(null==n)return new s.Widget(r.divText("Shared analysis metadata unavailable. Ask the sharer to re-share."));const a=r.div();if(a.style.padding="8px 4px",null!=n.supersededBy&&""!==n.supersededBy){const e=r.link("Newer version available — open it",async()=>{try{const e=await o.dapi.projects.find(n.supersededBy);await e.open()}catch(e){o.shell.warning(`Could not open the newer version: ${e?.message??e}`)}}),t=r.div([e]);t.style.padding="8px",t.style.marginBottom="10px",t.style.backgroundColor="#fff8dc",t.style.borderRadius="4px",a.appendChild(t)}a.appendChild(r.h2("Shared analysis details"));const i=(0,E.f)(t),l=null!=i?`${i.group2.name} vs ${i.group1.name}`:"unavailable",c=Number.isFinite(n.fcThreshold)?Math.pow(2,n.fcThreshold):NaN,u=Number.isFinite(n.fcThreshold)?`log2(${n.fcThreshold}) (${Number.isFinite(c)?c.toFixed(2):"NaN"}-fold)`:"(unknown)",m=Number.isFinite(n.pThreshold)?`${n.pThreshold} (FDR-adjusted)`:"(unknown)";a.appendChild(U("Target",n.target||"(unknown)")),a.appendChild(U("Shared",B(n.publishedAt))),a.appendChild(U("Shared by",n.publishedBy||"(unknown)")),a.appendChild(U("Method",function(e){switch(e){case"limma":return"limma — moderated t-test";case"deqms":return"DEqMS — peptide-count-aware moderated t-test";case"t-test":return"Welch t-test";case"spectronaut":return"Spectronaut Candidates (pre-computed DE)";default:return e||"(unknown method)"}}(n.deMethod))),a.appendChild(U("Comparison",l)),a.appendChild(U("Fold-change cutoff",u)),a.appendChild(U("p-value cutoff",m));const p=function(e,t){if(null!=t.publishedByEmail&&""!==t.publishedByEmail)return t.publishedByEmail;try{const t=e.col($.MD.PUBLISHED_BY_EMAIL);if(null!=t){const e=t.get(0);if(null!=e&&""!==e)return String(e)}}catch{}try{const t=e.getTag($.L6.PUBLISHED_BY_EMAIL);if(t)return t}catch{}return null}(t,n);if(null!=p){const e=t.name||"shared analysis",o=(0,$.Kj)({sharerEmail:p,sharerName:n.publishedBy||"colleague",projectName:e,publishedDateStr:B(n.publishedAt)}),s=r.link("Request re-run with different parameters",o);s.href=o;const i=r.div([s]);i.style.marginTop="12px",a.appendChild(i)}return new s.Widget(a)}(e)}static async recoverPublishedProjectsOnStartup(){const e=o.events.onProjectOpened??o.events.onCurrentProjectChanged??null;if(e&&"function"==typeof e.subscribe)e.subscribe(()=>{(async()=>{await new Promise(e=>setTimeout(e,200));const e=o.shell.tables;if(Array.isArray(e))for(const t of e)if((0,$.HF)(t))try{await(0,q.I)(t)}catch(e){o.shell.warning(`Could not auto-recover shared analysis on open: ${e?.message??e}`)}})()});else{const e=o.events.onViewAdded;e&&"function"==typeof e.subscribe&&e.subscribe(e=>{if(e instanceof s.TableView){const t=e.dataFrame;t&&(0,$.HF)(t)&&(0,q.I)(t).catch(e=>{o.shell.warning(`Could not auto-recover shared analysis on open: ${e?.message??e}`)})}})}}}Q([o.decorators.init({tags:["init"]}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"initProteomics",null),Q([o.decorators.func({tags:["autostart"],meta:{autostartImmediate:"true"}}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"buildProteomicsTopMenu",null),Q([o.decorators.func({"top-menu":"Proteomics | Import | Spectronaut Candidates..."}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"importSpectronautCandidates",null),Q([o.decorators.func({"top-menu":"Proteomics | Import | Spectronaut Report..."}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"importSpectronaut",null),Q([o.decorators.func({"top-menu":"Proteomics | Import | MaxQuant..."}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"importMaxQuant",null),Q([o.decorators.func({"top-menu":"Proteomics | Import | FragPipe..."}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"importFragPipe",null),Q([o.decorators.func({"top-menu":"Proteomics | Import | Generic Matrix..."}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"importGenericMatrix",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"annotateExperiment",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"setLog2Scale",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"normalizeProteomics",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"imputeMissingValues",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"differentialExpression",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"computeSpcStatus",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"showVolcanoPlot",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"showHeatmap",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"showPcaPlot",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"showGroupMeanCorrelation",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"showQcDashboard",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"showSpcDashboard",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"showAllVisualizations",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"enrichmentAnalysis",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"exportEnrichmentInputs",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"enrichmentCharts",null),Q([o.decorators.func({name:"Proteomics Demo",description:"End-to-end proteomics differential-expression analysis on the HYE benchmark: import → impute → differential expression → volcano + heatmap, with a QC dashboard tab and the top hit pre-selected for its UniProt panel",meta:{demoPath:"Proteomics | Differential Expression",isDemoDashboard:"true"}}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"proteomicsDemo",null),Q([o.decorators.func({name:"Proteomics Enrichment Demo",description:"Pathway enrichment (g:Profiler GO / KEGG / Reactome / WikiPathways) on a human differential-expression result — cell-cycle up, oxidative-phosphorylation down — with the enrichment charts cross-linked to the volcano",meta:{demoPath:"Proteomics | Enrichment Analysis",isDemoDashboard:"true"}}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"proteomicsEnrichmentDemo",null),Q([o.decorators.panel({name:"Proteomics | UniProt",description:"UniProt protein details",meta:{role:"widgets"}}),K(0,o.decorators.param({options:{semType:"Proteomics-ProteinId"}})),W("design:type",Function),W("design:paramtypes",[String]),W("design:returntype",s.Widget)],se,"uniprotPanelWidget",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"shareAnalysisForReview",null),Q([o.decorators.panel({name:"Proteomics | Shared Analysis",description:"Audit context for a shared analysis snapshot",meta:{role:"widgets"}}),K(0,o.decorators.param({options:{semType:"Proteomics-ProteinId"}})),W("design:type",Function),W("design:paramtypes",[String]),W("design:returntype",s.Widget)],se,"publishedAnalysisPanelWidget",null),Q([o.decorators.func({tags:["autostart"],meta:{autostartImmediate:"true"}}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"recoverPublishedProjectsOnStartup",null)},498(e,t,n){"use strict";n.d(t,{A$:()=>d,S6:()=>u,ku:()=>f,nT:()=>p,xh:()=>m});var o=n(328),r=n(389),s=n(82),a=n(623),i=n(252),l=n(304),c=n(641);function u(e){if(!e||!e.trim())return null;const t=e.split(";")[0].trim();if(!t)return null;const n=t.match(/^(?:sp|tr)\|([A-Za-z0-9_-]+)\|/);if(n)return n[1];const o=t.match(/^([A-Za-z0-9]+?)ups\|/i);if(o)return o[1];if(t.includes("|"))return t.split("|")[0].trim();const r=t.match(/^([A-Za-z0-9_-]+)$/);return r?r[1].replace(/ups$/i,""):null}function m(e){if(!e)return null;const t=[];for(const n of o.shell.tables){if(!(0,i.f)(n))continue;const o=(0,l.k)(n,c.iu.PROTEIN_ID,["primary protein id","protein id","uniprot","accession"]);if(o)for(let r=0;r<n.rowCount;r++){const s=o.get(r);if(s&&u(s)===e){t.push(n);break}}}if(0===t.length)return null;const n=o.shell.tv?.dataFrame??null;return n&&t.includes(n)?n:t[0]}function p(e,t){const n=(0,i.f)(e);if(!n)return null;const o=(0,l.k)(e,c.iu.PROTEIN_ID,["primary protein id","protein id","uniprot","accession"]);if(!o)return null;let a=-1;for(let n=0;n<e.rowCount;n++){const e=o.get(n);if(e&&u(e)===t){a=n;break}}if(a<0)return null;const m=[n.group1,n.group2].map(t=>{const n=t.columns.map(t=>e.col(t)).filter(e=>null!=e).map(e=>e.isNone(a)?NaN:e.get(a)).filter(e=>"number"==typeof e&&!isNaN(e)&&e!==s.FLOAT_NULL),o=n.length;if(0===o)return{name:t.name,mean:NaN,sd:NaN,n:0};const r=n.reduce((e,t)=>e+t,0)/o,i=o>1?n.reduce((e,t)=>e+(t-r)**2,0)/(o-1):0;return{name:t.name,mean:r,sd:Math.sqrt(i),n:o}});if(m.every(e=>0===e.n))return r.divText("No per-group quantities available for this protein");const p=Math.max(...m.map(e=>isNaN(e.mean)?0:e.mean+(isNaN(e.sd)?0:e.sd))),d=p>0?p:1,f=e=>96-e/d*72,g=e=>"#"+(16777215&e).toString(16).padStart(6,"0").toUpperCase(),h=[g(c.PL.enrichedG1),g(c.PL.enrichedG2)],y="http://www.w3.org/2000/svg",E=document.createElementNS(y,"svg");E.setAttribute("width",String(200)),E.setAttribute("height",String(120)),m.forEach((e,t)=>{const n=24+40*t;if(0===e.n)return;const o=f(e.mean),r=document.createElementNS(y,"rect");if(r.setAttribute("x",String(n)),r.setAttribute("y",String(o)),r.setAttribute("width",String(24)),r.setAttribute("height",String(Math.max(0,96-o))),r.setAttribute("fill",h[t]??g(c.PL.notSig)),E.appendChild(r),e.n>1&&!isNaN(e.sd)){const t=n+12,o=f(e.mean+e.sd),r=f(e.mean-e.sd),s=document.createElementNS(y,"line");s.setAttribute("x1",String(t)),s.setAttribute("x2",String(t)),s.setAttribute("y1",String(o)),s.setAttribute("y2",String(r)),s.setAttribute("stroke","#333"),s.setAttribute("stroke-width","1"),E.appendChild(s)}const s=document.createElementNS(y,"text");s.setAttribute("x",String(n+12)),s.setAttribute("y",String(116)),s.setAttribute("text-anchor","middle"),s.setAttribute("font-size","10"),s.textContent=`${e.name} (n=${e.n})`,E.appendChild(s)});const w=r.divV([E]);return m.forEach(e=>{if(e.n>0){const t=r.divText(`${e.name}: mean=${e.mean.toFixed(2)} SD=${e.sd.toFixed(2)}`);t.style.fontSize="0.85em",w.appendChild(t)}}),w}function d(e,t){const n=document.createElement("div"),o=r.link(`UniProt: ${t}`,`https://www.uniprot.org/uniprot/${t}`,"Open full UniProt entry");o.style.fontWeight="bold",o.style.display="block",o.style.marginBottom="8px",n.appendChild(o);const s=function(e){return e.proteinDescription?.recommendedName?.fullName?.value??e.proteinDescription?.submissionNames?.[0]?.fullName?.value??"Unknown"}(e),a=e.genes?.[0]?.geneName?.value??"Unknown",i=e.organism?.scientificName??"Unknown",l=e.comments?.find(e=>"FUNCTION"===e.commentType);let c=l?.texts?.[0]?.value??"";c.length>200&&(c=c.substring(0,200)+"...");const u={Protein:s,Gene:a,Organism:i};c&&(u.Function=c),n.appendChild(r.tableFromMap(u));const d=function(e){const t=[],n=[],o=[];for(const r of e.uniProtKBCrossReferences??[]){if("GO"!==r.database)continue;const e=r.properties?.find(e=>"GoTerm"===e.key)?.value??"";e.startsWith("F:")?t.push(e.substring(2)):e.startsWith("P:")?n.push(e.substring(2)):e.startsWith("C:")&&o.push(e.substring(2))}return{mf:t,bp:n,cc:o}}(e),f=[{label:"Molecular Function",terms:d.mf},{label:"Biological Process",terms:d.bp},{label:"Cellular Component",terms:d.cc}];if(f.some(e=>e.terms.length>0)){const e=r.divText("GO Terms");e.style.fontWeight="bold",e.style.marginTop="8px",e.style.marginBottom="4px",n.appendChild(e);for(const e of f){if(0===e.terms.length)continue;const t=r.divText(e.label);t.style.fontWeight="bold",t.style.fontSize="0.9em",t.style.marginTop="4px",n.appendChild(t);const o=e.terms.slice(0,5).join(", "),s=r.divText(o);s.style.fontSize="0.85em",s.style.marginLeft="8px",n.appendChild(s)}}const g=m(t);if(g){const e=r.divText("Per-Group Quantities");e.style.fontWeight="bold",e.style.marginTop="8px",e.style.marginBottom="4px",n.appendChild(e);const o=p(g,t);n.appendChild(o??r.divText("No per-group quantities available for this protein"))}return n}function f(e){const t=u(e);return t?new s.Widget(r.wait(async()=>{const e=await async function(e){return await(0,a.Kf)(e)}(t);return e?d(e,t):r.divText(`Unable to fetch UniProt data for ${t}`)})):new s.Widget(r.divText("No valid UniProt accession found"))}},119(e,t,n){"use strict";n.d(t,{p:()=>f});var o=n(82),r=n(641),s=n(954),a=n(117);const i=[" MaxLFQ Intensity"," Intensity"," Razor Intensity"],l=["Protein ID","Protein"],c=["Gene","Gene Names","Gene Symbol"],u=["contam_","rev_","CON__","REV__"];function m(e,t){for(const n of t){const t=e.col(n);if(t)return t}return null}function p(e){const t=e.toLowerCase();for(const e of i)if(t.endsWith(e.toLowerCase())&&t.length>e.length)return e.toLowerCase();return null}function d(e,t,n,o){const r=m(e,t);r&&(0,s.wK)(e,r.name,n,o)}async function f(e){const t=function(e){const t=e.indexOf("\n"),n=(t>=0?e.substring(0,t):e).replace(/\r$/,"").split("\t"),o=[];for(const e of n)p(e)&&o.push({name:e,type:"double"});return o}(e),n=o.DataFrame.fromCsv(e,{delimiter:"\t",columnImportOptions:t});n.filter.init(e=>!0),function(e){const t=["Protein ID","Protein"],n=[];for(const o of t){const t=e.col(o);t&&n.push(t)}if(0!==n.length)for(let t=0;t<e.rowCount;t++)for(const o of n){const n=o.get(t);if("string"!=typeof n)continue;let r=!1;for(const e of u)if(n.startsWith(e)){r=!0;break}if(r){e.filter.set(t,!1,!1);break}}}(n),n.filter.fireChanged();const i=n.clone(n.filter),f=function(e){const t=new Map;for(const n of e.columns.names()){const r=e.col(n);if(!r)continue;if(r.type!==o.COLUMN_TYPE.FLOAT&&r.type!==o.COLUMN_TYPE.INT&&r.type!==o.COLUMN_TYPE.BIG_INT)continue;const s=n.toLowerCase();let a=null,i=null;s.endsWith(" maxlfq intensity")?(a=n.substring(0,n.length-17),i="maxLfq"):s.endsWith(" razor intensity")?(a=n.substring(0,n.length-16),i="razor"):s.endsWith(" intensity")&&(a=n.substring(0,n.length-10),i="intensity"),a&&i&&(t.has(a)||t.set(a,{}),t.get(a)[i]=n)}const n=[];for(const e of t.values())e.maxLfq?n.push(e.maxLfq):e.intensity?n.push(e.intensity):e.razor&&n.push(e.razor);return n}(i);return function(e,t){const n=m(e,l);n&&(n.semType=r.iu.PROTEIN_ID);const o=m(e,c);o&&(o.semType=r.iu.GENE_SYMBOL);for(const n of t){const t=e.col(n);t&&(t.semType=r.iu.INTENSITY)}}(i,f),d(i,l,"Primary Protein ID",r.iu.PROTEIN_ID),d(i,c,"Primary Gene Name",r.iu.GENE_SYMBOL),(0,s.Kh)(i,f),i.setTag("proteomics.source","fragpipe"),await(0,a.rv)(i),i}},312(e,t,n){"use strict";n.d(t,{E:()=>h});var o=n(82),r=n(641),s=n(954),a=n(117);const i=["lfq intensity","ibaq","reporter intensity","intensity"],l=["Potential contaminant","Potential.contaminant"],c=["Reverse"],u=["Only identified by site","Only.identified.by.site"],m=["Protein IDs","Majority protein IDs"],p=["Gene names","Gene name"];function d(e,t){for(const n of t){const t=e.col(n);if(t)return t}return null}function f(e,t){const n=d(e,t);if(n)for(let t=0;t<e.rowCount;t++)"+"===n.get(t)&&e.filter.set(t,!1,!1)}function g(e,t,n,o){const r=d(e,t);r&&(0,s.wK)(e,r.name,n,o)}async function h(e){const t=function(e){const t=e.indexOf("\n"),n=(t>=0?e.substring(0,t):e).replace(/\r$/,"").split("\t"),o=[];for(const e of n){const t=e.toLowerCase();for(const n of i)if(t.startsWith(n)){o.push({name:e,type:"double"});break}}return o}(e),n=o.DataFrame.fromCsv(e,{delimiter:"\t",columnImportOptions:t});n.filter.init(e=>!0),f(n,l),f(n,c),f(n,u),function(e){const t=[];for(const n of m){const o=e.col(n);o&&t.push(o)}if(0!==t.length)for(let n=0;n<e.rowCount;n++)for(const o of t){const t=o.get(n);if("string"==typeof t&&(t.startsWith("CON__")||t.startsWith("REV__"))){e.filter.set(n,!1,!1);break}}}(n),n.filter.fireChanged();const h=n.clone(n.filter);return function(e){const t=d(e,m);t&&(t.semType=r.iu.PROTEIN_ID);const n=d(e,p);n&&(n.semType=r.iu.GENE_SYMBOL)}(h),g(h,m,"Primary Protein ID",r.iu.PROTEIN_ID),g(h,p,"Primary Gene Name",r.iu.GENE_SYMBOL),function(e){const t=[];for(const n of e.columns.names()){const r=e.col(n);if(!r)continue;if(r.type!==o.COLUMN_TYPE.FLOAT&&r.type!==o.COLUMN_TYPE.INT)continue;const s=n.toLowerCase();for(const e of i)if(s.startsWith(e)){t.push(n);break}}(0,s.Kh)(e,t)}(h),h.setTag("proteomics.source","maxquant"),await(0,a.rv)(h),h}},954(e,t,n){"use strict";n.d(t,{Kh:()=>s,T6:()=>c,WI:()=>p,YL:()=>m,eY:()=>l,l3:()=>a,q2:()=>u,wK:()=>i});var o=n(82),r=n(641);function s(e,t){let n=0;for(const s of t){const t=e.col(s);if(!t)continue;t.semType=r.iu.INTENSITY;const a=`log2(${s})`,i=e.columns.addNewFloat(a);i.init(e=>{if(t.isNone(e))return o.FLOAT_NULL;const r=Number(t.get(e));return isNaN(r)?(n++,o.FLOAT_NULL):r>0?Math.log2(r):o.FLOAT_NULL}),i.semType=r.iu.INTENSITY}n>0&&console.warn(`log2TransformColumns: ${n} non-numeric value(s) dropped to null`)}function a(e,t){for(const n of t){const t=e.col(n);if(!t)continue;t.semType=r.iu.INTENSITY;const s=`log2(${n})`,a=e.columns.addNewFloat(s);a.init(e=>t.isNone(e)?o.FLOAT_NULL:Number(t.get(e))),a.semType=r.iu.INTENSITY}}function i(e,t,n,o){const r=e.col(t);if(!r)return;let s=!1;for(let t=0;t<e.rowCount&&!s;t++){const e=r.get(t);"string"==typeof e&&e.includes(";")&&(s=!0)}if(!s)return;const a=e.columns.addNewString(n);a.init(e=>{const t=r.get(e);if("string"!=typeof t||0===t.length)return null;const n=t.indexOf(";");return n>=0?t.substring(0,n):t}),a.semType=o}function l(e,t){let n=0,r=0,s=0;for(const a of t){const t=e.col(a);if(t&&(t.type===o.COLUMN_TYPE.FLOAT||t.type===o.COLUMN_TYPE.INT||t.type===o.COLUMN_TYPE.BIG_INT)){for(let o=0;o<e.rowCount&&s<200;o++){if(t.isNone(o))continue;const e=Number(t.get(o));e>=0&&e<=30?(n++,s++):e>=1e3&&(r++,s++)}if(s>=200)break}}return 0===s?{isLog2:!1,message:"No intensity values found"}:r/s>.5?{isLog2:!1,message:"Data appears to be raw intensities"}:n/s>.8?{isLog2:!0,message:"Data appears to be already log2-transformed"}:{isLog2:!1,message:"Could not determine data scale"}}function c(e){const t=e.indexOf("\n"),n=t>=0?e.substring(0,t):e;return(n.match(/\t/g)||[]).length>(n.match(/,/g)||[]).length?"\t":","}function u(e){const t=["protein","accession","uniprot"];for(const n of e.columns.toList()){if(n.type!==o.COLUMN_TYPE.STRING)continue;const e=n.name.toLowerCase();for(const o of t)if(e.includes(o))return n}return null}function m(e){const t=["gene","symbol","gene_name","genename"];for(const n of e.columns.toList()){if(n.type!==o.COLUMN_TYPE.STRING)continue;const e=n.name.toLowerCase();for(const o of t)if(e.includes(o))return n}return null}function p(e){const t=["intensity","lfq","ibaq","tmt","reporter","abundance"],n=[];for(const r of e.columns.toList()){if(r.type!==o.COLUMN_TYPE.FLOAT&&r.type!==o.COLUMN_TYPE.INT&&r.type!==o.COLUMN_TYPE.BIG_INT)continue;const e=r.name.toLowerCase();for(const o of t)if(e.includes(o)){n.push(r.name);break}}return n}},86(e,t,n){"use strict";n.d(t,{R:()=>_,g:()=>d});var o=n(82),r=n(641),s=n(954),a=n(117),i=n(252);const l=["PG.ProteinGroups","ProteinGroups","Protein Groups"],c=["PG.Genes","Genes","Gene Names"],u=["AVG Log2 Ratio","Log2 Ratio","AVG Log2 Fold Change"],m=["Qvalue","Q-Value","Q.Value","AdjustedPValue","Adjusted P-Value"],p=["Pvalue","PValue","P-Value","P.Value"],d=["Comparison (group1/group2)","Comparison"],f=["AVG Group Quantity Numerator"],g=["AVG Group Quantity Denominator"],h=["Condition Numerator"],y=["Condition Denominator"],E=["contam_","rev_","CON__","REV__"];function w(e,t){for(const n of t){const t=e.col(n);if(t)return t}return null}function v(e,t,n){if(t.name===n)return;const o=e.col(n);o&&o!==t||(t.name=n)}async function _(e){const t=(0,s.T6)(e),n=o.DataFrame.fromCsv(e,{delimiter:t}),_=w(n,l);if(!_)throw new Error(`Spectronaut Candidates: missing protein-group column (expected one of ${l.join(", ")})`);if(!w(n,u))throw new Error(`Spectronaut Candidates: missing log2 ratio column (expected one of ${u.join(", ")})`);if(!w(n,m))throw new Error(`Spectronaut Candidates: missing q-value column (expected one of ${m.join(", ")})`);n.filter.init(e=>!0),function(e,t){const n=e.col(t);if(n)for(let t=0;t<e.rowCount;t++){const o=n.get(t);if("string"==typeof o)for(const n of E)if(o.startsWith(n)){e.filter.set(t,!1,!1);break}}}(n,_.name),n.filter.fireChanged();const b=n.clone(n.filter),T=w(b,l),P=w(b,u),S=w(b,m),N=w(b,c),A=w(b,p);v(b,P,"log2FC"),v(b,S,"adj.p-value"),A&&v(b,A,"p-value"),T.semType=r.iu.PROTEIN_ID,N&&(N.semType=r.iu.GENE_SYMBOL),b.col("log2FC").semType=r.iu.LOG2FC,b.col("adj.p-value").semType=r.iu.P_VALUE,b.col("p-value")&&(b.col("p-value").semType=r.iu.P_VALUE),(0,s.wK)(b,T.name,"Primary Protein ID",r.iu.PROTEIN_ID),N&&(0,s.wK)(b,N.name,"Primary Gene Name",r.iu.GENE_SYMBOL),function(e){const t=w(e,d);if(!t)return;const n=e.rowCount;let r=null,s="",a="";for(let e=0;e<n;e++){const n=t.get(e);if("string"==typeof n&&n.includes(" / ")){const e=n.split(" / ");if(2===e.length&&e[0]&&e[1]){r=n,s=e[0],a=e[1];break}}}if(null===r)return;const i=`${a} / ${s}`,l=new Uint8Array(n);let c=!1;for(let e=0;e<n;e++)t.get(e)===i&&(l[e]=1,c=!0);if(!c)return;const u=e.col("log2FC"),m=u.getRawData(),p=new Array(n);for(let e=0;e<n;e++){const t=m[e];p[e]=t===o.FLOAT_NULL?o.FLOAT_NULL:l[e]?-t:t}u.init(e=>p[e]);const E=w(e,f),v=w(e,g);if(E&&v){const e=E.getRawData(),t=v.getRawData(),o=new Array(n),r=new Array(n);for(let s=0;s<n;s++){const n=e[s],a=t[s];o[s]=l[s]?a:n,r[s]=l[s]?n:a}E.init(e=>o[e]),v.init(e=>r[e])}const _=new Array(n);for(let e=0;e<n;e++)_[e]=l[e]?r:t.get(e);t.init(e=>_[e]);const C=w(e,h),b=w(e,y);if(C&&b){const e=new Array(n),t=new Array(n);for(let o=0;o<n;o++)e[o]=l[o]?s:C.get(o),t[o]=l[o]?a:b.get(o);C.init(t=>e[t]),b.init(e=>t[e])}}(b);const x=b.columns.addNewBool("significant"),D=b.col("log2FC").getRawData(),L=b.col("adj.p-value").getRawData();x.init(e=>{const t=D[e],n=L[e];return t!==o.FLOAT_NULL&&n!==o.FLOAT_NULL&&Math.abs(t)>=r.M5&&n<=r.Dx}),b.setTag("proteomics.source","spectronaut-candidates"),b.setTag("proteomics.de_complete","true"),b.setTag("proteomics.de_method","spectronaut");let F=C(w(b,h)),I=C(w(b,y));if(!F||!I){const e=C(w(b,d));if(e&&e.includes("/")){const[t,n]=e.split("/").map(e=>e.trim());F=F??(t||null),I=I??(n||null)}}return F&&I&&(0,i.$Y)(b,{group1:{name:F,columns:[]},group2:{name:I,columns:[]}}),await(0,a.rv)(b),b}function C(e){if(!e)return null;for(let t=0;t<e.length;t++){const n=e.get(t);if(null!=n&&String(n).trim().length>0)return String(n).trim()}return null}},53(e,t,n){"use strict";n.d(t,{A:()=>f,parseSpectronautText:()=>g});var o=n(328),r=n(82),s=n(641),a=n(954),i=n(252),l=n(117);const c=["R.Condition","R.Replicate","PG.ProteinGroups"],u=["PG.IBAQ","PG.Quantity"];function m(e){if(!e||0===e.trim().length)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}async function p(e){const t=function(e){const t=Array.from(e.proteinMap.keys()),n=t.length,o=r.Column.fromStrings("PG.ProteinGroups",t);o.semType=s.iu.PROTEIN_ID;const a=[o];if(e.organisms.size>0){const n=t.map(t=>e.organisms.get(t)??""),o=r.Column.fromStrings("PG.Organisms",n);a.push(o)}for(const o of e.sampleKeys){const i=new Float32Array(n);for(let s=0;s<n;s++){const n=e.proteinMap.get(t[s]);i[s]=n.has(o)?n.get(o):r.FLOAT_NULL}const l=r.Column.fromFloat32Array(o,i);l.semType=s.iu.INTENSITY,e.sampleFileNames.has(o)&&l.setTag("spectronaut.fileName",e.sampleFileNames.get(o)),a.push(l)}return r.DataFrame.fromColumns(a)}(e);(0,a.wK)(t,"PG.ProteinGroups","Primary Protein ID",s.iu.PROTEIN_ID);const n=e.sampleKeys;return(0,a.eY)(t,n).isLog2?(0,a.l3)(t,n):(0,a.Kh)(t,n),t.setTag("proteomics.preNormalized","true"),t.setTag("proteomics.source","spectronaut"),function(e,t){const n=new Map;for(const e of t){const t=e.lastIndexOf("_"),o=e.substring(0,t);n.has(o)||n.set(o,[]),n.get(o).push(`log2(${e})`)}const o=Array.from(n.keys());2===o.length&&(0,i.$Y)(e,{group1:{name:o[0],columns:n.get(o[0])},group2:{name:o[1],columns:n.get(o[1])}})}(t,e.sampleKeys),await(0,l.rv)(t),t}function d(e){if(null==e)return null;const t=e.trim();if(""===t||"NaN"===t||"NA"===t)return null;const n=Number(t);return Number.isFinite(n)?n:null}async function f(e,t=.01){const n=r.TaskBarProgressIndicator.create("Streaming Spectronaut report...");try{const r=e.stream().pipeThrough(new TextDecoderStream("utf-8")).getReader(),s=new Map;let a="",i=!1,l=new Map,f=-1,g=-1,y=-1,E=-1,w=-1,v=-1,_=-1,C=-1,b=-1,T=0,P=null,S=null,N=null,A=0,x=0,D=0,L=0,F=performance.now();const I=Math.max(1,e.size),M=e=>{if(e.length<T)return"malformed";const n=e[f];if(!n)return"filtered";if(n.startsWith("CON__")||n.startsWith("REV__"))return"filtered";const o=E>=0?d(e[E]):null;if(null!==o&&o>t)return"filtered";const r=d(e[w]);if(null===r&&null===o)return"filtered";const a=e[g]??"",i=e[y]??"",l=n+""+a+""+i;let c=s.get(l);if(void 0===c&&(c={protein:n,condition:a,replicate:i,maxQuantity:-1/0,minQvalue:1/0,fileName:null,organism:null},s.set(l,c)),null!==r&&r>c.maxQuantity&&(c.maxQuantity=r),null!==o&&o<c.minQvalue&&(c.minQvalue=o),null===c.fileName&&v>=0){const t=e[v];t&&(c.fileName=t)}if(null===c.organism&&_>=0){const t=e[_];t&&(c.organism=t)}if(C>=0){const t=e[C];if(t){const e=m(t);null!==e&&(null===P||e<P)&&(P=e,S=new Date(e).toISOString())}}if(b>=0&&null===N){const t=e[b];t&&t.trim().length>0&&(N=t)}return"kept"},O=e=>{const t=e.split("\t");l=new Map;for(let e=0;e<t.length;e++)l.set(t[e],e);for(const e of c)if(!l.has(e))throw new Error(`Missing required Spectronaut column: ${e}`);const n=u.find(e=>l.has(e));if(!n)throw new Error(`Missing protein-group quantity column (expected one of ${u.join(", ")})`);f=l.get("PG.ProteinGroups"),g=l.get("R.Condition"),y=l.get("R.Replicate"),w=l.get(n),E=l.has("EG.Qvalue")?l.get("EG.Qvalue"):-1,v=l.has("R.FileName")?l.get("R.FileName"):-1,_=l.has("PG.Organisms")?l.get("PG.Organisms"):-1,C=l.has("R.RunDate")?l.get("R.RunDate"):-1,b=l.has("R.InstrumentMethod")?l.get("R.InstrumentMethod"):-1,T=Math.max(f,g,y,w,E,v,_,C,b)+1,i=!0};for(;;){const{value:e,done:t}=await r.read();if(t)break;let o;for(A+=e.length,a+=e;(o=a.indexOf("\n"))>=0;){let e=a.slice(0,o);if(a=a.slice(o+1),e.endsWith("\r")&&(e=e.slice(0,-1)),i){if(0!==e.length)switch(M(e.split("\t"))){case"kept":x++;break;case"malformed":D++;break;case"filtered":L++}}else{if(0===e.length)continue;O(e)}}if(performance.now()-F>=16){const e=Math.min(99,A/I*100),t=D>0?`${x} rows (${D} malformed skipped)`:`${x} rows`;n.update(e,t),await new Promise(e=>setTimeout(e,0)),F=performance.now()}}if(a.length>0){let e=a;if(e.endsWith("\r")&&(e=e.slice(0,-1)),e.length>0)if(i)switch(M(e.split("\t"))){case"kept":x++;break;case"malformed":D++;break;case"filtered":L++}else O(e)}if(!i)throw new Error("Missing required Spectronaut column: R.Condition");D>0&&o.shell.info(`Spectronaut import: skipped ${D} malformed line(s)`);const R=function(e){const t=new Map,n=new Set,o=new Map,r=new Map;for(const s of e.values()){if(!Number.isFinite(s.maxQuantity))continue;const e=`${s.condition}_${s.replicate}`;n.add(e),t.has(s.protein)||t.set(s.protein,new Map),t.get(s.protein).set(e,s.maxQuantity),null===s.fileName||o.has(e)||o.set(e,s.fileName),null===s.organism||r.has(s.protein)||r.set(s.protein,s.organism)}return{proteinMap:t,sampleKeys:Array.from(n).sort(),sampleFileNames:o,organisms:r}}(s);R.earliestRunDate=S,R.firstInstrumentMethod=N;const G=await p(R);return h(G,R),G}finally{n.close()}}async function g(e,t=.01){const n=r.DataFrame.fromCsv(e,{delimiter:"\t"});for(const e of c)if(!n.col(e))throw new Error(`Missing required Spectronaut column: ${e}`);const o=u.find(e=>null!==n.col(e));if(!o)throw new Error(`Missing protein-group quantity column (expected one of ${u.join(", ")})`);const s=function(e,t,n){const o=e.col("R.Condition"),r=e.col("R.Replicate"),s=e.col("PG.ProteinGroups"),a=e.col(t),i=e.col("EG.Qvalue"),l=e.col("R.FileName"),c=e.col("PG.Organisms"),u=e.col("R.RunDate"),p=e.col("R.InstrumentMethod"),d=new Map,f=new Set,g=new Map,h=new Map;let y=null,E=null,w=null;for(let t=0;t<e.rowCount;t++){if(i)if(i.isNone(t));else{const e=i.get(t),o=Number(e);if(!isNaN(o)&&o>n)continue}const e=s.get(t);if(!e)continue;if(e.startsWith("CON__")||e.startsWith("REV__"))continue;const v=`${String(o.get(t))}_${String(r.get(t))}`;if(f.add(v),d.has(e)||d.set(e,new Map),d.get(e).has(v)||a.isNone(t)||d.get(e).set(v,Number(a.get(t))),!l||g.has(v)||l.isNone(t)||g.set(v,l.get(t)),!c||h.has(e)||c.isNone(t)||h.set(e,c.get(t)),u&&!u.isNone(t)){const e=m(String(u.get(t)));null!==e&&(null===y||e<y)&&(y=e,E=new Date(e).toISOString())}if(p&&null===w&&!p.isNone(t)){const e=String(p.get(t));e.trim().length>0&&(w=e)}}return{proteinMap:d,sampleKeys:Array.from(f).sort(),sampleFileNames:g,organisms:h,earliestRunDate:E,firstInstrumentMethod:w}}(n,o,t),a=await p(s);return h(a,s),a}function h(e,t){const n=null!=t.earliestRunDate,o=null!=t.firstInstrumentMethod;(n||o)&&e.setTag("proteomics.spc_run_meta_seed",JSON.stringify({instrument_id:t.firstInstrumentMethod??"",acquisition_datetime:t.earliestRunDate??""}))}},691(e,t,n){"use strict";n.d(t,{F:()=>u,Y:()=>c});var o=n(328),r=n(82),s=n(749),a=n(641),i=n(304),l=n(771);const c="FORMULA_LINE_MISSING:";async function u(e,t){const n=e.id;o.shell.closeAll(),await(0,s.cb)(100);const u=await o.dapi.projects.find(n);await u.open(),await(0,s.bk)(()=>!!o.shell.tv&&!!o.shell.tv.dataFrame,"assertPublishedShape: TableView never materialized after project.open()",5e3);const m=o.shell.tv.dataFrame;if(m.name!==t.expectedName)throw new Error(`assertPublishedShape: df.name: got "${m.name}", expected "${t.expectedName}"`);if(u.name!==t.expectedProjectName)throw new Error(`assertPublishedShape: project.name: got "${u.name}", expected "${t.expectedProjectName}"`);for(const e of t.expectedAllowlist)if(!m.col(e))throw new Error(`assertPublishedShape: allowlist column missing on reopen: "${e}"`);const p=m.columns.toList().map(e=>e.name).filter(e=>!e.startsWith("_meta_")&&!e.startsWith("~"));if(p.length!==t.expectedAllowlist.length){const e=p.filter(e=>!t.expectedAllowlist.includes(e)),n=t.expectedAllowlist.filter(e=>!p.includes(e));throw new Error(`assertPublishedShape: visible column count: got ${p.length}, expected ${t.expectedAllowlist.length}. Unexpected: [${e.join(", ")}]. Missing: [${n.join(", ")}].`)}const d=(0,i.k)(m,a.iu.PROTEIN_ID,["protein id","majority protein id","accession"]);if(null==d)throw new Error("assertPublishedShape: protein-id column not found via findColumn");if(d.semType!==a.iu.PROTEIN_ID)throw new Error(`assertPublishedShape: protein-id semType: got "${d.semType??"null"}", expected "${a.iu.PROTEIN_ID}". Detectors may not have re-fired on reopen — re-assign in trim-dataframe.ts Step E.`);const f=(0,l.M4)(m);if(null==f)throw new Error("assertPublishedShape: getPublishedMetadata returned null — published flag not set or all critical fields unreadable");const g=t.expectedMeta,h=(e,t)=>!(Math.abs(e-t)>1e-9);if(f.target!==g.target)throw new Error(`assertPublishedShape: meta.target: got "${f.target}", expected "${g.target}"`);if(f.deMethod!==g.deMethod)throw new Error(`assertPublishedShape: meta.deMethod: got "${f.deMethod}", expected "${g.deMethod}"`);if(!h(f.fcThreshold,g.fcThreshold))throw new Error(`assertPublishedShape: meta.fcThreshold: got ${f.fcThreshold}, expected ${g.fcThreshold}`);if(!h(f.pThreshold,g.pThreshold))throw new Error(`assertPublishedShape: meta.pThreshold: got ${f.pThreshold}, expected ${g.pThreshold}`);if(f.version!==g.version)throw new Error(`assertPublishedShape: meta.version: got ${f.version}, expected ${g.version}`);if(f.publishId!==g.publishId)throw new Error(`assertPublishedShape: meta.publishId: got "${f.publishId}", expected "${g.publishId}"`);if(f.includesEnrichment!==g.includesEnrichment)throw new Error(`assertPublishedShape: meta.includesEnrichment: got ${f.includesEnrichment}, expected ${g.includesEnrichment}`);if(f.publishedBy!==g.publishedBy)throw new Error(`assertPublishedShape: meta.publishedBy: got "${f.publishedBy}", expected "${g.publishedBy}"`);for(const e of Object.keys(l.MD)){const t=l.MD[e];if(!m.col(t))throw new Error(`assertPublishedShape: metadata column missing: "${t}"`)}let y=null;if(t.expectVolcano)try{await(0,s.bk)(()=>{const e=o.shell.tv;if(!e)return!1;for(const t of e.viewers)if(t.type===r.VIEWER.SCATTER_PLOT)return y=t,!0;return!1},"assertPublishedShape: volcano scatter plot not present on reopen — consider post-open recomputeVolcano in publish-project.ts",5e3)}catch(e){throw new Error(`assertPublishedShape: volcano viewer assertion failed: ${e?.message??e}`)}if(t.expectVolcano&&t.expectFormulaLines&&null!=y){const e=String(g.fcThreshold),t=String(g.pThreshold),n=String(-Math.log10(g.pThreshold)),o=[];try{const e=m.meta?.formulaLines?.items??[];Array.isArray(e)&&o.push(...e)}catch{}try{const e=y.getOptions?.(),t=e?.look?.formulaLines,n="string"==typeof t?JSON.parse(t):t;Array.isArray(n)&&o.push(...n)}catch{}try{const e=y?.props?.formulaLines,t="string"==typeof e?JSON.parse(e):e;Array.isArray(t)&&o.push(...t)}catch{}const r=o.map(e=>"string"==typeof e?.formula?e.formula:"").filter(e=>e.length>0),s=r.some(t=>t.includes(e)||t.includes(`-${e}`)),a=r.some(e=>e.includes(n)||e.includes(t));if(!s||!a)throw new Error(`${c} volcano reopened without formula lines for FC=${g.fcThreshold} and/or p=${g.pThreshold}. The look/filter config was stripped by the serializer (Phase 13 e527d07ba1 evidence). Plan 04 step 8 catch should invoke the post-open recovery hook from tags ${l.L6.PUBLISHED_FC_THRESHOLD} / ${l.L6.PUBLISHED_P_THRESHOLD} and re-run this assertion once.`)}if(t.expectEnrichment){const e=o.shell.tables;if(!Array.isArray(e)||e.length<2)throw new Error(`assertPublishedShape: expectEnrichment=true but grok.shell.tables has ${e?.length??0} DataFrames (need ≥ 2)`);if(!e.find(e=>{try{const t=e.col(l.MD.PUBLISHED_INCLUDES_ENRICHMENT);return null!=t&&"true"===String(t.get(0))}catch{return!1}}))throw new Error("assertPublishedShape: protein DF (with _meta_published_includes_enrichment=true) not found among reopened tables");if(!e.find(e=>"true"===e.getTag("proteomics.enrichment")))throw new Error("assertPublishedShape: enrichment DF (proteomics.enrichment=true tag) not found among reopened tables")}const E=u.options??{};if(null!=g.supersedes){const e=E[l.L6.SUPERSEDES];if(e!==g.supersedes)throw new Error(`assertPublishedShape: project.options['${l.L6.SUPERSEDES}']: got "${e??"null"}", expected "${g.supersedes}"`)}if(null!=g.supersededBy){const e=E[l.L6.SUPERSEDED_BY];if(e!==g.supersededBy)throw new Error(`assertPublishedShape: project.options['${l.L6.SUPERSEDED_BY}']: got "${e??"null"}", expected "${g.supersededBy}"`)}}},649(e,t,n){"use strict";n.d(t,{I:()=>c});var o=n(328),r=n(82),s=n(771),a=n(807),i=n(897);const l="proteomics.enrichment_wired";async function c(e){if(!(0,s.HF)(e))return;const t=function(e){try{const t=o.shell.tableViews;if(Array.isArray(t)){const n=t.find(t=>t?.dataFrame===e);if(n)return n}}catch{}try{const t=o.shell.tv;if(t&&t.dataFrame===e)return t}catch{}return null}(e);if(t){const n=Array.from(t.viewers).find(e=>e.type===r.VIEWER.SCATTER_PLOT);if(n){const t=e.getTag(s.L6.PUBLISHED_FC_THRESHOLD),o=e.getTag(s.L6.PUBLISHED_P_THRESHOLD);if(t&&o){const r=parseFloat(t),s=parseFloat(o);if(Number.isFinite(r)&&Number.isFinite(s)&&!function(e,t){try{const t=e.meta?.formulaLines?.items??[];if(Array.isArray(t)&&t.length>0)return!0}catch{}try{const e=t.getOptions?.(),n=e?.look?.formulaLines;if("string"==typeof n&&""!==n&&"[]"!==n)return!0;if(Array.isArray(n)&&n.length>0)return!0}catch{}return!1}(e,n))try{(0,a.u)(n,r,s)}catch{}}}}const n=function(e){try{const t=o.shell.tables;return Array.isArray(t)?t.find(t=>t!==e&&"true"===t?.getTag?.("proteomics.enrichment")&&"true"===t?.getTag?.(s.L6.PUBLISHED))??null:null}catch{return null}}(e);if(n&&"true"!==n.getTag(l))try{(0,i.aB)(n,e),n.setTag(l,"true")}catch{}}},807(e,t,n){"use strict";n.d(t,{u:()=>f,M:()=>g});var o=n(328),r=n(82),s=n(749),a=n(771),i=n(641),l=n(304);function c(e,t){let n,o;switch(e.columns.contains(t.name)&&e.columns.remove(t.name),t.type){case"datetime":n=e.columns.addNewDateTime(t.name);break;case"float":n=e.columns.addNewFloat(t.name);break;case"int":n=e.columns.addNewInt(t.name);break;default:n=e.columns.addNewString(t.name)}if(null==t.value){if(!t.emptyForNull)return;o="string"===t.type?"":0}else o=t.value instanceof Date?t.value:"boolean"==typeof t.value?t.value?"true":"false":"string"===t.type?String(t.value):t.value;n.init(()=>o),n.setTag(".hidden","true")}var u=n(691),m=n(70),p=n(897),d=n(637);function f(e,t,n){const o=e.dataFrame;if(!o)return;let r=null;try{const t=e.getOptions?.();r=t?.look?.yColumnName??null}catch{}if(!r)try{r=e.props?.yColumnName??null}catch{}if(!r)return;const s=`\${${r}}`,a="${log2FC}",i=-Math.log10(n),l=o.meta,c=l?.formulaLines;if(c){try{const e=Array.isArray(c.items)?c.items:[];c.items=e.filter(e=>{const t=e?.formula??"";return!("string"==typeof t&&(t.startsWith(s)||t.startsWith(a)))})}catch{}try{c.addLine({formula:`${s} = ${i}`,color:"#888888",width:1,visible:!0}),c.addLine({formula:`${a} = ${t}`,color:"#888888",width:1,visible:!0}),c.addLine({formula:`${a} = ${-t}`,color:"#888888",width:1,visible:!0})}catch{}try{e.props.showViewerFormulaLines=!0}catch{}}}async function g(e,t){const n=r.TaskBarProgressIndicator.create("Publishing snapshot...");try{n.description="Preparing metadata...";const g=o.shell.user?.friendlyName??"",h=o.shell.user?.email??null,y=e.getTag("proteomics.de_method")??"t-test";let E=i.M5,w=i.Dx;try{const e=t;"number"==typeof e.fcThreshold&&Number.isFinite(e.fcThreshold)&&(E=e.fcThreshold),"number"==typeof e.pThreshold&&Number.isFinite(e.pThreshold)&&(w=e.pThreshold)}catch{}const v=(0,a.fz)(t.target),_=function(e){if(!e)return 0;const t=/-v(\d+)-/.exec(e);if(!t)return 0;const n=parseInt(t[1],10);return Number.isFinite(n)?n:0}(t.priorVersion?.name),C=_>0?_+1:1,b=function(){try{const e=globalThis?.crypto;if(e&&"function"==typeof e.randomUUID)return e.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}(),T=new Date,P=T.toISOString().slice(0,10),S=(()=>{const e=o.shell.tables;return Array.isArray(e)?e.find(e=>"true"===e.getTag("proteomics.enrichment"))??null:null})(),N={target:t.target,publishedAt:T,publishedBy:g,publishedByEmail:h,deMethod:y,fcThreshold:E,pThreshold:w,version:C,publishId:b,includesEnrichment:!!S,supersedes:t.priorVersion?.id??null,supersededBy:null};n.description="Trimming snapshot...";const A=function(e,t){const n=(0,l.I)(e),o=n.proteinId,r=n.geneName,s=n.log2fc,u=(0,l.k)(e,"",["adj.p-value","adj.p","fdr","q-value"]),m=e.columns.toList().find(e=>{const t=e.name.toLowerCase();return("p-value"===t||"pvalue"===t)&&e.name!==(u?.name??"")})??null,p=(0,l.k)(e,"",["significant","sig"]),d=(0,l.k)(e,"",["direction","regulation","up_down"]),f=[["Protein ID",o],["log2FC",s],["p-value",m],["adj.p-value",u],["significant",p]];for(const[e,t]of f)if(null==t)throw new Error(`Cannot publish: missing required column [${e}]. Run Differential Expression to completion before publishing.`);const g=Array.from(new Set([o.name,r?.name,s.name,m.name,u.name,p.name,d?.name].filter(e=>"string"==typeof e&&e.length>0))),h=e.clone(null,g),y=["proteomics.source","proteomics.de_method","proteomics.groups","proteomics.de_complete"];for(const t of y){const n=e.getTag(t);null!=n&&""!==n&&h.setTag(t,n)}(0,a.W7)(h,t);const E=t.publishedAt instanceof Date?t.publishedAt.toISOString().slice(0,10):new Date(String(t.publishedAt)).toISOString().slice(0,10);h.name=`${e.name||"analysis"}_published_${E}`;const w=[[o,i.iu.PROTEIN_ID],[r,i.iu.GENE_SYMBOL],[s,i.iu.LOG2FC],[m,i.iu.P_VALUE]];for(const[e,t]of w){if(null==e)continue;const n=h.col(e.name);null!=n&&(n.semType=t)}const v=t.includesEnrichment?"true":"false",_=[{name:a.MD.PUBLISHED,value:"true",type:"string"},{name:a.MD.PUBLISHED_AT,value:t.publishedAt,type:"datetime"},{name:a.MD.PUBLISHED_BY,value:t.publishedBy,type:"string"},{name:a.MD.PUBLISHED_BY_EMAIL,value:t.publishedByEmail??"",type:"string",emptyForNull:!0},{name:a.MD.PUBLISHED_TARGET,value:t.target,type:"string"},{name:a.MD.PUBLISHED_DE_METHOD,value:t.deMethod,type:"string"},{name:a.MD.PUBLISHED_FC_THRESHOLD,value:String(t.fcThreshold),type:"string"},{name:a.MD.PUBLISHED_P_THRESHOLD,value:String(t.pThreshold),type:"string"},{name:a.MD.PUBLISHED_VERSION,value:String(t.version),type:"string"},{name:a.MD.PUBLISHED_ID,value:t.publishId,type:"string"},{name:a.MD.PUBLISHED_INCLUDES_ENRICHMENT,value:v,type:"string"},{name:a.MD.SUPERSEDES,value:t.supersedes??"",type:"string",emptyForNull:!0},{name:a.MD.SUPERSEDED_BY,value:t.supersededBy??"",type:"string",emptyForNull:!0}];for(const e of _)c(h,e);return h}(e,N),x=A.name;let D=null;S&&(n.description="Trimming enrichment...",D=function(e,t){const n=(0,l.k)(e,"",["term name","term","pathway"]),o=(0,l.k)(e,"",["source"]),r=(0,l.k)(e,"",["fdr","adj.p-value","adj.p","q-value","p-value","pvalue"]),s=(0,l.k)(e,"",["intersection","genes"]),i=(0,l.k)(e,"",["direction","regulation"]),u=(0,l.k)(e,"",["gene ratio"]),m=(0,l.k)(e,"",["gene count"]),p=[["Term Name",n],["Source",o],["significance (FDR / adj.p-value)",r],["Intersection",s]];for(const[e,t]of p)if(null==t)throw new Error(`Cannot publish enrichment: missing required column [${e}]. Re-run enrichment before publishing.`);const d=[n.name,o.name,r.name,s.name,i?.name,u?.name,m?.name].filter(e=>"string"==typeof e&&e.length>0),f=e.clone(null,d);f.setTag("proteomics.enrichment","true");const g=t.publishedAt instanceof Date?t.publishedAt.toISOString().slice(0,10):new Date(String(t.publishedAt)).toISOString().slice(0,10);return f.name=`enrichment_published_${g}`,c(f,{name:a.MD.PUBLISHED_ID,value:t.publishId,type:"string"}),c(f,{name:a.MD.PUBLISHED_INCLUDES_ENRICHMENT,value:"true",type:"string"}),f.setTag(a.L6.PUBLISHED,"true"),f.setTag(a.L6.PUBLISHED_ID,t.publishId),f.setTag(a.L6.PUBLISHED_INCLUDES_ENRICHMENT,"true"),f}(S,N)),n.description="Ensuring umbrella Space...";const L=t.umbrellaName??(0,d.ck)(),F=o.dapi;let I=null;try{I=await F.spaces.createRootSpace(L)}catch(e){const t=String(e?.message??e??"");if(!/already exists|exists/i.test(t))throw e;try{I=(await F.spaces.list()??[]).find(e=>e?.name===L||e?.friendlyName===L)??null}catch{}if(!I)throw new Error(`Umbrella Space '${L}' exists on the server but could not be resolved by name from spaces.list() (msg: ${t}). Ask an admin to inspect the conflicting Space.`)}const M=F.spaces.id(I.id);n.description="Ensuring per-target Space...";const O=`${(0,d.sK)()}-${v}`;let R=null;const G=async()=>{try{return(await M.children.filter("Project",!1).list()??[]).find(e=>e?.friendlyName===O||e?.name===O)??null}catch{return null}};try{await M.subspaceExists(O)&&(R=await G())}catch{}if(!R)try{R=await M.addSubspace(O)}catch(e){const t=String(e?.message??e??"");if(!/already exists|exists/i.test(t))throw e;if(R=await G(),!R)throw new Error(`Per-target child Space '${O}' exists but could not be resolved via umbrella children.list() (msg: ${t}).`)}const k=F.spaces.id(R.id);n.description="Saving Project...";const $=r.Project.create(),B=`${(0,d.sK)()}-${v}-v${C}-${P}`;$.name=B,$.friendlyName=`${(0,d.sK)().replace(/-/g," ")} ${t.target} v${C} ${P}`;try{$.options[a.L6.PUBLISHED_ID]=b}catch{}if(null!=t.priorVersion)try{$.options[a.L6.SUPERSEDES]=t.priorVersion.id}catch{}$.addChild(A.getTableInfo()),D&&$.addChild(D.getTableInfo()),n.description="Re-rendering volcano on trimmed snapshot...";const U=o.shell.addTableView(A);await(0,s.cb)(100);const j=(0,m.gO)(A,{fcThreshold:E,pThreshold:w});U.addViewer(j),f(j,E,w),await(0,s.cb)(100);const V=U.getInfo();$.addChild(V);let q=null;if(D){n.description="Re-rendering enrichment charts...";const e=o.shell.addTableView(D);await(0,s.cb)(100),(0,p.YS)(e,D),await(0,s.cb)(100),q=e.getInfo(),$.addChild(q),o.shell.v=U}await o.dapi.tables.uploadDataFrame(A),await o.dapi.tables.save(A.getTableInfo()),D&&(await o.dapi.tables.uploadDataFrame(D),await o.dapi.tables.save(D.getTableInfo())),await o.dapi.views.save(V),q&&await o.dapi.views.save(q),await o.dapi.projects.save($);try{await k.addEntity($.id)}catch(e){o.shell.warning(`Could not move Project into child Space "${O}": ${e?.message??e}. Continuing — reviewer view grant is applied directly to the Project.`)}n.description="Granting reviewer view-only access...";try{await o.dapi.permissions.grant($,t.reviewerGroup,!1)}catch(e){try{await o.dapi.projects.delete($)}catch(e){o.shell.error(`Manual cleanup required: project id ${$.id} could not be deleted: ${e?.message??e}`)}throw new Error(`Reviewer group view grant failed: ${e?.message??e}`)}n.description="Verifying view-only access...";const Y=t.reviewerGroup?.id,z=e=>null!=e&&("string"==typeof e?e===Y:null!=e?.id&&e.id===Y),H=await o.dapi.permissions.get($);let Q=null,W=null;try{R&&(Q=await o.dapi.permissions.get(R))}catch{}try{I&&(W=await o.dapi.permissions.get(I))}catch{}const K=e=>{for(const t of[H,Q,W]){const n=t?.[e];if(Array.isArray(n)&&n.some(z))return!0}return!1},J=K("view"),Z=K("edit"),X=K("share"),ee=K("delete");if(!J||Z||X||ee){try{await o.dapi.projects.delete($)}catch(e){o.shell.error(`Manual cleanup required: project id ${$.id} could not be deleted: ${e?.message??e}`)}throw new Error("Reviewer group already has elevated access via Space inheritance — publish aborted; ask an admin to scope the umbrella Space's permissions")}if(t.verify??(0,d.Cb)()){n.description="Verifying round-trip survival...";const e={expectedName:x,expectedProjectName:B,expectedAllowlist:A.columns.toList().map(e=>e.name).filter(e=>!e.startsWith("_meta_")&&!e.startsWith("~")),expectedMeta:{...N},expectVolcano:!0,expectEnrichment:!!D,expectFormulaLines:!0};let t=!1;for(;;)try{await(0,u.F)($,e);break}catch(e){const n=String(e?.message??e??"");if(!t&&n.startsWith(u.Y)){t=!0;const e=o.shell.tv,n=e?Array.from(e.viewers).find(e=>e.type===r.VIEWER.SCATTER_PLOT):null;if(n&&e){const t=e.dataFrame,r=parseFloat(t.getTag(a.L6.PUBLISHED_FC_THRESHOLD)??String(E)),i=parseFloat(t.getTag(a.L6.PUBLISHED_P_THRESHOLD)??String(w));f(n,Number.isFinite(r)?r:E,Number.isFinite(i)?i:w);try{await o.dapi.views.save(e.getInfo())}catch{}await(0,s.cb)(100);continue}}try{await o.dapi.projects.delete($)}catch(e){o.shell.error(`Manual cleanup required: project id ${$.id} could not be deleted: ${e?.message??e}`)}throw new Error(`Round-trip shape verification failed: ${e?.message??e}`)}}if(null!=t.priorVersion){n.description="Updating supersede chain...";const e=t.priorVersion.id;try{const t=await o.dapi.projects.find(e);t.options[a.L6.SUPERSEDED_BY]=$.id,await o.dapi.projects.save(t)}catch(e){o.shell.warning(`Supersede pointer on prior version's options failed: ${e?.message??e} (DataFrame-tag dual-write path below provides fallback).`)}try{o.shell.closeAll(),await(0,s.cb)(100);const t=await o.dapi.projects.find(e);await t.open(),await(0,s.bk)(()=>!!o.shell.tv&&!!o.shell.tv.dataFrame,"supersede stamp: prior project DF did not materialize",5e3);const n=o.shell.tv.dataFrame;n.setTag(a.L6.SUPERSEDED_BY,$.id);const r=n.col(a.MD.SUPERSEDED_BY);if(r)try{r.set(0,$.id)}catch{}await o.dapi.tables.uploadDataFrame(n),await o.dapi.tables.save(n.getTableInfo())}catch(e){o.shell.warning(`Supersede tag could not be stamped on prior version DF: ${e?.message??e} (Project.options pointer was still written — Plan 06 panel falls back to that path)`)}try{$.options[a.L6.SUPERSEDES]=e}catch{}try{await o.dapi.projects.save($)}catch(e){o.shell.warning(`Could not write supersedes pointer on new project options: ${e?.message??e}`)}}n.description="Restoring your analysis...";try{if(o.shell.closeAll(),await(0,s.cb)(100),S)try{(0,p.q6)(S,e)}catch{}const t=o.shell.addTableView(e);try{t.addViewer((0,m.gO)(e))}catch{}}catch{}return n.description="Done.",$}finally{n.close()}}},637(e,t,n){"use strict";n.d(t,{Cb:()=>i,ck:()=>s,sK:()=>a});var o=n(110);function r(e,t){try{const t=o._package?.settings?.[e];if("string"==typeof t&&t.trim().length>0)return t.trim()}catch{}return t}function s(){return r("reviewSpaceName","Proteomics-Reviews")}function a(){return r("reviewNamePrefix","Proteomics-Review")}function i(){try{const e=o._package?.settings?.verifyPublishedDashboard;if(!1===e||"false"===e)return!1;if(!0===e||"true"===e)return!0}catch{}return!0}},771(e,t,n){"use strict";n.d(t,{$y:()=>s,HF:()=>l,Kj:()=>d,L6:()=>a,M4:()=>c,MD:()=>i,T7:()=>p,W7:()=>u,fz:()=>m});var o=n(328),r=n(637);const s="proteomics.de_complete",a={PUBLISHED:"proteomics.published",PUBLISHED_AT:"proteomics.published_at",PUBLISHED_BY:"proteomics.published_by",PUBLISHED_BY_EMAIL:"proteomics.published_by_email",PUBLISHED_TARGET:"proteomics.published_target",PUBLISHED_DE_METHOD:"proteomics.published_de_method",PUBLISHED_FC_THRESHOLD:"proteomics.published_fc_threshold",PUBLISHED_P_THRESHOLD:"proteomics.published_p_threshold",PUBLISHED_VERSION:"proteomics.published_version",PUBLISHED_ID:"proteomics.published_id",PUBLISHED_INCLUDES_ENRICHMENT:"proteomics.published_includes_enrichment",SUPERSEDED_BY:"proteomics.superseded_by",SUPERSEDES:"proteomics.supersedes"},i={PUBLISHED:"_meta_published",PUBLISHED_AT:"_meta_published_at",PUBLISHED_BY:"_meta_published_by",PUBLISHED_BY_EMAIL:"_meta_published_by_email",PUBLISHED_TARGET:"_meta_published_target",PUBLISHED_DE_METHOD:"_meta_published_de_method",PUBLISHED_FC_THRESHOLD:"_meta_published_fc_threshold",PUBLISHED_P_THRESHOLD:"_meta_published_p_threshold",PUBLISHED_VERSION:"_meta_published_version",PUBLISHED_ID:"_meta_published_id",PUBLISHED_INCLUDES_ENRICHMENT:"_meta_published_includes_enrichment",SUPERSEDED_BY:"_meta_superseded_by",SUPERSEDES:"_meta_supersedes"};function l(e){return"true"===e.getTag(a.PUBLISHED)}function c(e){if(!l(e))return null;const t=(t,n)=>{try{const n=e.col(i[t]);if(null!=n){const e=n.get(0);if(null!=e&&""!==e)return String(e)}}catch{}try{return e.getTag(a[n])??null}catch{return null}},n=(e,n)=>{const o=t(e,n);if(null==o)return NaN;const r=parseFloat(o);return Number.isFinite(r)?r:NaN},o=t("PUBLISHED_TARGET","PUBLISHED_TARGET"),r=t("PUBLISHED_ID","PUBLISHED_ID");if(null==o||null==r)return null;const s=(()=>{try{const t=e.col(i.PUBLISHED_AT);if(null!=t){const e=t.get(0);if(e instanceof Date)return e;if("string"==typeof e&&e)return new Date(e);if("number"==typeof e)return new Date(e)}}catch{}try{const t=e.getTag(a.PUBLISHED_AT);if(t)return new Date(t)}catch{}return null})(),c=t("PUBLISHED_VERSION","PUBLISHED_VERSION"),u=null!=c?parseInt(c,10):NaN;return{target:o,publishedAt:s??new Date(NaN),publishedBy:t("PUBLISHED_BY","PUBLISHED_BY")??"",publishedByEmail:t("PUBLISHED_BY_EMAIL","PUBLISHED_BY_EMAIL"),deMethod:t("PUBLISHED_DE_METHOD","PUBLISHED_DE_METHOD")??"",fcThreshold:n("PUBLISHED_FC_THRESHOLD","PUBLISHED_FC_THRESHOLD"),pThreshold:n("PUBLISHED_P_THRESHOLD","PUBLISHED_P_THRESHOLD"),version:Number.isFinite(u)?u:1,publishId:r,includesEnrichment:"true"===t("PUBLISHED_INCLUDES_ENRICHMENT","PUBLISHED_INCLUDES_ENRICHMENT"),supersedes:t("SUPERSEDES","SUPERSEDES"),supersededBy:t("SUPERSEDED_BY","SUPERSEDED_BY")}}function u(e,t){e.setTag(a.PUBLISHED,"true"),e.setTag(a.PUBLISHED_AT,t.publishedAt instanceof Date?t.publishedAt.toISOString():String(t.publishedAt)),e.setTag(a.PUBLISHED_BY,t.publishedBy),null!=t.publishedByEmail&&e.setTag(a.PUBLISHED_BY_EMAIL,t.publishedByEmail),e.setTag(a.PUBLISHED_TARGET,t.target),e.setTag(a.PUBLISHED_DE_METHOD,t.deMethod),e.setTag(a.PUBLISHED_FC_THRESHOLD,String(t.fcThreshold)),e.setTag(a.PUBLISHED_P_THRESHOLD,String(t.pThreshold)),e.setTag(a.PUBLISHED_VERSION,String(t.version)),e.setTag(a.PUBLISHED_ID,t.publishId),e.setTag(a.PUBLISHED_INCLUDES_ENRICHMENT,t.includesEnrichment?"true":"false"),null!=t.supersedes&&e.setTag(a.SUPERSEDES,t.supersedes),null!=t.supersededBy&&e.setTag(a.SUPERSEDED_BY,t.supersededBy)}function m(e){if(null==e)return"unnamed";let t=String(e).replace(/[^A-Za-z0-9._-]+/g,"-").replace(/-{2,}/g,"-").replace(/^[-.]+|[-.]+$/g,"").slice(0,64).replace(/[-.]+$/g,"");return 0===t.length&&(t="unnamed"),t}async function p(e,t){const n=m(e),s=`${(0,r.sK)()}-${n}-v`,a=/-v(\d+)-/,i=e=>{let t=null,n=-1;for(const o of e){const e=o?.name??"",r=a.exec(e);if(!r)continue;const s=parseInt(r[1],10);Number.isFinite(s)&&s>n&&(n=s,t=o)}return t};try{const e=`${s}%`,t=await o.dapi.projects.filter(`name like "${e}"`).list();if(Array.isArray(t)&&t.length>0)return i(t)}catch{}try{const e=await o.dapi.projects.list(),t=(Array.isArray(e)?e:[]).filter(e=>(e?.name??"").startsWith(s));if(t.length>0)return i(t)}catch{}return null}function d(e){const t=`Re-run request: ${e.projectName}`,n=`Hi ${e.sharerName}, could you re-run with [different parameters]? Looking at ${e.projectName} (shared ${e.publishedDateStr}).`;return`mailto:${e.sharerEmail?encodeURIComponent(e.sharerEmail):""}?subject=${encodeURIComponent(t)}&body=${encodeURIComponent(n)}`}},304(e,t,n){"use strict";n.d(t,{I:()=>s,k:()=>r});var o=n(641);function r(e,t,n){const o=e.columns.toList().find(e=>e.semType===t);if(o)return o;for(const t of n){const n=t.toLowerCase(),o=e.columns.toList().find(e=>e.name.toLowerCase().includes(n));if(o)return o}return null}function s(e){return{proteinId:r(e,o.iu.PROTEIN_ID,["protein id","majority protein id","accession","uniprot"]),geneName:r(e,o.iu.GENE_SYMBOL,["gene name","gene symbol"]),log2fc:r(e,o.iu.LOG2FC,["log2fc","log2 fold","logfc"]),pValue:r(e,o.iu.P_VALUE,["p-value","pvalue","adj.p","fdr","q-value"])}}},117(e,t,n){"use strict";n.d(t,{FH:()=>h,I5:()=>i,KK:()=>g,Rw:()=>l,eA:()=>d,no:()=>p,oA:()=>m,qo:()=>f,rv:()=>E});var o=n(328),r=n(304),s=n(641),a=n(623);const i="proteomics-gene-labels",l="14-r1-1",c="__schema_v",u=["ENSRNOG","ENSMUSG","LOC","ENSG","ENSDARG","ENSRNO","MGP_","RGD","AABR"];function m(e){return e.startsWith("ENS")||e.startsWith("MGP_")}function p(e){for(const t of u)if(e.startsWith(t))return!0;return!1}function d(e){return e.startsWith("ENSG")?"homo_sapiens":e.startsWith("ENSMUSG")||e.startsWith("MGP_")?"mus_musculus":e.startsWith("ENSRNOG")||e.startsWith("ENSRNO")?"rattus_norvegicus":e.startsWith("ENSDARG")?"danio_rerio":null}function f(e){if(null==e||""===e)return null;let t=String(e);t=t.split("[")[0].trim(),t=t.replace(/^Predicted to enable\s+/i,""),t=t.replace(/^Predicted to be involved in\s+/i,""),t=t.replace(/^Predicted to be located in\s+/i,""),t=t.replace(/^Predicted to be part of\s+/i,""),t=t.replace(/^Predicted to be\s+/i,""),t=t.replace(/^Predicted to\s+/i,"");const n=t.split(".");return n.length>0&&(t=n[0].trim()),t=t.replace(/_RAT$/i,""),t=t.replace(/_MOUSE$/i,""),t=t.replace(/_HUMAN$/i,""),t.length>0&&t[0]===t[0].toLowerCase()&&t[0]!==t[0].toUpperCase()&&(t=t[0].toUpperCase()+t.slice(1)),t.length>60&&(t=t.slice(0,57)+"..."),""===t||t.length<3||t.toLowerCase().includes("uncharacterized")?null:t}function g(e,t,n){return e+(t?"*":"")+(n?"†":"")}async function h(e){const t=new Map;if(0===e.length)return t;const n=async()=>o.dapi.fetchProxy("https://rest.ensembl.org/lookup/id",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({ids:e})});let r,s;try{r=await n()}catch(e){return console.warn(`Ensembl lookup/id batch failed (network): ${e?.message??e}`),t}if(429===r.status){const e=parseFloat(r.headers.get("Retry-After")??"1"),o=Math.min(3e4,Math.max(0,1e3*e));await new Promise(e=>setTimeout(e,o));try{r=await n()}catch(e){return console.warn(`Ensembl lookup/id retry failed: ${e?.message??e}`),t}}if(!r.ok)return console.warn(`Ensembl lookup/id returned status ${r.status}; continuing`),t;try{s=await r.json()}catch(e){return console.warn(`Ensembl lookup/id JSON parse failed: ${e?.message??e}`),t}if(s&&"object"==typeof s)for(const[e,n]of Object.entries(s))if(n&&"object"==typeof n){const o=n,r={};"string"==typeof o.display_name&&(r.display_name=o.display_name),"string"==typeof o.external_name&&(r.external_name=o.external_name),"string"==typeof o.description&&(r.description=o.description),"string"==typeof o.species&&(r.species=o.species),"string"==typeof o.biotype&&(r.biotype=o.biotype),"string"==typeof o.object_type&&(r.object_type=o.object_type),t.set(e,r)}return t}function y(e,t){if(!t)return null;const n=[t.external_name,t.display_name,t.description?t.description.split("[")[0].trim():void 0];for(const t of n)if(t&&t!==e&&!p(t))return t;return null}async function E(e,t){const n=(0,r.k)(e,s.iu.GENE_SYMBOL,["gene name","gene names","gene symbol"]),u=e.rowCount,d=new Array(u).fill(""),E=new Array(u).fill("");if(null!=n)for(let e=0;e<u;e++){const t=n.get(e),o=null==t?"":String(t);d[e]=o}const w=(0,r.k)(e,s.iu.PROTEIN_ID,["protein ids","primary protein id","protein id","majority protein ids","accession","uniprot"]),v=[],_=(e,t,n)=>{if(!t)return!1;const o=t.includes("*"),r=t.replace(/[*†]/g,"");return!!p(r)&&(v.push({row:e,clean:r,hadAsterisk:o,source:n}),!0)};for(let e=0;e<u;e++){const t=null!=n?n.get(e):null;if(!_(e,null==t?"":String(t),"gene")&&null!=w){const t=w.get(e);_(e,null==t?"":String(t).split(";")[0],"protein")}}for(const t of["Display Name","Source ID"])null!=e.col(t)&&e.columns.remove(t);if(0===v.length){const t=e.columns.addNewString("Display Name");t.init(e=>d[e]),t.semType=s.iu.DISPLAY_NAME;const n=e.columns.addNewString("Source ID");return n.init(e=>E[e]),void(n.semType=s.iu.SOURCE_ID)}const C=[...new Set(v.map(e=>e.clean))].filter(e=>m(e)),b=await async function(){try{const e=await o.dapi.userDataStorage.get(i)??{};return e[c]!==l?{[c]:l}:e}catch{return{[c]:l}}}(),T={},P=new Map;for(const e of C){const t=b[e];t&&"object"==typeof t&&P.set(e,t)}const S=C.filter(e=>!P.has(e));let N=!1;if(S.length>0){const e=function(e){const t=[];for(let n=0;n<e.length;n+=1e3)t.push(e.slice(n,n+1e3));return t}(S),n=e.length;let r=0;try{await(0,a.Pd)(e,6,async e=>{const o=await h(e);for(const[e,t]of o)P.set(e,t),T[e]=t;for(const t of e)o.has(t)||(N=!0);r++,t?.(r,n,"lookup")})}finally{await async function(e,t){try{await o.dapi.userDataStorage.put(i,{...e,...t,[c]:l})}catch(e){console.warn(`Gene-label cache write failed: ${e?.message??e}`)}}(b,T)}}const A=e.col("Protein Descriptions")??e.col("Protein names")??e.col("Description")??e.col("protein_descriptions");for(const e of v){const t=P.get(e.clean);let n=y(e.clean,t);if(null==n&&null!=t){const o=f(t.description??null);null==o||o===e.clean||p(o)||(n=o)}if(null==n&&null!=A){const t=A.get(e.row),o=f(null==t?null:String(t));null!=o&&o!==e.clean&&!p(o)&&o.length>3&&(n=o)}const o=g(n??e.clean,e.hadAsterisk,!0);d[e.row]=o,E[e.row]=e.clean}t?.(v.length,v.length,"apply");const x=new Map,D=new Map;for(let e=0;e<u;e++){const t=d[e],n=E[e];t&&n&&(x.has(t)||x.set(t,new Set),x.get(t).add(n),D.has(t)||D.set(t,[]),D.get(t).push(e))}let L=0;for(const[e,t]of x)if(!(t.size<=1))for(const t of D.get(e)??[]){const n=E[t];n&&(d[t]=`${e} (${n})`,L++)}if(L>0&&o.shell.warning(`${L} duplicate gene names disambiguated with source IDs.`),N){const e=v.filter(e=>m(e.clean)&&!P.has(e.clean)).length;o.shell.warning(`Ensembl gene-label resolution unavailable. Showing raw IDs (${e} unresolved). Re-import to retry.`)}const F=e.columns.addNewString("Display Name");F.init(e=>d[e]),F.semType=s.iu.DISPLAY_NAME;const I=e.columns.addNewString("Source ID");I.init(e=>E[e]),I.semType=s.iu.SOURCE_ID}},935(e,t,n){"use strict";n.d(t,{$S:()=>a,Ae:()=>o,Vr:()=>c,X3:()=>s,qj:()=>i});const o=[{display:"Homo sapiens (Human)",code:"hsapiens"},{display:"Mus musculus (Mouse)",code:"mmusculus"},{display:"Rattus norvegicus (Rat)",code:"rnorvegicus"},{display:"Saccharomyces cerevisiae (Yeast)",code:"scerevisiae"},{display:"Escherichia coli (K12)",code:"ecoli"},{display:"Danio rerio (Zebrafish)",code:"drerio"},{display:"Drosophila melanogaster (Fruit fly)",code:"dmelanogaster"},{display:"Arabidopsis thaliana",code:"athaliana"},{display:"Caenorhabditis elegans",code:"celegans"}],r=o.map(e=>({scientific:e.display.split("(")[0].trim().toLowerCase(),code:e.code}));function s(e){return o.find(t=>t.code===e)?.display}function a(e){return o.find(t=>t.display===e)?.code}function i(e){if(!e)return;const t=e.toLowerCase();for(const{scientific:e,code:n}of r)if(t.includes(e))return n}const l=["pg.organisms","organism","organisms","species"];function c(e){const t=function(e){for(const t of e.columns.toList()){const e=t.name.toLowerCase();if(l.some(t=>e===t||e.includes(t)))return t}return null}(e);if(!t)return;const n=new Set;for(let e=0;e<t.length;e++){if(t.isNone(e))continue;const o=i(t.get(e));if(o&&n.add(o),n.size>1)return}return 1===n.size?[...n][0]:void 0}},641(e,t,n){"use strict";n.d(t,{Dx:()=>s,M5:()=>r,PL:()=>a,iu:()=>o});const o={PROTEIN_ID:"Proteomics-ProteinId",GENE_SYMBOL:"Proteomics-GeneSymbol",LOG2FC:"Proteomics-Log2FC",P_VALUE:"Proteomics-PValue",INTENSITY:"Proteomics-Intensity",SUBCELLULAR_LOCATION:"Proteomics-SubcellularLocation",DISPLAY_NAME:"Proteomics-DisplayName",SOURCE_ID:"Proteomics-SourceId",NUMERATOR_MEAN:"Proteomics-NumeratorMean",DENOMINATOR_MEAN:"Proteomics-DenominatorMean"},r=1,s=.05,a={enrichedG1:4294902015,enrichedG2:4278255615,notSig:4289374890}},897(e,t,n){"use strict";n.d(t,{$i:()=>m,E0:()=>p,YS:()=>w,aB:()=>h,bC:()=>u,q6:()=>E});var o=n(328),r=n(389),s=n(82),a=n(858),i=n(304),l=n(641);let c=[];const u="negLog10FDR",m="~enrichChartTop";function p(e,t=15){const n=e.col("FDR");if(!n)return;const o=-Math.log10(Number.MIN_VALUE),r=n.getRawData();e.columns.contains(u)&&e.columns.remove(u);const s=e.columns.addNewFloat(u);s.init(e=>r[e]>0?-Math.log10(r[e]):o),s.setTag(".hidden","true");const a=e.col("Direction"),i=new Map;for(let t=0;t<e.rowCount;t++){if(n.isNone(t))continue;const e=a?String(a.get(t)):"";i.has(e)||i.set(e,[]),i.get(e).push({idx:t,fdr:n.get(t)})}const l=new Array(e.rowCount).fill(!1);for(const e of i.values()){e.sort((e,t)=>e.fdr-t.fdr);for(let n=0;n<Math.min(t,e.length);n++)l[e[n].idx]=!0}e.columns.contains(m)&&e.columns.remove(m),e.columns.addNewBool(m).init(e=>l[e])}function d(e){const t=[`\${${m}}`];return e&&t.push(`\${Direction} == "${e}"`),t.join(" and ")}function f(e,t){return s.Viewer.scatterPlot(e,{x:"Gene Ratio",y:"Term Name",sizeColumnName:"Gene Count",colorColumnName:u,markerMinSize:5,markerMaxSize:25,filter:d(t),title:t?`Enrichment — ${t}`:"Enrichment Dot Plot"})}function g(e,t){return s.Viewer.barChart(e,{splitColumnName:"Term Name",valueColumnName:u,valueAggrType:"avg",barSortType:"by value",barSortOrder:"desc",orientation:"Horizontal",filter:d(t),title:t?`Top Enriched — ${t}`:"Top Enriched Terms"})}function h(e,t){const n=(0,i.k)(t,l.iu.GENE_SYMBOL,["gene name","gene symbol"]);if(!n)return a.Subscription.EMPTY;const o=new Map;for(let e=0;e<t.rowCount;e++)if(!n.isNone(e)){const t=n.get(e).trim();o.has(t)||o.set(t,[]),o.get(t).push(e)}return e.onCurrentRowChanged.subscribe(()=>{const n=e.currentRowIdx;if(n<0)return;const r=e.col("Intersection");if(!r)return;const s=r.get(n);if(!s)return;const a=s.split(",").map(e=>e.trim()).filter(Boolean);t.selection.setAll(!1,!1);for(const e of a){const n=o.get(e);if(n)for(const e of n)t.selection.set(e,!0,!1)}t.selection.fireChanged()})}function y(e,t){const n=e.col("Direction");if(!n)return!1;for(let o=0;o<e.rowCount;o++)if(n.get(o)===t)return!0;return!1}function E(e,t){for(const e of c)e.unsubscribe();let n;c=[];for(const t of o.shell.tableViews)if(t.dataFrame?.dart===e.dart){n=t;break}const a=n??o.shell.addTableView(e);o.shell.v=a;const i=a;if("true"===e.getTag("proteomics.enrichment_smart_filtered")){const t=e.getTag("proteomics.enrichment_smart_filtered_kept")??"?",n=e.getTag("proteomics.enrichment_smart_filtered_total")??"?",o=e.getTag("proteomics.enrichment_smart_filtered_dropped_parents")??"?",i=e.getTag("proteomics.enrichment_smart_filtered_cap")??"15",l=r.divText(`Smart pathway filter active: showing ${t} of ${n} terms (dropped ${o} generic parents, capped at ${i} per source). Re-run with the filter off to see all.`);l.dataset.smartFilterBanner="true",a.dockManager.dock(l,s.DOCK_TYPE.TOP,null,"Smart Filter Info",.1)}return w(i,e),c.push(h(e,t)),a}function w(e,t){if(p(t),y(t,"Up")&&y(t,"Down")){const n=e.dockManager.dock(f(t,"Up"),s.DOCK_TYPE.RIGHT,null,"Up — Dot Plot",.6),o=e.dockManager.dock(f(t,"Down"),s.DOCK_TYPE.RIGHT,n,"Down — Dot Plot",.5);return e.dockManager.dock(g(t,"Up"),s.DOCK_TYPE.DOWN,n,"Up — Bar Chart",.5),void e.dockManager.dock(g(t,"Down"),s.DOCK_TYPE.DOWN,o,"Down — Bar Chart",.5)}const n=e.dockManager.dock(f(t),s.DOCK_TYPE.RIGHT,null,"Dot Plot",.5);e.dockManager.dock(g(t),s.DOCK_TYPE.DOWN,n,"Bar Chart",.5)}},644(e,t,n){"use strict";n.d(t,{CN:()=>g,Z7:()=>h,hy:()=>p,nc:()=>d});var o=n(82),r=n(304),s=n(641),a=n(252);const i="Numerator Mean",l="Denominator Mean",c=`\${${i}} = \${${l}}`;function u(e,t){return e.columns.contains(t)&&e.columns.remove(t),e.columns.addNewFloat(t)}function m(e,t){let n=0,o=0;for(const r of e)r.isNone(t)||(n+=r.get(t),o++);return o>0?n/o:NaN}function p(e,t){const n=t.group1.columns.map(t=>e.col(t)).filter(e=>null!=e),r=t.group2.columns.map(t=>e.col(t)).filter(e=>null!=e),a=e.rowCount,c=new Float32Array(a),p=new Float32Array(a);for(let e=0;e<a;e++){const t=m(n,e),s=m(r,e);c[e]=isNaN(t)?o.FLOAT_NULL:t,p[e]=isNaN(s)?o.FLOAT_NULL:s}const d=u(e,i);d.init(e=>c[e]),d.semType=s.iu.NUMERATOR_MEAN;const f=u(e,l);f.init(e=>p[e]),f.semType=s.iu.DENOMINATOR_MEAN}function d(e,t){let n=0,r=0,s=0;for(let a=0;a<e.length;a++){const i=e[a],l=t[a];Number.isFinite(i)&&Number.isFinite(l)&&i!==o.FLOAT_NULL&&l!==o.FLOAT_NULL&&(r+=i,s+=l,n++)}if(0===n)return NaN;const a=r/n,i=s/n;let l=0,c=0,u=0;for(let n=0;n<e.length;n++){const r=e[n],s=t[n];if(!Number.isFinite(r)||!Number.isFinite(s)||r===o.FLOAT_NULL||s===o.FLOAT_NULL)continue;const m=r-a,p=s-i;l+=m*p,c+=m*m,u+=p*p}const m=Math.sqrt(c*u);return 0===m?NaN:l/m}function f(e){const t=e.map((e,t)=>({v:e,i:t}));t.sort((e,t)=>e.v-t.v);const n=new Array(e.length);let o=0;for(;o<t.length;){let e=o;for(;e+1<t.length&&t[e+1].v===t[o].v;)e++;const r=(o+e)/2+1;for(let s=o;s<=e;s++)n[t[s].i]=r;o=e+1}return n}function g(e,t){return d(f(e),f(t))}function h(e,t){const n=(0,a.f)(e);if(!n)throw new Error("Annotate experimental groups first (Proteomics | Annotate Experiment)");p(e,n);const u=e.plot.scatter({x:i,y:l,color:"direction"}),m=(0,r.k)(e,s.iu.DISPLAY_NAME,["display name"])??(0,r.k)(e,s.iu.GENE_SYMBOL,["gene name","gene symbol"]);m&&(u.props.labelColumnNames=[m.name],u.props.showLabelsFor="MouseOverRow"),e.meta.formulaLines.items=e.meta.formulaLines.items.filter(e=>{const t=e.formula??"";return!("string"==typeof t&&t.includes(i)&&t.includes(l))}),e.meta.formulaLines.addLine({formula:c,color:"#888888",width:1,visible:!0}),u.props.showViewerFormulaLines=!0;const{r:f,rho:h}=function(e,t,n){const r=e.col(t),s=e.col(n);if(!r||!s)return{r:NaN,rho:NaN};const a=r.getRawData(),i=s.getRawData(),l=[],c=[];for(let t=0;t<e.rowCount;t++){if(!e.filter.get(t))continue;const n=a[t],r=i[t];n!==o.FLOAT_NULL&&r!==o.FLOAT_NULL&&Number.isFinite(n)&&Number.isFinite(r)&&(l.push(n),c.push(r))}return{r:d(l,c),rho:g(l,c)}}(e,i,l),y=t?.title??"Group-Mean Correlation",E=Number.isFinite(f)?f.toFixed(2):"NA",w=Number.isFinite(h)?h.toFixed(2):"NA";return u.setOptions({title:`${y} — r=${E} (Pearson), ρ=${w} (Spearman)`,xColumnLabel:`${n.group1.name} mean (log2 intensity)`,yColumnLabel:`${n.group2.name} mean (log2 intensity)`}),u}},715(e,t,n){"use strict";n.d(t,{Hc:()=>a,JZ:()=>m,Pq:()=>u,ho:()=>p,iQ:()=>c,j4:()=>d,rA:()=>f});var o=n(82),r=n(641),s=n(304);function a(e){return e.columns.toList().filter(e=>e.semType===r.iu.INTENSITY&&e.name.startsWith("log2(")).map(e=>e.name)}function i(e,t){let n=0,o=0;for(const r of e)r.isNone(t)||(n+=r.get(t),o++);return o>0?n/o:NaN}function l(e,t){return e.columns.contains(t)&&e.columns.remove(t),e.columns.addNewFloat(t)}function c(e,t){const n=t.group1.columns.map(t=>e.col(t)),r=t.group2.columns.map(t=>e.col(t)),s=e.rowCount,a=new Float32Array(s),c=new Float32Array(s);for(let e=0;e<s;e++){const t=i(n,e),s=i(r,e);isNaN(t)||isNaN(s)?(a[e]=o.FLOAT_NULL,c[e]=o.FLOAT_NULL):(a[e]=s-t,c[e]=(t+s)/2)}l(e,"M").init(e=>a[e]),l(e,"A").init(e=>c[e])}function u(e,t=.1){const n=e.col("A"),r=e.col("M");if(!n||!r)return void l(e,"MA_trend");const s=n.getRawData(),a=r.getRawData(),i=[];for(let t=0;t<e.rowCount;t++)s[t]!==o.FLOAT_NULL&&a[t]!==o.FLOAT_NULL&&i.push({idx:t,a:s[t],m:a[t]});const c=new Float32Array(e.rowCount);if(c.fill(o.FLOAT_NULL),i.length<3)return void l(e,"MA_trend").init(e=>c[e]);i.sort((e,t)=>e.a-t.a);const u=Math.max(Math.round(i.length*t/2),5);for(let e=0;e<i.length;e++){const t=Math.max(0,e-u),n=Math.min(i.length-1,e+u);let o=0,r=0;for(let e=t;e<=n;e++)o+=i[e].m,r++;c[i[e].idx]=o/r}l(e,"MA_trend").init(e=>c[e])}function m(e,t,n,r){const s=t.map(t=>e.col(t)).filter(e=>null!=e&&e.type===o.COLUMN_TYPE.FLOAT).map(e=>e.getRawData()),a=e.rowCount,i=new Float32Array(a),c=new Float32Array(a);for(let e=0;e<a;e++){let t=0,n=0,r=0;for(const a of s){const s=a[e];if(s!==o.FLOAT_NULL){const e=Math.pow(2,s);t++;const o=e-n;n+=o/t,r+=o*(e-n)}}if(t<1)i[e]=o.FLOAT_NULL,c[e]=o.FLOAT_NULL;else if(t<2)i[e]=o.FLOAT_NULL,c[e]=n;else{const s=r/(t-1),a=Math.sqrt(Math.max(0,s));i[e]=n>0?a/n:o.FLOAT_NULL,c[e]=n}}l(e,n).init(e=>i[e]),l(e,r).init(e=>c[e])}function p(e,t){const n=[],a=(0,s.k)(e,r.iu.PROTEIN_ID,["protein id","accession"]);a&&n.push(a.clone());for(const r of t){const t=e.col(r),s=t.type===o.COLUMN_TYPE.FLOAT?t.getRawData():null,a=new Int32Array(e.rowCount);if(s)for(let t=0;t<e.rowCount;t++)a[t]=s[t]===o.FLOAT_NULL?0:1;else for(let n=0;n<e.rowCount;n++)a[n]=t.isNone(n)?0:1;n.push(o.Column.fromInt32Array(r,a))}const i=o.DataFrame.fromColumns(n);return i.name="Missing Values",i}function d(e,t){const n=(0,s.k)(e,r.iu.PROTEIN_ID,["protein id","accession"]),a=[],i=[],l=[];for(let o=0;o<e.rowCount;o++){const r=n?n.get(o)??String(o):String(o);for(const n of t){const t=e.col(n);t.isNone(o)||(a.push(r),i.push(n),l.push(t.get(o)))}}const c=o.DataFrame.fromColumns([o.Column.fromStrings("ProteinId",a),o.Column.fromStrings("Sample",i),o.Column.fromFloat32Array("Intensity",new Float32Array(l))]);return c.name="Intensity Distributions",c}function f(e,t,n){const r=[],s=[],a=[],i=new Set(n.group1.columns),l=new Set(n.group2.columns);for(const o of t){const t=e.col(o);let c=0;for(let n=0;n<e.rowCount;n++)t.isNone(n)&&c++;r.push(o),s.push(c/e.rowCount*100),i.has(o)?a.push(n.group1.name):l.has(o)?a.push(n.group2.name):a.push("Other")}const c=o.DataFrame.fromColumns([o.Column.fromStrings("Sample",r),o.Column.fromFloat32Array("MissingPct",new Float32Array(s)),o.Column.fromStrings("Group",a)]);return c.name="Missing Values per Sample",c}},589(e,t,n){"use strict";n.d(t,{aggregateParetoCounts:()=>E,computeControlLines:()=>g,createSpcChartPanel:()=>y,r9:()=>C,resolveDrillDown:()=>h});var o=n(328),r=n(389),s=n(82),a=n(655),i=n(883);const l=["median_intensity","missing_pct","control_corr","protein_count"],c={median_intensity:"Median log2 intensity",missing_pct:"Missing %",control_corr:"Control replicate correlation",protein_count:"Protein count"},u="#888888",m="#666666",p="spc.last_picked_instrument",d={rule_1_only:"Expected false-alarm rate at this rule set: ~0.27%. (Rule 1 only — a point beyond 3σ.)",rules_1_5:"Expected false-alarm rate at this rule set: ~0.4%. (Rules 1 + 5 — a single point beyond 3σ, or 2 of 3 beyond 2σ.)",rules_1_5_2:"Enabling rules 1+5+2 raises the expected false-alarm rate to ~1.1%.",rules_all_8:"Expected false-alarm rate at this rule set: ~2.65%. Enabling all 8 rules will flag roughly 1 in 38 normal-operation runs.",rules_other:"More rules enabled → higher false-alarm rate. The Nelson 1+5 default is calibrated for ~0.4%."};function f(e){const t=e.median_intensity,n=Object.entries(t).filter(([e,t])=>t).map(([e])=>e).sort();return 1===n.length&&"nelson_1"===n[0]?"rule_1_only":2===n.length&&"nelson_1"===n[0]&&"nelson_5"===n[1]?"rules_1_5":3===n.length&&n.includes("nelson_1")&&n.includes("nelson_5")&&n.includes("nelson_2")?"rules_1_5_2":8===n.length?"rules_all_8":"rules_other"}function g(e,t){if(!e)return{ucl:NaN,cl:NaN,lcl:NaN};const n=e.metrics[t];return n&&Number.isFinite(n.mean)&&Number.isFinite(n.sd)?{ucl:n.mean+3*n.sd,cl:n.mean,lcl:n.mean-3*n.sd}:{ucl:NaN,cl:NaN,lcl:NaN}}async function h(e,t){if(null==e.source_project_id)return{kind:"toast",message:`Source for '${e.run_label}' is not currently available. Open the run's analyzed file and re-run Compute SPC Status.`};const n=await t.projectsFind(e.source_project_id);return n?(await n.open(),{kind:"opened",id:e.source_project_id}):{kind:"toast",message:`Source for '${e.run_label}' is not currently available. Open the run's analyzed file and re-run Compute SPC Status.`}}function y(e,t,n){const o=s.Viewer.lineChart(e,{xColumnName:"acquisition_datetime",yColumnNames:[n],title:c[n]});if(t){const e=g(t,n);if(Number.isFinite(e.cl)){const t=o?.meta?.formulaLines;if(t&&"function"==typeof t.addLine)try{t.addLine({formula:`\${${n}} = ${e.ucl}`,color:m,width:1,style:"dashed",visible:!0,title:"UCL"}),t.addLine({formula:`\${${n}} = ${e.cl}`,color:u,width:1,style:"solid",visible:!0,title:"CL"}),t.addLine({formula:`\${${n}} = ${e.lcl}`,color:m,width:1,style:"dashed",visible:!0,title:"LCL"})}catch(e){}}}const r=`MR_${n}`,i=s.Viewer.lineChart(e,{xColumnName:"acquisition_datetime",yColumnNames:[r],title:`MR ${c[n]}`});if(t&&e.col(r)){const t=e.col(r);let n=0,o=0;for(let r=0;r<e.rowCount;r++){if(t.isNone(r))continue;const e=Number(t.get(r));Number.isFinite(e)&&(n+=e,o++)}if(o>0){const e=n/o,t=a.Mj*e,s=i?.meta?.formulaLines;if(s&&"function"==typeof s.addLine)try{s.addLine({formula:`\${${r}} = ${t}`,color:m,width:1,style:"dashed",visible:!0,title:"MR UCL"}),s.addLine({formula:`\${${r}} = ${e}`,color:u,width:1,style:"solid",visible:!0,title:"MR CL"})}catch(e){}}}return{iChart:o,mrChart:i}}function E(e){const t=new Map;for(const n of e){const e=Array.isArray(n.rules_tripped)?n.rules_tripped:[];for(const n of e){const e=t.get(n)??0;t.set(n,e+1)}}const n=[];for(const[e,o]of t.entries()){const t=e.indexOf("@");t<0?n.push({rule:e,metric:"",count:o}):n.push({rule:e.slice(0,t),metric:e.slice(t+1),count:o})}return n.sort((e,t)=>t.count-e.count),n}function w(e){switch(e){case"nelson_1":return"Nelson rule 1: a single point beyond 3σ from the centerline.";case"nelson_2":return"Nelson rule 2: 9 consecutive points on the same side of the centerline.";case"nelson_3":return"Nelson rule 3: 6 consecutive points all trending up, or all trending down.";case"nelson_4":return"Nelson rule 4: 14 consecutive points alternating above and below the centerline.";case"nelson_5":return"Nelson rule 5: 2 out of 3 consecutive points beyond 2σ on the same side.";case"nelson_6":return"Nelson rule 6: 4 out of 5 consecutive points beyond 1σ on the same side.";case"nelson_7":return"Nelson rule 7: 15 consecutive points within 1σ of the centerline (unusually stable).";case"nelson_8":return"Nelson rule 8: 8 consecutive points more than 1σ from the centerline on either side."}}function v(e,t){const n=e.rowCount;if(0===n)return;const o={median_intensity:e.col("median_intensity"),missing_pct:e.col("missing_pct"),control_corr:e.col("control_corr"),protein_count:e.col("protein_count")},r=e.col("status"),s=e.col("rules_tripped");if(r&&s){for(let e=0;e<n;e++){const n={median_intensity:Number(o.median_intensity?.get(e)),missing_pct:Number(o.missing_pct?.get(e)),control_corr:Number(o.control_corr?.get(e)),protein_count:Number(o.protein_count?.get(e)),sample_count:0,computed_at:""},i={median_intensity:[],missing_pct:[],control_corr:[],protein_count:[]};for(let t=0;t<e;t++)i.median_intensity.push(Number(o.median_intensity?.get(t))),i.missing_pct.push(Number(o.missing_pct?.get(t))),i.control_corr.push(Number(o.control_corr?.get(t))),i.protein_count.push(Number(o.protein_count?.get(t)));const l=(0,a.uV)(n,i,t.metrics,t.rules_enabled);r.set(e,l.status),s.set(e,JSON.stringify(l.rulesTripped))}a.classifyStatus}}function _(e,t,n,s){const u=!!s,m=u?`Rebuild baseline for ${e}`:`Lock baseline for ${e}`,p=t.slice().sort((e,t)=>e.acquisition_datetime.localeCompare(t.acquisition_datetime)),g=new Set;if(u)for(const e of s.included_run_ids)g.add(e);else{const e=Math.min(7,p.length);for(let t=0;t<e;t++)g.add(p[t].run_id)}const h=[],y=r.divV([]);y.style.maxHeight="300px",y.style.overflowY="auto";for(const e of p){const t=r.input.bool("",{value:g.has(e.run_id)});h.push({run:e,input:t}),y.appendChild(r.divH([t.root,r.divText(e.acquisition_datetime.slice(0,10)),r.divText(e.run_label)]))}const E=r.input.bool("Iterate 3σ outlier removal (recommended)",{value:!u||s.iteration_trace.length>0,tooltipText:"When on, runs more than 3 standard deviations from the baseline mean are dropped from the baseline. Capped at 2 passes."}),v=s?.rules_enabled??(0,a.kY)(),_=["nelson_1","nelson_2","nelson_3","nelson_4","nelson_5","nelson_6","nelson_7","nelson_8"],C={median_intensity:{},missing_pct:{},control_corr:{},protein_count:{}},b=[r.divH([r.divText(""),..._.map(e=>r.divText(e.replace("nelson_","R")))])],T=r.divText(d[f(v)]);for(const e of l){const t=[r.divText(c[e])];for(const n of _){const o=r.input.bool("",{value:v[e][n],tooltipText:w(n)});o.onChanged.subscribe(()=>{const e=P();T.textContent=d[f(e)]}),C[e][n]=o,t.push(o.root)}b.push(r.divH(t))}function P(){const e={};for(const t of l){e[t]={};for(const n of _)e[t][n]=!!C[t][n].value}return e}const S=[];u?S.push(r.divText(`This replaces the locked baseline from ${s.locked_at}. The previous baseline is not kept.`)):S.push(r.divText("Pick the runs that represent normal operation:")),S.push(y),S.push(E.root),S.push(r.h2("Nelson rules")),S.push(r.divV(b)),S.push(T);const N=r.dialog(m);for(const e of S)N.add(e);N.onOK(async()=>{const t=h.filter(e=>!0===e.input.value).map(e=>e.run);if(t.length<3)return void o.shell.warning("At least 3 runs must remain after outlier removal — too few to compute a baseline.");const r=new Set,s=[];if(E.value)for(const e of l){const n=t.map(t=>({run_id:t.run_id,value:t[e]})),o=(0,i.oF)(n,2);for(const e of o.excluded_run_ids)r.add(e);for(const e of o.iteration_trace)s.push(e)}const a=t.filter(e=>!r.has(e.run_id));if(a.length<3)return void o.shell.warning("At least 3 runs must remain after outlier removal — too few to compute a baseline.");const c=(0,i.OI)(a),m={instrument_id:e,locked_at:(new Date).toISOString(),included_run_ids:a.map(e=>e.run_id),excluded_run_ids:Array.from(r),iteration_trace:s,metrics:c,rules_enabled:P()};await n(m),u?o.shell.info(`Baseline rebuilt for ${e}: ${a.length} runs included, ${r.size} excluded. Previous baseline replaced.`):o.shell.info(`Baseline locked for ${e}: ${a.length} runs included, ${r.size} excluded.`)}),N.show()}async function C(){const e=await(0,i.loadRuns)();if(0===e.length)return void o.shell.warning("No SPC runs recorded yet. Open an analyzed file, then run Analyze → Compute SPC Status. The dashboard turns on once at least 4 runs have been computed.");const t=Array.from(new Set(e.map(e=>e.instrument_id))),n=await o.dapi.userDataStorage.get(p),u=n&&n.instrument_id||t[0],m=new Map;for(const e of t)m.set(e,await(0,i.loadBaseline)(e));const g=t.map(e=>m.get(e)?`${e} (baseline locked)`:`${e} (no baseline)`),C=new Map;for(let e=0;e<t.length;e++)C.set(g[e],t[e]);const b=g[t.indexOf(u)]??g[0],T=r.input.choice("Instrument",{value:b,items:g,nullable:!1,tooltipText:"Switches the trend charts and baseline to a different instrument. Only instruments with computed SPC runs are listed."});r.dialog("SPC Dashboard").add(T).onOK(async()=>{const e=C.get(String(T.value))??t[0];await o.dapi.userDataStorage.put(p,{instrument_id:e}),await async function(e){const t=await(0,i.loadRuns)(e);let n;n=0===t.length?s.DataFrame.create(0):(0,i.$G)(t),n.name=`SPC — ${e}`,function(e){for(const t of l){const n=e.col(t);if(!n)continue;const o=`MR_${t}`;e.columns.contains(o)&&e.columns.remove(o);const r=e.columns.addNewFloat(o),s=e.rowCount;let a=null;for(let e=0;e<s;e++){if(0===e){r.set(e,null),a=null;continue}if(n.isNone(e)||n.isNone(e-1)){r.set(e,null);continue}const t=Number(n.get(e)),o=Number(n.get(e-1));Number.isFinite(t)&&Number.isFinite(o)?(r.set(e,Math.abs(t-o)),a=t):r.set(e,null)}}}(n);const u=o.shell.addTableView(n);let m=await(0,i.loadBaseline)(e);const p=()=>{for(const e of l){const{iChart:t,mrChart:o}=y(n,m,e);u.dockManager.dock(t,s.DOCK_TYPE.RIGHT,null,`I-chart ${c[e]}`,.5),u.dockManager.dock(o,s.DOCK_TYPE.DOWN,null,`MR-chart ${c[e]}`,.5)}const t=function(e,t){if(e.rowCount<4)return null;const n=e.col("rules_tripped");if(!n)return null;const o=e.rowCount,r=[];for(let e=0;e<o;e++){const t=String(n.get(e)??"");let o=[];if(t.length>0)try{o=JSON.parse(t)}catch{o=[]}r.push({rules_tripped:o})}const a=E(r);if(0===a.length)return null;const i=s.Column.fromStrings("rule_metric",a.map(e=>e.metric?`${e.rule}@${e.metric}`:e.rule)),l=new Int32Array(a.map(e=>e.count)),c=new Int32Array(a.map(()=>o)),u=new Float32Array(a.map(e=>e.count/o*100)),m=s.DataFrame.fromColumns([i,s.Column.fromInt32Array("trip_count",l),s.Column.fromInt32Array("total_runs",c),s.Column.fromFloat32Array("pct",u)]),p=s.Viewer.barChart(m,{splitColumnName:"rule_metric",valueColumnName:"trip_count",title:`Which rules trip most often — ${t}`});try{p.props.xLabel="(rule, metric)",p.props.yLabel="Times tripped"}catch(e){}return p}(n,e);if(null!==t)u.dockManager.dock(t,s.DOCK_TYPE.DOWN,null,"Pareto",.3);else{const e=r.divV([r.divText("Pareto chart appears once 4 or more runs have been recorded for this instrument.")]);u.dockManager.dock(e,s.DOCK_TYPE.DOWN,null,"Pareto",.3)}},g=function(e,t,n,o){const s=r.h2(`Instrument: ${e}`);let i;i=t?r.divV([r.divText(`Baseline locked: ${t.locked_at}`),r.divText(`${t.included_run_ids.length} runs included · ${t.excluded_run_ids.length} runs excluded (3σ outlier).`),r.button("Rebuild baseline...",n)]):r.divV([r.divText("No baseline locked yet. The dashboard turns on once a baseline exists.")]);const u=["nelson_1","nelson_2","nelson_3","nelson_4","nelson_5","nelson_6","nelson_7","nelson_8"],m=t?.rules_enabled??(0,a.kY)(),p=r.divText(d[f(m)]),g=[];g.push(r.divH([r.divText(""),...u.map(e=>r.divText(e.replace("nelson_","R")))]));for(const e of l){const t=[r.divText(c[e])];for(const n of u){const s=r.input.bool("",{value:m[e][n],tooltipText:w(n)});s.onChanged.subscribe(async t=>{await o(e,n,!!t)}),t.push(s.root)}g.push(r.divH(t))}return{el:r.divV([s,i,r.h2("Nelson rules"),r.divV(g),p]),setDisclosure:e=>{p.textContent=e}}}(e,m,()=>{_(e,t,async t=>{await(0,i.saveBaseline)(e,t),m=t,v(n,t),p()},m??void 0)},async(t,o,r)=>{m&&(m.rules_enabled[t][o]=r,await(0,i.saveBaseline)(e,m),v(n,m))});if(u.dockManager.dock(g.el,s.DOCK_TYPE.LEFT,null,"SPC Controls",.25),null===m){const o=r.divV([r.h2(`No baseline locked for ${e}.`),r.divText("Pick the runs that represent normal operation, then click Lock baseline. The dashboard turns on once a baseline exists."),r.button("Define baseline...",()=>{_(e,t,async t=>{await(0,i.saveBaseline)(e,t),m=t,v(n,t),p()})})]);u.dockManager.dock(o,s.DOCK_TYPE.RIGHT,null,"Baseline",.75)}else p();!function(e,t){e.dataFrame.onCurrentRowChanged.subscribe(async()=>{const e=t.currentRowIdx;if(e<0)return;const n=String(t.col("status")?.get(e)??"");if("flagged"!==n&&"out_of_control"!==n)return;const r=t.col("source_project_id")?.get(e),s=null==r||""===r?null:String(r),a=await h({run_id:String(t.col("run_id")?.get(e)??""),run_label:String(t.col("run_label")?.get(e)??""),source_project_id:s},{projectsFind:async e=>{const t=await o.dapi.projects.find(e);return t?{open:()=>t.open()}:null}});"toast"===a.kind&&o.shell.warning(a.message)})}(u,n)}(e)}).show()}},70(e,t,n){"use strict";n.d(t,{Bb:()=>A,CK:()=>w,DI:()=>N,EO:()=>v,GE:()=>M,MC:()=>C,PL:()=>i.PL,S6:()=>O,XC:()=>k,bX:()=>D,f0:()=>R,fQ:()=>f,gO:()=>$,j9:()=>g,kX:()=>x,m2:()=>G,nj:()=>B,ur:()=>P});var o=n(82),r=n(389),s=n(713),a=n(304),i=n(641),l=n(498),c=n(252),u=n(623);const m=-Math.log10(Number.MIN_VALUE),p="negLog10P",d="direction",f="Subcellular Location",g="proteomics.volcano_metric";let h=[];const y="proteomics-volcano";function E(e,t){if("p-value"===t){const t=e.col("p-value");if(t)return t}const n=e.col("adj.p-value");if(!n)throw new Error("adj.p-value column not found");return n}function w(e,t="adj.p-value"){const n=E(e,t);return(e.col(p)??e.columns.addNewFloat(p)).init(e=>{if(n.isNone(e))return o.FLOAT_NULL;const t=n.get(e);return t>0?-Math.log10(t):m}),p}function v(e,t,n,o="adj.p-value"){const r=e.col("log2FC");if(!r)throw new Error("log2FC column not found");const s=E(e,o),a=(0,c.f)(e),l=a?`Enriched in ${a.group1.name}`:"Enriched in group1",u=a?`Enriched in ${a.group2.name}`:"Enriched in group2",m="Not significant",p=e.rowCount,f=new Array(p);for(let e=0;e<p;e++){if(r.isNone(e)||s.isNone(e)){f[e]=m;continue}const o=r.get(e),a=s.get(e);f[e]=a<=n&&o>t?l:a<=n&&o<-t?u:m}const g=e.col(d)??e.columns.addNewString(d);return g.init(e=>f[e]),g.meta.colors.setCategorical({[l]:i.PL.enrichedG1,[u]:i.PL.enrichedG2,[m]:i.PL.notSig}),d}const _="proteomics.location_acc_hash";async function C(e,t){const n=(0,a.k)(e,i.iu.PROTEIN_ID,["primary protein id","protein id","protein ids","accession","uniprot"])??e.col("Primary Protein ID")??e.col("Protein ID"),o=e.rowCount,r=new Array(o).fill(null),s=new Set;if(n)for(let e=0;e<o;e++){const t=n.get(e),o=t?(0,l.S6)(t):null;r[e]=o,o&&s.add(o)}const m=function(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=t+((t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24))>>>0;return t.toString(16).padStart(8,"0")}([...s].sort().join("|")),p=e.col(f);if(p&&p.getTag(_)===m)return t?.(1,1,"init-column"),f;const d=await(0,u.n0)([...s],(0,c.Di)(e),t),g=new Array(o);for(let e=0;e<o;e++){const t=r[e];g[e]=t&&d.get(t)||"Unknown"}const h=p??e.columns.addNewString(f);return h.init(e=>g[e]),h.meta.colors.setCategorical(u.Jn),h.semType=i.iu.SUBCELLULAR_LOCATION,h.setTag(_,m),t?.(1,1,"init-column"),f}function b(e,t,n,o){const r=-Math.log10(o),s=`\${${t}}`,a="${log2FC}";e.meta.formulaLines.items=e.meta.formulaLines.items.filter(e=>{const t=e.formula??"";return!("string"==typeof t&&(t.startsWith(s)||t.startsWith(a)))}),e.meta.formulaLines.addLine({formula:`${s} = ${r}`,color:"#888888",width:1,visible:!0}),e.meta.formulaLines.addLine({formula:`${a} = ${n}`,color:"#888888",width:1,visible:!0}),e.meta.formulaLines.addLine({formula:`${a} = ${-n}`,color:"#888888",width:1,visible:!0})}function T(e){return"p-value"===e?"-Log10(p-value)":"-Log10(Q-value)"}function P(e,t){const n=t.getOptions(),o=(n?.look??{}).colorColumnName===f?"location":"significance";return{metric:e.getTag(g)??"adj.p-value",colorDim:o}}function S(e,t){const n=e.root.querySelector("[data-volcano-axis-y]");if(n){const e=t.getTag(g);n.textContent=T(e)}}function N(e,t){x(e);const n=e.root;n.style.position=n.style.position||"relative";const o=r.divV([]);o.dataset.volcanoBusy="true",Object.assign(o.style,{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",padding:"12px 20px",background:"rgba(255,255,255,0.95)",border:"1px solid #ccc",borderRadius:"6px",boxShadow:"0 2px 8px rgba(0,0,0,0.15)",fontSize:"0.95em",textAlign:"center",pointerEvents:"none",zIndex:"6",maxWidth:"320px"});const s=r.divText(t);s.style.fontWeight="bold",s.style.marginBottom="4px";const a=r.divText("");a.style.fontSize="0.85em",a.style.color="#666",o.appendChild(s),o.appendChild(a),n.appendChild(o)}function A(e,t,n){const o=e.root.querySelector("[data-volcano-busy]");if(!o)return;const[r,s]=Array.from(o.children);r&&(r.textContent=t),s&&(s.textContent=n??"")}function x(e){e.root.querySelectorAll("[data-volcano-busy]").forEach(e=>e.remove())}const D="~Volcano label",L="proteomics.volcano_top_n",F="proteomics.volcano_x_max",I="proteomics.volcano_y_max";function M(e){const t=t=>{const n=parseFloat(e.getTag(t)??"");return Number.isFinite(n)&&n>0?n:null};return{xMax:t(F),yMax:t(I)}}function O(e,t,n){const o=(t,n)=>e.setTag(t,null!=n&&Number.isFinite(n)&&n>0?String(n):"");o(F,t),o(I,n)}function R(e,t){const{xMax:n,yMax:o}=M(t);if(null!=n)e.props.xMin=-n,e.props.xMax=n;else{const n=t.col("log2FC");if(null!=n&&Number.isFinite(n.min)&&Number.isFinite(n.max)){const t=Math.max(.05*(n.max-n.min),1e-6);e.props.xMin=n.min-t,e.props.xMax=n.max+t}}if(null!=o)e.props.yMin=0,e.props.yMax=o;else{const n=t.col(p);null!=n&&Number.isFinite(n.max)&&(e.props.yMin=0,e.props.yMax=1.05*n.max+1e-6)}}function G(e){const t=parseInt(e.getTag(L)??"",10);return Number.isFinite(t)&&t>=0?t:15}function k(e,t,n=15,r){e.setTag(L,String(n));const s=function(e){return(0,a.k)(e,i.iu.DISPLAY_NAME,["display name"])??(0,a.k)(e,i.iu.GENE_SYMBOL,["gene name","gene symbol"])}(e);if(!s)return;const l=e.col(D)??e.columns.addNewString(D),c=new Set(function(e,t){if(t<=0)return[];const n=e.col(p),r=e.col("log2FC");if(!n||!r)return[];const s=n.getRawData(),a=r.getRawData(),i=[];for(let t=0;t<e.rowCount;t++)e.filter.get(t)&&s[t]!==o.FLOAT_NULL&&a[t]!==o.FLOAT_NULL&&i.push(t);return i.sort((e,t)=>{const n=s[t]-s[e];return 0!==n?n:Math.abs(a[t])-Math.abs(a[e])}),i.slice(0,t)}(e,n));if(r)for(const e of r)c.add(e);l.init(e=>c.has(e)?String(s.get(e)??""):""),t.props.labelColumnNames=[D],t.props.showLabelsFor="All"}function $(e,t){const n=t?.fcThreshold??i.M5,o=t?.pThreshold??i.Dx;!function(){for(const e of h)e.unsubscribe();h=[]}();const a=e.getTag(g)??"adj.p-value";e.setTag(g,a);const l=w(e,a),u=v(e,n,o,a),m=e.plot.scatter({x:"log2FC",y:l,color:u});b(e,l,n,o),m.props.showViewerFormulaLines=!0,function(){const e="proteomics-volcano-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent=`.${y} .d4-column-selector.d4-vertical,.${y} .d4-column-selector.d4-bottom-center{display:none !important;}`,document.head.appendChild(t)}(),m.root.classList.add(y);const p=t?.title??function(e){const t=(0,c.f)(e);return t?`Volcano Plot: ${t.group1.name} vs ${t.group2.name}`:"Volcano Plot"}(e);return m.setOptions({title:p}),function(e,t){const n=e.root;n.style.position=n.style.position||"relative";const o=r.divText("Log2 Fold Change");o.dataset.volcanoAxisX="true",Object.assign(o.style,{position:"absolute",bottom:"4px",left:"50%",transform:"translateX(-50%)",fontSize:"0.85em",pointerEvents:"none",background:"rgba(255,255,255,0.7)",padding:"0 4px",zIndex:"4"}),n.appendChild(o);const a=t.getTag(g),i=r.divText(T(a));i.dataset.volcanoAxisY="true",Object.assign(i.style,{position:"absolute",left:"4px",top:"50%",transform:"translateY(-50%) rotate(-90deg)",transformOrigin:"left center",fontSize:"0.85em",pointerEvents:"none",background:"rgba(255,255,255,0.7)",padding:"0 4px",zIndex:"4"}),n.appendChild(i),h.push(e.onPropertyValueChanged.pipe((0,s.debounceTime)(50)).subscribe(()=>S(e,t)))}(m,e),function(e,t){const n=e.root;n.style.position=n.style.position||"relative";const o=r.divV([]);o.dataset.volcanoCounter="true",Object.assign(o.style,{position:"absolute",bottom:"8px",right:"8px",padding:"8px 16px",background:"rgba(255,255,255,0.85)",borderRadius:"4px",fontSize:"0.9em",pointerEvents:"none",zIndex:"5"}),n.appendChild(o);const a=()=>{const n=t.filter.trueCount,s=e.props.colorColumnName,a=s?t.col(s):null,i=new Map;let l=!1;if(a&&(s===d||s===f)){l=!0;for(const e of a.categories)i.set(e,0);for(let e=0;e<t.rowCount;e++){if(!t.filter.get(e))continue;if(a.isNone(e))continue;const n=a.get(e);i.set(n,(i.get(n)??0)+1)}}o.replaceChildren();const c=r.divText("Visible Proteins");if(c.style.fontWeight="bold",o.appendChild(c),o.appendChild(r.divText(`Total: ${n.toLocaleString()}`)),l)for(const[e,t]of i)o.appendChild(r.divText(`${e}: ${t.toLocaleString()}`))};a(),h.push(t.onFilterChanged.pipe((0,s.debounceTime)(50)).subscribe(a),t.onSelectionChanged.pipe((0,s.debounceTime)(50)).subscribe(a),e.onPropertyValueChanged.pipe((0,s.debounceTime)(50)).subscribe(a))}(m,e),R(m,e),k(e,m,t?.topNLabels??15),m}async function B(e,t,n,o,r=i.M5,s=i.Dx,a){e.setTag(g,n);const l=w(e,n),c=v(e,r,s,n);b(e,l,r,s),t.props.xColumnName="log2FC",t.props.yColumnName=l,t.props.colorColumnName="location"===o?await C(e,a):c,S(t,e),R(t,e)}},82(e){"use strict";e.exports=DG},328(e){"use strict";e.exports=grok},858(e){"use strict";e.exports=rxjs},713(e){"use strict";e.exports=rxjs.operators},389(e){"use strict";e.exports=ui}},t={};function n(o){var r=t[o];if(void 0!==r)return r.exports;var s=t[o]={exports:{}};return e[o].call(s.exports,s,s.exports,n),s.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var o in t)n.o(t,o)&&!n.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var o={};(()=>{"use strict";n.r(o),n.d(o,{_package:()=>je,initAutoTests:()=>qe,test:()=>Ve,tests:()=>t.CN});var e=n(82),t=n(749),r=n(312),s=n(641);function a(e,t){return[t.join("\t"),...e.map(e=>e.join("\t"))].join("\n")}const i=["Protein IDs","Majority protein IDs","Gene names","Potential contaminant","Reverse","Only identified by site","LFQ intensity Sample1","LFQ intensity Sample2","iBAQ"];(0,t.L1)("Parsers",()=>{(0,t.t6)("MaxQuant: filters contaminant rows",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"],["P99999","P99999","TP53","+","","","3000","4000","600"]],i),n=await(0,r.E)(e);(0,t.E3)(n.rowCount,1)}),(0,t.t6)("MaxQuant: filters reverse rows",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"],["P99999","P99999","TP53","","+","","3000","4000","600"]],i),n=await(0,r.E)(e);(0,t.E3)(n.rowCount,1)}),(0,t.t6)("MaxQuant: filters only-by-site rows",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"],["P99999","P99999","TP53","","","+","3000","4000","600"]],i),n=await(0,r.E)(e);(0,t.E3)(n.rowCount,1)}),(0,t.t6)("MaxQuant: filters CON__ prefix rows",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"],["CON__P99999","CON__P99999","KRT1","","","","3000","4000","600"]],i),n=await(0,r.E)(e);(0,t.E3)(n.rowCount,1)}),(0,t.t6)("MaxQuant: filters REV__ prefix rows",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"],["REV__P99999","REV__P99999","TP53","","","","3000","4000","600"]],i),n=await(0,r.E)(e);(0,t.E3)(n.rowCount,1)}),(0,t.t6)("MaxQuant: detects LFQ intensity columns",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"]],i),n=await(0,r.E)(e);(0,t.E3)(null!==n.col("LFQ intensity Sample1"),!0),(0,t.E3)(null!==n.col("log2(LFQ intensity Sample1)"),!0),(0,t.E3)(null!==n.col("log2(LFQ intensity Sample2)"),!0)}),(0,t.t6)("MaxQuant: log2 transforms intensity values correctly",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1024","2048","500"]],i),n=(await(0,r.E)(e)).col("log2(LFQ intensity Sample1)");(0,t.E3)(null!==n,!0),n&&(0,t.E3)(Math.abs(n.get(0)-10)<.001,!0)}),(0,t.t6)("MaxQuant: zero intensity produces FLOAT_NULL in log2",async()=>{const e=a([["P12345","P12345","BRCA1","","","","0","2048","500"]],i),n=(await(0,r.E)(e)).col("log2(LFQ intensity Sample1)");(0,t.E3)(null!==n,!0),n&&(0,t.E3)(n.isNone(0),!0)}),(0,t.t6)("MaxQuant: assigns semantic types",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"]],i),n=await(0,r.E)(e);(0,t.E3)(n.col("Protein IDs")?.semType,s.iu.PROTEIN_ID),(0,t.E3)(n.col("Gene names")?.semType,s.iu.GENE_SYMBOL),(0,t.E3)(n.col("LFQ intensity Sample1")?.semType,s.iu.INTENSITY),(0,t.E3)(n.col("log2(LFQ intensity Sample1)")?.semType,s.iu.INTENSITY)}),(0,t.t6)("MaxQuant: parses primary protein ID from semicolon-delimited",async()=>{const e=a([["P12345;Q67890;R11111","P12345","BRCA1;BRCA2","","","","1000","2000","500"]],i),n=await(0,r.E)(e),o=n.col("Primary Protein ID");(0,t.E3)(null!==o,!0),o&&(0,t.E3)(o.get(0),"P12345");const s=n.col("Primary Gene Name");(0,t.E3)(null!==s,!0),s&&(0,t.E3)(s.get(0),"BRCA1")}),(0,t.t6)("MaxQuant: no contaminant IDs remain after filtering",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"],["P22222","P22222","TP53","","","","3000","4000","600"],["CON__P99999","CON__P99999","KRT1","+","","","5000","6000","700"],["REV__P88888","REV__P88888","FAKE1","","+","","7000","8000","800"],["P77777","P77777","FAKE2","","","+","9000","1000","900"]],i),n=await(0,r.E)(e);(0,t.E3)(n.rowCount,2);const o=n.col("Protein IDs");for(let e=0;e<n.rowCount;e++){const t=o.get(e);if(t.startsWith("CON__")||t.startsWith("REV__"))throw new Error(`Found filtered ID in output: ${t}`)}}),(0,t.t6)("MaxQuant: assigns intensity semantic type to log2 columns",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"]],i),n=await(0,r.E)(e);(0,t.E3)(n.col("log2(LFQ intensity Sample1)")?.semType,s.iu.INTENSITY),(0,t.E3)(n.col("log2(LFQ intensity Sample2)")?.semType,s.iu.INTENSITY),(0,t.E3)(n.col("log2(iBAQ)")?.semType,s.iu.INTENSITY)}),(0,t.t6)("MaxQuant: handles MQ 2.x dot column names",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000"],["P99999","P99999","TP53","+","","","3000"]],["Protein IDs","Majority protein IDs","Gene names","Potential.contaminant","Reverse","Only.identified.by.site","LFQ intensity Sample1"]),n=await(0,r.E)(e);(0,t.E3)(n.rowCount,1)}),(0,t.t6)("MaxQuant: parser tags proteomics.source",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"]],i),n=await(0,r.E)(e);(0,t.E3)(n.getTag("proteomics.source"),"maxquant")}),(0,t.t6)("MaxQuant: iBAQ columns detected as intensity",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"]],i),n=await(0,r.E)(e);(0,t.E3)(n.col("iBAQ")?.semType,s.iu.INTENSITY),(0,t.E3)(null!==n.col("log2(iBAQ)"),!0)})});var l=n(252),c=n(350),u=n(47),m=n(829);function p(t,n,o,r,a){const i=[];i.push(e.Column.fromStrings("Protein ID",Array.from({length:t},(e,t)=>`P${t}`)));const l=[...n,...o],c=r&&a?[...r,...a]:void 0;for(let n=0;n<l.length;n++){const o=new Float32Array(t);if(c&&c[n])for(let e=0;e<t;e++)o[e]=c[n][e];const r=e.Column.fromFloat32Array(l[n],o);r.semType=s.iu.INTENSITY,i.push(r)}return e.DataFrame.fromColumns(i)}(0,t.L1)("Experiment Setup",()=>{(0,t.t6)("setGroups persists group assignments as tag",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0"]),e.Column.fromFloat32Array("s1",new Float32Array([1]))]);(0,l.$Y)(n,{group1:{name:"Control",columns:["s1"]},group2:{name:"Treatment",columns:["s2"]}});const o=n.getTag("proteomics.groups");(0,t.E3)(null!==o&&""!==o,!0);const r=JSON.parse(o);(0,t.E3)(r.group1.name,"Control"),(0,t.E3)(r.group2.name,"Treatment")}),(0,t.t6)("getGroups returns null for untagged DataFrame",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0"])]),o=(0,l.f)(n);(0,t.E3)(o,null)}),(0,t.t6)("getOrganism returns undefined until set, then round-trips the code",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0"])]);(0,t.E3)(void 0===(0,l.Di)(n),!0),(0,l.Np)(n,"rnorvegicus"),(0,t.E3)((0,l.Di)(n),"rnorvegicus")}),(0,t.t6)("applyAnnotation persists the organism alongside the groups",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0"])]);(0,l.applyAnnotation)(n,{group1:{name:"Control",columns:["s1","s2"]},group2:{name:"Treatment",columns:["s3","s4"]},organism:"rnorvegicus"}),(0,t.E3)((0,l.Di)(n),"rnorvegicus"),(0,t.E3)((0,l.f)(n).group1.name,"Control");const o=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0"])]);(0,l.applyAnnotation)(o,{group1:{name:"A",columns:["s1"]},group2:{name:"B",columns:["s2"]}}),(0,t.E3)(void 0===(0,l.Di)(o),!0)}),(0,t.t6)("getGroups round-trips GroupAssignment correctly",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0"])]);(0,l.$Y)(n,{group1:{name:"Control",columns:["s1","s2","s3"]},group2:{name:"Treatment",columns:["s4","s5","s6"]}});const o=(0,l.f)(n);(0,t.E3)(null!==o,!0),(0,t.E3)(o.group1.name,"Control"),(0,t.E3)(o.group2.name,"Treatment"),(0,t.E3)(o.group1.columns.length,3),(0,t.E3)(o.group2.columns.length,3),(0,t.E3)(o.group1.columns[0],"s1"),(0,t.E3)(o.group2.columns[2],"s6")}),(0,t.t6)("seedAnnotationDialogInputs returns Control/Treatment defaults when no tag",async()=>{const e=p(3,["s1","s2"],["s3","s4"]),n=(0,l.Yf)(e,["s1","s2","s3","s4"]);(0,t.E3)(n.group1Name,"Control"),(0,t.E3)(n.group2Name,"Treatment"),(0,t.E3)(n.group1Cols.length,0),(0,t.E3)(n.group2Cols.length,0)}),(0,t.t6)("seedAnnotationDialogInputs reads names + columns from existing groups",async()=>{const e=p(3,["s1","s2"],["s3","s4"]);(0,l.$Y)(e,{group1:{name:"DMD",columns:["s1","s2"]},group2:{name:"WT",columns:["s3","s4"]}});const n=(0,l.Yf)(e,["s1","s2","s3","s4"]);(0,t.E3)(n.group1Name,"DMD"),(0,t.E3)(n.group2Name,"WT"),(0,t.E3)(n.group1Cols.length,2),(0,t.E3)(n.group2Cols.length,2),(0,t.E3)(n.group1Cols[0].name,"s1"),(0,t.E3)(n.group2Cols[1].name,"s4")}),(0,t.t6)("seedAnnotationDialogInputs drops column refs not in the DataFrame",async()=>{const e=p(3,["s1","s2"],["s3","s4"]);(0,l.$Y)(e,{group1:{name:"DMD",columns:["s1","gone","s2"]},group2:{name:"WT",columns:["also-gone","s3","s4"]}});const n=(0,l.Yf)(e,["s1","s2","s3","s4"]);(0,t.E3)(n.group1Cols.length,2),(0,t.E3)(n.group2Cols.length,2),(0,t.E3)(n.group1Cols.map(e=>e.name).join(","),"s1,s2"),(0,t.E3)(n.group2Cols.map(e=>e.name).join(","),"s3,s4")}),(0,t.t6)("seedAnnotationDialogInputs drops column refs not in available list",async()=>{const e=p(3,["s1","s2"],["s3","s4"]);(0,l.$Y)(e,{group1:{name:"A",columns:["s1","s2"]},group2:{name:"B",columns:["s3","s4"]}});const n=(0,l.Yf)(e,["s1","s3"]);(0,t.E3)(n.group1Cols.length,1),(0,t.E3)(n.group2Cols.length,1),(0,t.E3)(n.group1Cols[0].name,"s1"),(0,t.E3)(n.group2Cols[0].name,"s3")}),(0,t.t6)("seedAnnotationDialogInputs falls back to defaults when stored names are empty",async()=>{const e=p(3,["s1","s2"],["s3","s4"]);(0,l.$Y)(e,{group1:{name:"",columns:["s1","s2"]},group2:{name:"",columns:["s3","s4"]}});const n=(0,l.Yf)(e,["s1","s2","s3","s4"]);(0,t.E3)(n.group1Name,"Control"),(0,t.E3)(n.group2Name,"Treatment")})}),(0,t.L1)("Normalization",()=>{(0,t.t6)("median normalization shifts column medians to zero",async()=>{const n=e.Column.fromFloat32Array("intensity",new Float32Array([2,4,6,8,10]));n.semType=s.iu.INTENSITY;const o=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3","P4"]),n]);(0,c.aj)(o,["intensity"]);const r=o.col("intensity");(0,t.E3)(Math.abs(r.get(0)- -4)<.01,!0),(0,t.E3)(Math.abs(r.get(1)- -2)<.01,!0),(0,t.E3)(Math.abs(r.get(2)-0)<.01,!0),(0,t.E3)(Math.abs(r.get(3)-2)<.01,!0),(0,t.E3)(Math.abs(r.get(4)-4)<.01,!0)}),(0,t.t6)("median normalization skips null values",async()=>{const n=e.Column.fromFloat32Array("intensity",new Float32Array([2,e.FLOAT_NULL,6,8,e.FLOAT_NULL]));n.semType=s.iu.INTENSITY;const o=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3","P4"]),n]);(0,c.aj)(o,["intensity"]);const r=o.col("intensity");(0,t.E3)(r.isNone(1),!0),(0,t.E3)(r.isNone(4),!0),(0,t.E3)(!r.isNone(0),!0),(0,t.E3)(!r.isNone(2),!0),(0,t.E3)(!r.isNone(3),!0)}),(0,t.t6)("normalization sets proteomics.normalized tag",async()=>{const n=e.Column.fromFloat32Array("intensity",new Float32Array([1,2,3]));n.semType=s.iu.INTENSITY;const o=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2"]),n]);(0,c.aj)(o,["intensity"]),(0,t.E3)(o.getTag("proteomics.normalized"),"true")}),(0,t.t6)("quantile normalization aligns column distributions",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([5,2,3,6])),o=e.Column.fromFloat32Array("s2",new Float32Array([4,14,8,2])),r=e.Column.fromFloat32Array("s3",new Float32Array([3,1,9,7]));n.semType=s.iu.INTENSITY,o.semType=s.iu.INTENSITY,r.semType=s.iu.INTENSITY;const a=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3"]),n,o,r]);(0,c.VD)(a,["s1","s2","s3"]);const i=[a.col("s1").get(0),a.col("s1").get(1),a.col("s1").get(2),a.col("s1").get(3)],l=[a.col("s2").get(0),a.col("s2").get(1),a.col("s2").get(2),a.col("s2").get(3)],u=[a.col("s3").get(0),a.col("s3").get(1),a.col("s3").get(2),a.col("s3").get(3)];i.sort((e,t)=>e-t),l.sort((e,t)=>e-t),u.sort((e,t)=>e-t);for(let e=0;e<4;e++)(0,t.E3)(Math.abs(i[e]-l[e])<.01,!0),(0,t.E3)(Math.abs(i[e]-u[e])<.01,!0)}),(0,t.t6)("quantile normalization preserves null values",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([5,e.FLOAT_NULL,3,6])),o=e.Column.fromFloat32Array("s2",new Float32Array([4,14,8,e.FLOAT_NULL]));n.semType=s.iu.INTENSITY,o.semType=s.iu.INTENSITY;const r=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3"]),n,o]);(0,c.VD)(r,["s1","s2"]),(0,t.E3)(r.col("s1").isNone(1),!0),(0,t.E3)(r.col("s2").isNone(3),!0),(0,t.E3)(!r.col("s1").isNone(0),!0),(0,t.E3)(!r.col("s2").isNone(0),!0)}),(0,t.t6)("quantile normalization sets proteomics.normalized tag",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([1,2,3])),o=e.Column.fromFloat32Array("s2",new Float32Array([4,5,6]));n.semType=s.iu.INTENSITY,o.semType=s.iu.INTENSITY;const r=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2"]),n,o]);(0,c.VD)(r,["s1","s2"]),(0,t.E3)(r.getTag("proteomics.normalized"),"true")}),(0,t.t6)("quantile normalization with < 2 columns returns without error",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([1,2,3]));n.semType=s.iu.INTENSITY;const o=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2"]),n]);(0,c.VD)(o,["s1"]),(0,t.E3)(Math.abs(o.col("s1").get(0)-1)<.01,!0)}),(0,t.t6)("vsnNormalize falls back to quantile on R failure",async()=>{const n=e.Column.fromFloat32Array("log2(s1)",new Float32Array([5,2,3,6])),o=e.Column.fromFloat32Array("log2(s2)",new Float32Array([4,14,8,2]));n.semType=s.iu.INTENSITY,o.semType=s.iu.INTENSITY;const r=e.Column.fromFloat32Array("s1",new Float32Array([32,4,8,64])),a=e.Column.fromFloat32Array("s2",new Float32Array([16,16384,256,4])),i=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3"]),r,a,n,o]);await(0,c.Nx)(i,["log2(s1)","log2(s2)"]),(0,t.E3)(i.getTag("proteomics.normalized"),"true")})}),(0,t.L1)("Imputation",()=>{(0,t.t6)("MinProb imputation fills all NaN values",async()=>{const n=new Float32Array([10,e.FLOAT_NULL,14,e.FLOAT_NULL,12]),o=e.Column.fromFloat32Array("intensity",n);o.semType=s.iu.INTENSITY;const r=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3","P4"]),o]);(0,u.U0)(r,["intensity"]);const a=r.col("intensity");for(let e=0;e<a.length;e++)(0,t.E3)(a.isNone(e),!1)}),(0,t.t6)("imputed values are below the observed mean",async()=>{const n=new Float32Array([10,12,14,16,e.FLOAT_NULL,e.FLOAT_NULL]),o=e.Column.fromFloat32Array("intensity",n);o.semType=s.iu.INTENSITY;const r=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3","P4","P5"]),o]);(0,u.U0)(r,["intensity"],1.8,.3);const a=r.col("intensity");(0,t.E3)(a.get(4)<13,!0),(0,t.E3)(a.get(5)<13,!0)}),(0,t.t6)("imputation sets proteomics.imputed tag",async()=>{const n=e.Column.fromFloat32Array("intensity",new Float32Array([1,e.FLOAT_NULL,3]));n.semType=s.iu.INTENSITY;const o=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2"]),n]);(0,u.U0)(o,["intensity"]),(0,t.E3)(o.getTag("proteomics.imputed"),"true")}),(0,t.t6)("kNN imputation fills missing values using nearest neighbors",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([10,11,10.5,12,100])),o=e.Column.fromFloat32Array("s2",new Float32Array([20,21,e.FLOAT_NULL,22,200])),r=e.Column.fromFloat32Array("s3",new Float32Array([30,31,30.5,32,300]));n.semType=s.iu.INTENSITY,o.semType=s.iu.INTENSITY,r.semType=s.iu.INTENSITY;const a=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3","P4"]),n,o,r]),i=(0,u.Mx)(a,["s1","s2","s3"],3);(0,t.E3)(i,1);const l=a.col("s2").get(2);(0,t.E3)(Math.abs(l-21)<1,!0)}),(0,t.t6)("kNN imputation falls back to column mean when no neighbors have values",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([10,e.FLOAT_NULL,e.FLOAT_NULL])),o=e.Column.fromFloat32Array("s2",new Float32Array([20,e.FLOAT_NULL,e.FLOAT_NULL]));n.semType=s.iu.INTENSITY,o.semType=s.iu.INTENSITY;const r=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2"]),n,o]),a=(0,u.Mx)(r,["s1","s2"],10);(0,t.E3)(a>=2,!0)}),(0,t.t6)("kNN imputation returns correct count and sets tag",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([1,2,e.FLOAT_NULL,4])),o=e.Column.fromFloat32Array("s2",new Float32Array([5,e.FLOAT_NULL,7,8]));n.semType=s.iu.INTENSITY,o.semType=s.iu.INTENSITY;const r=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3"]),n,o]),a=(0,u.Mx)(r,["s1","s2"],3);(0,t.E3)(a,2),(0,t.E3)(r.getTag("proteomics.imputed"),"true");for(let e=0;e<4;e++)(0,t.E3)(r.col("s1").isNone(e),!1),(0,t.E3)(r.col("s2").isNone(e),!1)}),(0,t.t6)("imputeZero replaces all nulls with 0",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([1,e.FLOAT_NULL,3,e.FLOAT_NULL]));n.semType=s.iu.INTENSITY;const o=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3"]),n]),r=(0,u.fX)(o,["s1"]);(0,t.E3)(r,2),(0,t.E3)(Math.abs(o.col("s1").get(1)-0)<.01,!0),(0,t.E3)(Math.abs(o.col("s1").get(3)-0)<.01,!0),(0,t.E3)(o.getTag("proteomics.imputed"),"true")}),(0,t.t6)("imputeMean replaces all nulls with column mean",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([2,e.FLOAT_NULL,6,e.FLOAT_NULL]));n.semType=s.iu.INTENSITY;const o=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3"]),n]),r=(0,u.Q2)(o,["s1"]);(0,t.E3)(r,2),(0,t.E3)(Math.abs(o.col("s1").get(1)-4)<.01,!0),(0,t.E3)(Math.abs(o.col("s1").get(3)-4)<.01,!0),(0,t.E3)(o.getTag("proteomics.imputed"),"true")}),(0,t.t6)("imputeMedian replaces all nulls with column median",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([2,e.FLOAT_NULL,6,10,e.FLOAT_NULL]));n.semType=s.iu.INTENSITY;const o=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3","P4"]),n]),r=(0,u.p4)(o,["s1"]);(0,t.E3)(r,2),(0,t.E3)(Math.abs(o.col("s1").get(1)-6)<.01,!0),(0,t.E3)(Math.abs(o.col("s1").get(4)-6)<.01,!0),(0,t.E3)(o.getTag("proteomics.imputed"),"true")})}),(0,t.L1)("Differential Expression",()=>{(0,t.t6)("DE produces correct log2FC sign for known groups",async()=>{const e=["ctrl1","ctrl2","ctrl3"],n=["treat1","treat2","treat3"],o=e.map(()=>Array.from({length:5},()=>5)),r=n.map(()=>Array.from({length:5},()=>10)),s=p(5,e,n,o,r);(0,m.ps)(s,e,n,"Control","Treatment");const a=s.col("log2FC");for(let e=0;e<5;e++)(0,t.E3)(a.get(e)>0,!0)}),(0,t.t6)("DE produces valid p-values between 0 and 1",async()=>{const e=["ctrl1","ctrl2","ctrl3"],n=["treat1","treat2","treat3"],o=p(3,e,n,[[4.8,5.1,5.3],[4.9,5,5.2],[5.1,4.8,5]],[[9.8,10.1,10.3],[9.9,10,10.2],[10.1,9.8,10]]);(0,m.ps)(o,e,n,"Control","Treatment");const r=o.col("p-value"),s=o.col("adj.p-value");for(let e=0;e<3;e++)(0,t.E3)(r.get(e)>=0&&r.get(e)<=1,!0),(0,t.E3)(s.get(e)>=0&&s.get(e)<=1,!0)}),(0,t.t6)("proteins with <2 replicates get null p-values",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["P0"]),e.Column.fromFloat32Array("ctrl1",new Float32Array([5])),e.Column.fromFloat32Array("ctrl2",new Float32Array([e.FLOAT_NULL])),e.Column.fromFloat32Array("ctrl3",new Float32Array([e.FLOAT_NULL])),e.Column.fromFloat32Array("treat1",new Float32Array([10])),e.Column.fromFloat32Array("treat2",new Float32Array([10.5])),e.Column.fromFloat32Array("treat3",new Float32Array([9.5]))]);(0,m.ps)(n,["ctrl1","ctrl2","ctrl3"],["treat1","treat2","treat3"],"Control","Treatment");const o=n.col("p-value");(0,t.E3)(o.isNone(0),!0)}),(0,t.t6)("significant column marks proteins passing both thresholds",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["P_significant","P_not_significant"]),e.Column.fromFloat32Array("ctrl1",new Float32Array([5,5])),e.Column.fromFloat32Array("ctrl2",new Float32Array([5.1,5.1])),e.Column.fromFloat32Array("ctrl3",new Float32Array([4.9,4.9])),e.Column.fromFloat32Array("treat1",new Float32Array([12,5.2])),e.Column.fromFloat32Array("treat2",new Float32Array([12.1,4.8])),e.Column.fromFloat32Array("treat3",new Float32Array([11.9,5]))]);(0,m.ps)(n,["ctrl1","ctrl2","ctrl3"],["treat1","treat2","treat3"],"Control","Treatment",1,.05);const o=n.col("significant");(0,t.E3)(o.get(0),!0),(0,t.E3)(o.get(1),!1)}),(0,t.t6)("DE sets proteomics.de_complete tag",async()=>{const e=["ctrl1","ctrl2","ctrl3"],n=["treat1","treat2","treat3"],o=e.map(()=>Array.from({length:2},()=>5)),r=n.map(()=>Array.from({length:2},()=>10)),s=p(2,e,n,o,r);(0,m.ps)(s,e,n,"Control","Treatment"),(0,t.E3)(s.getTag("proteomics.de_complete"),"true")}),(0,t.t6)("D-09: DE dialog defaults to the declared (group1 = numerator) contrast",async()=>{(0,t.E3)((0,m.zV)("DMD","WT"),"DMD vs WT"),(0,t.E3)((0,m.zV)("WT","DMD"),"WT vs DMD")}),(0,t.t6)("D-09: contrast is direction-only — reversing flips sign, not |log2FC|",async()=>{const e=["dmd1","dmd2","dmd3"],n=["wt1","wt2","wt3"],o=e.map(()=>Array.from({length:3},()=>9)),r=n.map(()=>Array.from({length:3},()=>4)),s=p(3,e,n,o,r);(0,m.ps)(s,n,e,"WT","DMD");const a=s.col("log2FC").get(0),i=p(3,e,n,o,r);(0,m.ps)(i,e,n,"DMD","WT");const l=i.col("log2FC").get(0);(0,t.E3)(a>0,!0),(0,t.E3)(l<0,!0),(0,t.E3)(Math.abs(Math.abs(a)-Math.abs(l))<1e-6,!0)}),(0,t.t6)("DE assigns correct semantic types",async()=>{const e=["ctrl1","ctrl2","ctrl3"],n=["treat1","treat2","treat3"],o=e.map(()=>Array.from({length:2},()=>5)),r=n.map(()=>Array.from({length:2},()=>10)),a=p(2,e,n,o,r);(0,m.ps)(a,e,n,"Control","Treatment"),(0,t.E3)(a.col("log2FC").semType,s.iu.LOG2FC),(0,t.E3)(a.col("p-value").semType,s.iu.P_VALUE),(0,t.E3)(a.col("adj.p-value").semType,s.iu.P_VALUE)})}),(0,t.L1)("DE result alignment",()=>{(0,t.t6)("copyDEResultsToFrame realigns by row key, not position",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["P0","P1","P2","P3"])]),o=[3,1,4,2],r=e.DataFrame.fromColumns([e.Column.fromList("int","row",o),e.Column.fromList("double","log2FC",o.map(e=>e-1)),e.Column.fromList("double","p.value",o.map(e=>e-1)),e.Column.fromList("double","adj.p.value",o.map(e=>e-1)),e.Column.fromList("bool","significant",o.map(e=>e-1==0))]),s=(0,m.pd)(n,r);for(let e=0;e<4;e++)(0,t.E3)(n.col("log2FC").get(e),e),(0,t.E3)(n.col("p-value").get(e),e),(0,t.E3)(n.col("adj.p-value").get(e),e),(0,t.E3)(n.col("significant").get(e),0===e);(0,t.E3)(s,1)}),(0,t.t6)("copyDEResultsToFrame falls back to positional without row key",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["P0","P1","P2"])]),o=e.DataFrame.fromColumns([e.Column.fromList("double","log2FC",[10,20,30]),e.Column.fromList("double","p.value",[1,2,3]),e.Column.fromList("double","adj.p.value",[4,5,6]),e.Column.fromList("bool","significant",[!1,!0,!1])]);(0,m.pd)(n,o),(0,t.E3)(n.col("log2FC").get(1),20),(0,t.E3)(n.col("adj.p-value").get(2),6),(0,t.E3)(n.col("significant").get(1),!0),(0,t.E3)(n.col("significant").get(0),!1)})});var d=n(954);function f(e){const t=e.delimiter??",";return[e.headers.join(t),...e.rows.map(e=>e.join(t))].join("\n")}(0,t.L1)("Generic Parser",()=>{(0,t.t6)("Generic: parses CSV with comma delimiter",async()=>{const n=f({headers:["Protein","Intensity A","Intensity B","Intensity C"],rows:[["P12345","1000","2000","3000"],["P67890","4000","5000","6000"]]}),o=(0,d.T6)(n);(0,t.E3)(o,",");const r=e.DataFrame.fromCsv(n,{delimiter:","});(0,t.E3)(r.columns.length,4),(0,t.E3)(r.rowCount,2)}),(0,t.t6)("Generic: parses TSV with tab delimiter",async()=>{const n=f({headers:["Protein","Intensity A","Intensity B","Intensity C"],rows:[["P12345","1000","2000","3000"],["P67890","4000","5000","6000"]],delimiter:"\t"}),o=(0,d.T6)(n);(0,t.E3)(o,"\t");const r=e.DataFrame.fromCsv(n,{delimiter:"\t"});(0,t.E3)(r.columns.length,4),(0,t.E3)(r.rowCount,2)}),(0,t.t6)("Generic: auto-suggests protein ID column",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein IDs",["P12345"]),e.Column.fromStrings("Gene names",["BRCA1"]),e.Column.fromList(e.COLUMN_TYPE.FLOAT,"Intensity A",[1e3])]),o=(0,d.q2)(n);(0,t.E3)(null!==o,!0),(0,t.E3)(o.name,"Protein IDs")}),(0,t.t6)("Generic: auto-suggests intensity columns",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P12345"]),e.Column.fromList(e.COLUMN_TYPE.FLOAT,"Intensity Sample1",[1e3]),e.Column.fromList(e.COLUMN_TYPE.FLOAT,"LFQ Sample2",[2e3]),e.Column.fromStrings("notes",["some note"])]),o=(0,d.WI)(n);(0,t.E3)(o.length,2),(0,t.E3)(o.includes("Intensity Sample1"),!0),(0,t.E3)(o.includes("LFQ Sample2"),!0)}),(0,t.t6)("Generic: detects raw intensities for log2 toggle",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromList(e.COLUMN_TYPE.FLOAT,"vals",[5e4,1e5,2e5])]),o=(0,d.eY)(n,["vals"]);(0,t.E3)(o.isLog2,!1)}),(0,t.t6)("Generic: detects already-log2 data",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromList(e.COLUMN_TYPE.FLOAT,"vals",[15.2,18.7,12.1])]),o=(0,d.eY)(n,["vals"]);(0,t.E3)(o.isLog2,!0)}),(0,t.t6)("Generic: log2TransformColumns produces correct values",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromList(e.COLUMN_TYPE.FLOAT,"Intensity A",[1024,0,2048])]);(0,d.Kh)(n,["Intensity A"]);const o=n.col("log2(Intensity A)");(0,t.E3)(null!==o,!0),o&&((0,t.E3)(Math.abs(o.get(0)-10)<.001,!0),(0,t.E3)(o.isNone(1),!0),(0,t.E3)(Math.abs(o.get(2)-11)<.001,!0),(0,t.E3)(o.semType,s.iu.INTENSITY));const r=n.col("Intensity A");(0,t.E3)(r.semType,s.iu.INTENSITY)}),(0,t.t6)("Generic: copyAsLog2Columns copies values without transform",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromList(e.COLUMN_TYPE.FLOAT,"Intensity A",[15.2,18.7])]);(0,d.l3)(n,["Intensity A"]);const o=n.col("log2(Intensity A)");(0,t.E3)(null!==o,!0),o&&((0,t.E3)(Math.abs(o.get(0)-15.2)<.001,!0),(0,t.E3)(Math.abs(o.get(1)-18.7)<.001,!0))}),(0,t.t6)("Generic: addPrimaryColumnIfNeeded creates column for semicolons",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein",["P12345;Q67890","P11111"])]);(0,d.wK)(n,"Protein","Primary Protein",s.iu.PROTEIN_ID);const o=n.col("Primary Protein");(0,t.E3)(null!==o,!0),o&&((0,t.E3)(o.get(0),"P12345"),(0,t.E3)(o.get(1),"P11111"))}),(0,t.t6)("Generic: addPrimaryColumnIfNeeded skips when no semicolons",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein",["P12345","P11111"])]);(0,d.wK)(n,"Protein","Primary Protein",s.iu.PROTEIN_ID);const o=n.col("Primary Protein");(0,t.E3)(o,null)}),(0,t.t6)("Generic: assigns semantic types to selected columns",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein",["P12345"])]).col("Protein");n.semType=s.iu.PROTEIN_ID,(0,t.E3)(n.semType,s.iu.PROTEIN_ID)})});var g=n(715);(0,t.L1)("QC Dashboard",()=>{(0,t.t6)("getIntensityColumns",async()=>{const n=e.Column.fromFloat32Array("log2(sample1)",new Float32Array([1,2]));n.semType=s.iu.INTENSITY;const o=e.Column.fromFloat32Array("other",new Float32Array([3,4])),r=e.Column.fromFloat32Array("log2(sample2)",new Float32Array([5,6]));r.semType=s.iu.INTENSITY;const a=e.DataFrame.fromColumns([n,o,r]),i=(0,g.Hc)(a);(0,t.E3)(i.length,2),(0,t.E3)(i[0],"log2(sample1)"),(0,t.E3)(i[1],"log2(sample2)")}),(0,t.t6)("MA computation",async()=>{const n=e.Column.fromFloat32Array("log2(ctrl1)",new Float32Array([10,5,8]));n.semType=s.iu.INTENSITY;const o=e.Column.fromFloat32Array("log2(ctrl2)",new Float32Array([12,7,6]));o.semType=s.iu.INTENSITY;const r=e.Column.fromFloat32Array("log2(treat1)",new Float32Array([8,3,e.FLOAT_NULL]));r.semType=s.iu.INTENSITY;const a=e.Column.fromFloat32Array("log2(treat2)",new Float32Array([6,5,e.FLOAT_NULL]));a.semType=s.iu.INTENSITY;const i=e.DataFrame.fromColumns([n,o,r,a]);(0,g.iQ)(i,{group1:{name:"Control",columns:["log2(ctrl1)","log2(ctrl2)"]},group2:{name:"Treatment",columns:["log2(treat1)","log2(treat2)"]}});const l=i.col("M"),c=i.col("A");(0,t.E3)(Math.abs(l.get(0)- -4)<.01,!0),(0,t.E3)(Math.abs(c.get(0)-9)<.01,!0),(0,t.E3)(l.isNone(2),!0),(0,t.E3)(c.isNone(2),!0)}),(0,t.t6)("CV computation",async()=>{const n=e.Column.fromFloat32Array("log2(s1)",new Float32Array([2,3]));n.semType=s.iu.INTENSITY;const o=e.Column.fromFloat32Array("log2(s2)",new Float32Array([2,5]));o.semType=s.iu.INTENSITY;const r=e.Column.fromFloat32Array("log2(s3)",new Float32Array([2,7]));r.semType=s.iu.INTENSITY;const a=e.DataFrame.fromColumns([n,o,r]);(0,g.JZ)(a,["log2(s1)","log2(s2)","log2(s3)"],"CV","Mean");const i=a.col("CV"),l=a.col("Mean");(0,t.E3)(Math.abs(i.get(0))<.001,!0),(0,t.E3)(Math.abs(l.get(0)-4)<.01,!0),(0,t.E3)(i.get(1)>0,!0)}),(0,t.t6)("Loess/moving-average trend",async()=>{let n=12345;const o=()=>(n=1664525*n+1013904223>>>0,n/4294967295),r=new Float32Array(25),s=new Float32Array(25);for(let e=0;e<25;e++)r[e]=e+1,s[e]=.5*Math.sin(e/5)+.3*(o()-.5);const a=e.DataFrame.fromColumns([e.Column.fromFloat32Array("A",r),e.Column.fromFloat32Array("M",s)]);(0,g.Pq)(a,.5);const i=a.col("MA_trend");(0,t.E3)(null!==i,!0);let l=0;for(let e=0;e<25;e++)i.isNone(e)||l++;(0,t.E3)(l>0,!0);let c=0,u=0,m=0,p=0,d=0,f=0;for(let e=0;e<25;e++){const t=s[e];if(c+=t,u+=t*t,m++,!i.isNone(e)){const t=i.get(e);p+=t,d+=t*t,f++}}const h=u/m-c/m*(c/m),y=d/f-p/f*(p/f);(0,t.E3)(y<h,!0)}),(0,t.t6)("Missingness matrix",async()=>{const n=e.Column.fromFloat32Array("log2(s1)",new Float32Array([5,e.FLOAT_NULL]));n.semType=s.iu.INTENSITY;const o=e.Column.fromFloat32Array("log2(s2)",new Float32Array([e.FLOAT_NULL,3]));o.semType=s.iu.INTENSITY;const r=e.DataFrame.fromColumns([n,o]),a=(0,g.ho)(r,["log2(s1)","log2(s2)"]);(0,t.E3)(a.rowCount,2),(0,t.E3)(a.name,"Missing Values");const i=a.col("log2(s1)"),l=a.col("log2(s2)");(0,t.E3)(i.get(0),1),(0,t.E3)(l.get(0),0),(0,t.E3)(i.get(1),0),(0,t.E3)(l.get(1),1)}),(0,t.t6)("Unpivot intensities",async()=>{const n=e.Column.fromStrings("Protein ID",["P0","P1"]);n.semType=s.iu.PROTEIN_ID;const o=e.Column.fromFloat32Array("log2(s1)",new Float32Array([10,e.FLOAT_NULL]));o.semType=s.iu.INTENSITY;const r=e.Column.fromFloat32Array("log2(s2)",new Float32Array([20,30]));r.semType=s.iu.INTENSITY;const a=e.DataFrame.fromColumns([n,o,r]),i=(0,g.j4)(a,["log2(s1)","log2(s2)"]);(0,t.E3)(i.name,"Intensity Distributions"),(0,t.E3)(i.rowCount,3),(0,t.E3)(null!==i.col("ProteinId"),!0),(0,t.E3)(null!==i.col("Sample"),!0),(0,t.E3)(null!==i.col("Intensity"),!0)}),(0,t.t6)("Missing bar data",async()=>{const n=e.Column.fromFloat32Array("log2(ctrl1)",new Float32Array([5,e.FLOAT_NULL,7]));n.semType=s.iu.INTENSITY;const o=e.Column.fromFloat32Array("log2(treat1)",new Float32Array([10,11,12]));o.semType=s.iu.INTENSITY;const r=e.DataFrame.fromColumns([n,o]),a=(0,g.rA)(r,["log2(ctrl1)","log2(treat1)"],{group1:{name:"Control",columns:["log2(ctrl1)"]},group2:{name:"Treatment",columns:["log2(treat1)"]}});(0,t.E3)(a.rowCount,2);const i=a.col("MissingPct"),l=a.col("Group");(0,t.E3)(Math.abs(i.get(0)-33.333)<1,!0),(0,t.E3)(Math.abs(i.get(1))<.01,!0),(0,t.E3)(l.get(0),"Control"),(0,t.E3)(l.get(1),"Treatment")})});var h=n(230),y=n(897);(0,t.L1)("Enrichment",()=>{(0,t.t6)("buildEnrichmentDf creates correct schema",async()=>{const e=(0,h.Mz)([{native:"GO:0006915",name:"apoptotic process",source:"GO:BP",p_value:.001,significant:!0,term_size:500,query_size:50,intersection_size:10,effective_domain_size:2e4,precision:.2,recall:.02,intersections:[["IEA"],["IDA"],[],["TAS"]]},{native:"KEGG:04210",name:"Apoptosis",source:"KEGG",p_value:.03,significant:!0,term_size:120,query_size:50,intersection_size:5,effective_domain_size:2e4,precision:.1,recall:.042,intersections:[[],["evidence"],[],[]]},{native:"REAC:R-HSA-109581",name:"Apoptosis",source:"REAC",p_value:.12,significant:!1,term_size:80,query_size:50,intersection_size:3,effective_domain_size:2e4,precision:.06,recall:.0375,intersections:[["IEA"],[],[],[]]}],["TP53","BRCA1","EGFR","MYC"]);(0,t.E3)(e.columns.length,8),(0,t.E3)(null!==e.col("Source"),!0),(0,t.E3)(null!==e.col("Term ID"),!0),(0,t.E3)(null!==e.col("Term Name"),!0),(0,t.E3)(null!==e.col("FDR"),!0),(0,t.E3)(null!==e.col("Gene Count"),!0),(0,t.E3)(null!==e.col("Gene Ratio"),!0),(0,t.E3)(null!==e.col("Intersection"),!0),(0,t.E3)(null!==e.col("Significant"),!0),(0,t.E3)(e.rowCount,3)}),(0,t.t6)("buildEnrichmentDf sets enrichment tag",async()=>{const e=(0,h.Mz)([{native:"GO:0006915",name:"apoptotic process",source:"GO:BP",p_value:.001,significant:!0,term_size:500,query_size:50,intersection_size:10,effective_domain_size:2e4,precision:.2,recall:.02,intersections:[["IEA"],["IDA"],[],["TAS"]]},{native:"KEGG:04210",name:"Apoptosis",source:"KEGG",p_value:.03,significant:!0,term_size:120,query_size:50,intersection_size:5,effective_domain_size:2e4,precision:.1,recall:.042,intersections:[[],["evidence"],[],[]]},{native:"REAC:R-HSA-109581",name:"Apoptosis",source:"REAC",p_value:.12,significant:!1,term_size:80,query_size:50,intersection_size:3,effective_domain_size:2e4,precision:.06,recall:.0375,intersections:[["IEA"],[],[],[]]}],["TP53","BRCA1","EGFR","MYC"]);(0,t.E3)(e.getTag("proteomics.enrichment"),"true")}),(0,t.t6)("buildEnrichmentDf marks significant terms",async()=>{const e=(0,h.Mz)([{native:"GO:0006915",name:"apoptotic process",source:"GO:BP",p_value:.001,significant:!0,term_size:500,query_size:50,intersection_size:10,effective_domain_size:2e4,precision:.2,recall:.02,intersections:[["IEA"],["IDA"],[],["TAS"]]},{native:"KEGG:04210",name:"Apoptosis",source:"KEGG",p_value:.03,significant:!0,term_size:120,query_size:50,intersection_size:5,effective_domain_size:2e4,precision:.1,recall:.042,intersections:[[],["evidence"],[],[]]},{native:"REAC:R-HSA-109581",name:"Apoptosis",source:"REAC",p_value:.12,significant:!1,term_size:80,query_size:50,intersection_size:3,effective_domain_size:2e4,precision:.06,recall:.0375,intersections:[["IEA"],[],[],[]]}],["TP53","BRCA1","EGFR","MYC"]).col("Significant");(0,t.E3)(e.get(0),!0),(0,t.E3)(e.get(1),!0),(0,t.E3)(e.get(2),!1)}),(0,t.t6)("buildEnrichmentDf extracts intersection genes",async()=>{const e=(0,h.Mz)([{native:"GO:0006915",name:"apoptotic process",source:"GO:BP",p_value:.01,significant:!0,term_size:500,query_size:4,intersection_size:2,effective_domain_size:2e4,precision:.5,recall:.004,intersections:[["IEA"],[],["TAS"],[]]}],["TP53","BRCA1","EGFR","MYC"]).col("Intersection").get(0);(0,t.E3)(e,"TP53, EGFR")}),(0,t.t6)("countSignificantProteins counts correctly",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromFloat32Array("log2FC",new Float32Array([2,.5,-1.5,3])),e.Column.fromFloat32Array("adjP",new Float32Array([.01,.001,.1,.03]))]),o=(0,h.bM)(n,1,.05,n.col("log2FC"),n.col("adjP"));(0,t.E3)(o.significant,2),(0,t.E3)(o.total,4)}),(0,t.t6)("countSignificantProteins handles null values",async()=>{const n=e.Column.fromFloat32Array("log2FC",new Float32Array([2,0,-1.5])),o=e.Column.fromFloat32Array("adjP",new Float32Array([.01,0,.03]));n.set(1,e.FLOAT_NULL),o.set(1,e.FLOAT_NULL);const r=e.DataFrame.fromColumns([n,o]),s=(0,h.bM)(r,1,.05,n,o);(0,t.E3)(s.significant,2),(0,t.E3)(s.total,3)}),(0,t.t6)("splitGenesByDirection splits significant genes by fc sign, shared background",async()=>{const e=new Map([[0,"A"],[1,"B"],[2,"C"],[3,"D"]]),n=new Float32Array([2,-2,.5,-3]),o=new Float32Array([.01,.01,.001,.2]),{upGenes:r,downGenes:s,background:a}=(0,h.Bx)(e,n,o,1,.05);(0,t.E3)(r.length,1),(0,t.E3)(r[0],"A"),(0,t.E3)(s.length,1),(0,t.E3)(s[0],"B"),(0,t.E3)(a.length,4),(0,t.E3)(a.includes("A")&&a.includes("B")&&a.includes("C")&&a.includes("D"),!0),(0,t.E3)(r.some(e=>s.includes(e)),!1)}),(0,t.t6)("splitGenesByDirection skips null fc/p rows",async()=>{const n=new Map([[0,"A"],[1,"B"]]),o=new Float32Array([2,0]),r=new Float32Array([.01,0]);o[1]=e.FLOAT_NULL,r[1]=e.FLOAT_NULL;const{upGenes:s,downGenes:a,background:i}=(0,h.Bx)(n,o,r,1,.05);(0,t.E3)(s.length,1),(0,t.E3)(a.length,0),(0,t.E3)(i.length,2)}),(0,t.t6)("buildEnrichmentDf adds Direction column when label given",async()=>{const e=(0,h.Mz)([{native:"GO:0006915",name:"apoptotic process",source:"GO:BP",p_value:.001,significant:!0,term_size:500,query_size:50,intersection_size:10,effective_domain_size:2e4,precision:.2,recall:.02,intersections:[["IEA"],["IDA"],[],["TAS"]]},{native:"KEGG:04210",name:"Apoptosis",source:"KEGG",p_value:.03,significant:!0,term_size:120,query_size:50,intersection_size:5,effective_domain_size:2e4,precision:.1,recall:.042,intersections:[[],["evidence"],[],[]]},{native:"REAC:R-HSA-109581",name:"Apoptosis",source:"REAC",p_value:.12,significant:!1,term_size:80,query_size:50,intersection_size:3,effective_domain_size:2e4,precision:.06,recall:.0375,intersections:[["IEA"],[],[],[]]}],["TP53","BRCA1","EGFR","MYC"],.05,"Up"),n=e.col("Direction");(0,t.E3)(null!==n,!0),(0,t.E3)(n.get(0),"Up"),(0,t.E3)(n.get(1),"Up"),(0,t.E3)(e.columns.length,9),(0,t.E3)(null!==e.col("Intersection"),!0),(0,t.E3)(e.getTag("proteomics.enrichment"),"true")}),(0,t.t6)("buildEnrichmentDf omits Direction column when no label",async()=>{const e=(0,h.Mz)([{native:"GO:0006915",name:"apoptotic process",source:"GO:BP",p_value:.001,significant:!0,term_size:500,query_size:50,intersection_size:10,effective_domain_size:2e4,precision:.2,recall:.02,intersections:[["IEA"],["IDA"],[],["TAS"]]},{native:"KEGG:04210",name:"Apoptosis",source:"KEGG",p_value:.03,significant:!0,term_size:120,query_size:50,intersection_size:5,effective_domain_size:2e4,precision:.1,recall:.042,intersections:[[],["evidence"],[],[]]},{native:"REAC:R-HSA-109581",name:"Apoptosis",source:"REAC",p_value:.12,significant:!1,term_size:80,query_size:50,intersection_size:3,effective_domain_size:2e4,precision:.06,recall:.0375,intersections:[["IEA"],[],[],[]]}],["TP53","BRCA1","EGFR","MYC"]);(0,t.E3)(e.col("Direction"),null),(0,t.E3)(e.columns.length,8)}),(0,t.t6)("wireEnrichmentToVolcano selects matching proteins, source DF unmutated",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Intersection",["TP53, EGFR"]),e.Column.fromStrings("Direction",["Up"])]),o=e.Column.fromStrings("Gene Symbol",["TP53","EGFR","MYC"]);o.semType=s.iu.GENE_SYMBOL;const r=e.DataFrame.fromColumns([o]),a=(0,y.aB)(n,r);n.currentRowIdx=0,(0,t.E3)(r.selection.trueCount,2),(0,t.E3)(r.selection.get(2),!1),(0,t.E3)(n.rowCount,1),(0,t.E3)(r.rowCount,3),a.unsubscribe()}),(0,t.t6)("ORGANISM_LIST contains 9 entries with valid codes",async()=>{(0,t.E3)(h.Ae.length,9),(0,t.E3)(h.Ae[0].display,"Homo sapiens (Human)"),(0,t.E3)(h.Ae[0].code,"hsapiens");for(const e of h.Ae)(0,t.E3)(e.display.length>0,!0),(0,t.E3)(e.code.length>0,!0)})});var E=n(989);function w(){const t=e.DataFrame.fromColumns([e.Column.fromStrings("Gene names",["G1","G2","G3"]),e.Column.fromFloat32Array("log2FC",new Float32Array([2,-2,.1])),e.Column.fromFloat32Array("adj.p-value",new Float32Array([.01,.01,.5]))]);return t.col("Gene names").semType=s.iu.GENE_SYMBOL,t.col("log2FC").semType=s.iu.LOG2FC,t.col("adj.p-value").semType=s.iu.P_VALUE,t}(0,t.L1)("Enrichment Export",()=>{(0,t.t6)("buildEnrichmentInputsCsv: up/down/background split matches thresholds",async()=>{const{csv:e,counts:n}=(0,E.J)(w(),1,.05);(0,t.E3)(n.up,1,"one up gene"),(0,t.E3)(n.down,1,"one down gene"),(0,t.E3)(n.background,3,"all three genes in background");const o=e.split("\n");(0,t.E3)(o[0],"gene,list","tidy long header"),(0,t.E3)(o.includes("G1,up"),!0,"G1 is up"),(0,t.E3)(o.includes("G2,down"),!0,"G2 is down"),(0,t.E3)(o.includes("G1,background")&&o.includes("G2,background")&&o.includes("G3,background"),!0,"all genes listed as background"),(0,t.E3)(o.includes("G3,up")||o.includes("G3,down"),!1,"G3 stays background-only")}),(0,t.t6)("buildEnrichmentInputsCsv: looser thresholds pull more genes in",async()=>{const{counts:e}=(0,E.J)(w(),0,.6);(0,t.E3)(e.up,2,"G1 and G3 now up"),(0,t.E3)(e.down,1,"G2 still down"),(0,t.E3)(e.background,3,"background unchanged")}),(0,t.t6)("buildEnrichmentInputsCsv: quotes a gene containing a comma",async()=>{const e=w();e.col("Gene names").set(0,"G1,alias");const{csv:n}=(0,E.J)(e,1,.05);(0,t.E3)(n.includes('"G1,alias",up'),!0,"comma-bearing field is CSV-quoted")}),(0,t.t6)("buildEnrichmentInputsCsv: throws without DE columns",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Gene names",["G1"])]);n.col("Gene names").semType=s.iu.GENE_SYMBOL;let o=!1;try{(0,E.J)(n,1,.05)}catch{o=!0}(0,t.E3)(o,!0,"missing log2FC/adj.p-value is an error")})});var v=n(328),_=n(858);function C(t,n){const o=[],r=[],s=[],a=[],i=[],l=[],c=[],u=[],m=[];for(let e=0;e<t;e++){o.push(e%2==0?"GO:BP":"KEGG"),r.push(`GO:${String(e).padStart(7,"0")}`),s.push(n&&0===e?n:`Term ${e+1}`);const t=.001*(e+1);a.push(t),i.push(t),l.push(10-Math.min(e,9)),c.push(.2-.005*e),u.push("TP53, BRCA1"),m.push(t<.05)}const p=e.DataFrame.fromColumns([e.Column.fromStrings("Source",o),e.Column.fromStrings("Term ID",r),e.Column.fromStrings("Term Name",s),e.Column.fromFloat32Array("P-value",new Float32Array(a)),e.Column.fromFloat32Array("FDR",new Float32Array(i)),e.Column.fromInt32Array("Gene Count",new Int32Array(l)),e.Column.fromFloat32Array("Gene Ratio",new Float32Array(c)),e.Column.fromStrings("Intersection",u),e.Column.fromList("bool","Significant",m)]);return p.setTag("proteomics.enrichment","true"),p}function b(){const t=e.Column.fromStrings("Gene Name",["TP53","BRCA1","EGFR","MYC","AKT1"]);return t.semType=s.iu.GENE_SYMBOL,e.DataFrame.fromColumns([t,e.Column.fromFloat32Array("log2FC",new Float32Array([1.5,-2,.5,3,-1])),e.Column.fromFloat32Array("adj.p-value",new Float32Array([.001,.01,.5,1e-4,.04]))])}function T(t,n){t.columns.add(e.Column.fromStrings("Direction",n))}function P(e,t){let n=0;for(const o of e.viewers)o.dataFrame?.dart===t.dart&&n++;return n}function S(e){let t=0;for(const n of e.viewers)t++;return t}function N(e){let t=0;for(let n=0;n<e.length;n++)!0===e.get(n)&&t++;return t}(0,t.L1)("Enrichment Visualization",()=>{(0,t.t6)("prepareEnrichmentChartColumns adds negLog10FDR on the same frame",async()=>{const e=C(20);(0,y.E0)(e,15);const n=e.col(y.bC);(0,t.E3)(null!==n,!0);const o=n.get(0);(0,t.E3)(Math.abs(o-3)<.01,!0),(0,t.E3)(e.rowCount,20)}),(0,t.t6)("prepareEnrichmentChartColumns marks exactly topN terms (no Direction)",async()=>{const e=C(20);(0,y.E0)(e,15);const n=e.col(y.$i);(0,t.E3)(N(n),15)}),(0,t.t6)("prepareEnrichmentChartColumns marks topN per direction",async()=>{const e=C(20);T(e,Array.from({length:20},(e,t)=>t<10?"Up":"Down")),(0,y.E0)(e,5);const n=e.col(y.$i);(0,t.E3)(N(n),10)}),(0,t.t6)("prepareEnrichmentChartColumns marks all when fewer rows than topN",async()=>{const e=C(5);(0,y.E0)(e,15);const n=e.col(y.$i);(0,t.E3)(N(n),5)}),(0,t.t6)("prepareEnrichmentChartColumns is idempotent on re-run",async()=>{const e=C(20);(0,y.E0)(e,15);const n=e.columns.length;(0,y.E0)(e,15),(0,t.E3)(e.columns.length,n)}),(0,t.t6)("wireEnrichmentToVolcano returns EMPTY without gene column",async()=>{const n=C(3),o=e.DataFrame.fromColumns([e.Column.fromStrings("SomeColumn",["A","B","C"])]),r=(0,y.aB)(n,o);(0,t.E3)(r===_.Subscription.EMPTY,!0)}),(0,t.t6)("wireEnrichmentToVolcano selects matching genes on protein DataFrame",async()=>{const e=C(3);e.col("Intersection").set(0,"TP53, BRCA1");const n=b(),o=(0,y.aB)(e,n);(0,t.E3)(o!==_.Subscription.EMPTY,!0),e.currentRowIdx=0,(0,t.E3)(n.selection.get(0),!0),(0,t.E3)(n.selection.get(1),!0),(0,t.E3)(n.selection.get(2),!1),(0,t.E3)(n.selection.get(3),!1),(0,t.E3)(n.selection.get(4),!1),o.unsubscribe()}),(0,t.t6)("wireEnrichmentToVolcano clears selection before new selection",async()=>{const e=C(3);e.col("Intersection").set(0,"TP53"),e.col("Intersection").set(1,"EGFR");const n=b();n.selection.set(4,!0,!1),n.selection.fireChanged();const o=(0,y.aB)(e,n);e.currentRowIdx=0,(0,t.E3)(n.selection.get(4),!1),(0,t.E3)(n.selection.get(0),!0),o.unsubscribe()}),(0,t.t6)("openEnrichmentVisualization docks dot/bar on enrichment view (directional)",async()=>{const e=C(4);T(e,["Up","Up","Down","Down"]),e.name="Enrichment (test B)";const n=b();n.name="Protein (test B)";const o=v.shell.addTableView(n),r=S(o),s=(0,y.q6)(e,n);try{(0,t.E3)(S(o),r,"protein view must not gain dot/bar viewers; gained "+(S(o)-r)),(0,t.E3)(S(s)>=4,!0,`enrichment view should carry ≥4 dot/bar viewers; got ${S(s)}`),(0,t.E3)(P(s,n),0,"enrichment view must not carry a proteinDf-bound volcano"),e.currentRowIdx=0,(0,t.E3)(n.selection.trueCount>=1,!0,"selecting an enrichment row should still highlight matching protein rows")}finally{s.close(),o.close()}}),(0,t.t6)("openEnrichmentVisualization docks dot/bar on enrichment view (single-direction)",async()=>{const e=C(3);e.name="Enrichment (test C)";const n=b();n.name="Protein (test C)";const o=v.shell.addTableView(n),r=S(o),s=(0,y.q6)(e,n);try{(0,t.E3)(S(o),r,"protein view must not gain dot/bar viewers; gained "+(S(o)-r)),(0,t.E3)(S(s)>=2,!0,`enrichment view should carry ≥2 dot/bar viewers; got ${S(s)}`),(0,t.E3)(P(s,n),0,"enrichment view must not carry a proteinDf-bound volcano")}finally{s.close(),o.close()}}),(0,t.t6)("openEnrichmentVisualization switches focus to enrichment TableView",async()=>{const e=C(4);T(e,["Up","Up","Down","Down"]),e.name="Enrichment (test D)";const n=b();n.name="Protein (test D)";const o=v.shell.addTableView(n),r=(0,y.q6)(e,n);try{const n=v.shell.v?.dataFrame?.dart;(0,t.E3)(n===e.dart,!0,"focused view should be the enrichment TableView after enrichment runs")}finally{r.close(),o.close()}}),(0,t.t6)("enrichmentBannerRendersWhenTagSet",async()=>{const e=C(3);e.name="Enrichment (banner-on)",e.setTag("proteomics.enrichment_smart_filtered","true"),e.setTag("proteomics.enrichment_smart_filtered_kept","20"),e.setTag("proteomics.enrichment_smart_filtered_total","47"),e.setTag("proteomics.enrichment_smart_filtered_dropped_parents","3"),e.setTag("proteomics.enrichment_smart_filtered_cap","15");const n=b(),o=(0,y.q6)(e,n);try{const e=o.root.querySelectorAll('[data-smart-filter-banner="true"]');(0,t.E3)(e.length>=1,!0,"banner should be docked when tag is set");const n=e[0].textContent??"";(0,t.E3)(n.includes("Smart pathway filter active"),!0),(0,t.E3)(n.includes("showing 20 of 47 terms"),!0),(0,t.E3)(n.includes("dropped 3 generic parents"),!0),(0,t.E3)(n.includes("capped at 15 per source"),!0),(0,t.E3)(n.includes("Re-run with the filter off"),!0)}finally{o.close()}}),(0,t.t6)("enrichmentBannerAbsentWhenTagUnset",async()=>{const e=C(3);e.name="Enrichment (banner-off)";const n=b(),o=(0,y.q6)(e,n);try{const e=o.root.querySelectorAll('[data-smart-filter-banner="true"]');(0,t.E3)(e.length,0)}finally{o.close()}})});var A=n(53),x=n(110);function D(e){const t=[["R.FileName","R.Condition","R.Replicate","PG.ProteinGroups","PG.Organisms",e.quantityColumn??"PG.IBAQ","EG.Qvalue","PEP.StrippedSequence","EG.ModifiedPeptide","FG.Charge","FG.Id"].join("\t")],n=[{strip:"PEPTIDER",mod:"_PEPTIDER_",charge:"2",fg:"FG1"},{strip:"ANOTHERPEP",mod:"_ANOTHERPEP_",charge:"3",fg:"FG2"}],o=(e,o,r,s,a,i,l)=>{for(const c of n)t.push([e,o,String(r),s,a,i,l,c.strip,c.mod,c.charge,c.fg].join("\t"))};let r=100;for(const t of e.proteins){const n=e.ibaqValues?.get(t.id)??r++;for(const r of e.conditions)for(const s of e.replicates){const a=(e.fileNameTemplate??"file")+`_${r}_${s}`,i=e.qValues?.get(t.id)??.001,l=t.organism??"Homo sapiens";o(a,r,s,t.id,l,String(n),String(i))}}if(e.extraRows){let t=500;for(const n of e.extraRows){const r=n.quantity??t++;for(const t of e.conditions)for(const s of e.replicates){const a=(e.fileNameTemplate??"file")+`_${t}_${s}`,i=n.organism??"Homo sapiens";o(a,t,s,n.id,i,String(r),String(n.qValue))}}}return t.join("\n")}(0,t.L1)("Spectronaut",()=>{const e=[{id:"P12345"},{id:"Q67890"},{id:"O15439"}],n={proteins:e,conditions:["CondA","CondB"],replicates:[1,2]};async function o(e){return await(0,A.A)(new File([e],"fixture.tsv",{type:"text/tab-separated-values"}))}async function r(e){return je.files.readAsText(`demo/${e}`)}function a(e){return e.columns.toList().filter(e=>e.semType===s.iu.INTENSITY&&!e.name.startsWith("log2(")).map(e=>e.name).sort()}function i(e){const t=e.col("Primary Protein ID")??e.col("PG.ProteinGroups"),n=new Map;for(let o=0;o<e.rowCount;o++)n.set(String(t.get(o)),o);return{col:t,map:n}}async function c(e){const t=[],n=v.shell.info.bind(v.shell);v.shell.info=e=>{t.push(String(e))};try{return{df:await o(e),infos:t}}finally{v.shell.info=n}}(0,t.t6)("pivot produces correct protein count",async()=>{const e=D(n),o=await(0,A.parseSpectronautText)(e);(0,t.E3)(o.rowCount,3)}),(0,t.t6)("pivot produces correct sample column names",async()=>{const e=D(n),o=await(0,A.parseSpectronautText)(e);(0,t.E3)(null!==o.col("CondA_1"),!0),(0,t.E3)(null!==o.col("CondA_2"),!0),(0,t.E3)(null!==o.col("CondB_1"),!0),(0,t.E3)(null!==o.col("CondB_2"),!0)}),(0,t.t6)("CON__ and REV__ prefixed proteins are excluded",async()=>{const e=D({...n,proteins:[{id:"P12345"},{id:"CON__P99999"},{id:"REV__Q11111"}]}),o=await(0,A.parseSpectronautText)(e);(0,t.E3)(o.rowCount,1),(0,t.E3)(o.col("PG.ProteinGroups").get(0),"P12345")}),(0,t.t6)("rows with numeric EG.Qvalue > threshold are excluded",async()=>{const o=new Map;o.set("P12345",.001),o.set("Q67890",.05),o.set("O15439",.005);const r=D({...n,proteins:e,qValues:o}),s=await(0,A.parseSpectronautText)(r);(0,t.E3)(s.rowCount,2)}),(0,t.t6)("non-numeric EG.Qvalue rows treated as passing",async()=>{const o=new Map;o.set("P12345",.001),o.set("Q67890","Profiled"),o.set("O15439","NaN");const r=D({...n,proteins:e,qValues:o}),s=await(0,A.parseSpectronautText)(r);(0,t.E3)(s.rowCount,3)}),(0,t.t6)("PG.ProteinGroups has PROTEIN_ID semantic type",async()=>{const e=D(n),o=await(0,A.parseSpectronautText)(e);(0,t.E3)(o.col("PG.ProteinGroups")?.semType,s.iu.PROTEIN_ID)}),(0,t.t6)("intensity columns have INTENSITY semantic type",async()=>{const e=D(n),o=await(0,A.parseSpectronautText)(e);(0,t.E3)(o.col("CondA_1")?.semType,s.iu.INTENSITY),(0,t.E3)(o.col("CondB_2")?.semType,s.iu.INTENSITY)}),(0,t.t6)("R.FileName stored as spectronaut.fileName tag on intensity columns",async()=>{const e=D({...n,fileNameTemplate:"run"}),o=(await(0,A.parseSpectronautText)(e)).col("CondA_1");if((0,t.E3)(null!==o,!0),o){const e=o.getTag("spectronaut.fileName");(0,t.E3)(null!==e&&""!==e,!0),(0,t.E3)(e.includes("run"),!0)}}),(0,t.t6)("groups auto-populated via setGroups when exactly 2 conditions",async()=>{const e=D(n),o=await(0,A.parseSpectronautText)(e),r=(0,l.f)(o);(0,t.E3)(null!==r,!0),r&&((0,t.E3)(r.group1.columns.length,2),(0,t.E3)(r.group2.columns.length,2))}),(0,t.t6)("groups not set when more than 2 conditions",async()=>{const e=D({...n,conditions:["CondA","CondB","CondC"]}),o=await(0,A.parseSpectronautText)(e),r=(0,l.f)(o);(0,t.E3)(r,null)}),(0,t.t6)("pre-normalized tag set for raw (non-log2) intensity data",async()=>{const e=D(n),o=await(0,A.parseSpectronautText)(e);(0,t.E3)(o.getTag("proteomics.preNormalized"),"true")}),(0,t.t6)("pre-normalized tag set when detectLog2Status detects log2-range values",async()=>{const e=new Map;e.set("P12345",15.2),e.set("Q67890",22.7),e.set("O15439",18.1);const o=D({...n,ibaqValues:e}),r=await(0,A.parseSpectronautText)(o);(0,t.E3)(r.getTag("proteomics.preNormalized"),"true")}),(0,t.t6)("both raw and log2 intensity columns present in output",async()=>{const e=D(n),o=await(0,A.parseSpectronautText)(e);(0,t.E3)(null!==o.col("CondA_1"),!0),(0,t.E3)(null!==o.col("log2(CondA_1)"),!0),(0,t.E3)(null!==o.col("log2(CondB_2)"),!0)}),(0,t.t6)("proteomics.source tag set to spectronaut",async()=>{const e=D(n),o=await(0,A.parseSpectronautText)(e);(0,t.E3)(o.getTag("proteomics.source"),"spectronaut")}),(0,t.t6)("PG.Quantity accepted as alternative to PG.IBAQ",async()=>{const e=D({...n,quantityColumn:"PG.Quantity"}),o=await(0,A.parseSpectronautText)(e);(0,t.E3)(o.rowCount,3),(0,t.E3)(null!==o.col("CondA_1"),!0),(0,t.E3)(null!==o.col("CondB_2"),!0),(0,t.E3)(o.col("CondA_1")?.semType,s.iu.INTENSITY)}),(0,t.t6)("throws when neither PG.IBAQ nor PG.Quantity is present",async()=>{const e=D({...n,quantityColumn:"PG.Bogus"});let o=!1;try{await(0,A.parseSpectronautText)(e)}catch(e){o=!0,(0,t.E3)(e.message.includes("PG.IBAQ"),!0),(0,t.E3)(e.message.includes("PG.Quantity"),!0)}(0,t.E3)(o,!0)}),(0,t.t6)("demo file produces correct dimensions",async()=>{const e=[];for(let t=0;t<93;t++)e.push({id:`P${String(t).padStart(5,"0")}`});const n=D({proteins:e,conditions:["HYE mix A","HYE mix B"],replicates:[1,2,3,4]}),o=await(0,A.parseSpectronautText)(n);(0,t.E3)(o.rowCount,93);const r=o.columns.toList().filter(e=>e.semType===s.iu.INTENSITY&&!e.name.startsWith("log2("));(0,t.E3)(r.length,8)}),(0,t.t6)("streams precursor fixture",async()=>{const e=await r("spectronaut-hye-precursor.tsv"),n=await o(e);(0,t.E3)(n.rowCount>0,!0);const a=n.columns.toList().find(e=>e.semType===s.iu.INTENSITY&&!e.name.startsWith("log2(")&&(e.name.startsWith("CondA_")||e.name.startsWith("CondB_")));(0,t.E3)(void 0!==a,!0),(0,t.E3)(n.col("PG.ProteinGroups")?.semType,s.iu.PROTEIN_ID)}),(0,t.t6)("sniffIsPrecursor routes by header",async()=>{const e=["R.FileName","R.Condition","R.Replicate","PG.ProteinGroups","PG.Organisms","PG.Quantity","EG.Qvalue","EG.ModifiedPeptide","FG.Charge","PEP.StrippedSequence"].join("\t"),n=["run_CondA_1","CondA","1","P1","Homo sapiens","10","0.001","_PEP_","2","PEP"].join("\t"),o=["R.FileName","R.Condition","R.Replicate","PG.ProteinGroups","PG.Organisms","PG.IBAQ"].join("\t"),r=["run_CondA_1","CondA","1","P1","Homo sapiens","10"].join("\t");(0,t.E3)(await(0,x.sniffIsPrecursor)(new File([e+"\n"+n],"p.tsv")),!0),(0,t.E3)(await(0,x.sniffIsPrecursor)(new File([o+"\n"+r],"pg.tsv")),!1)}),(0,t.t6)("stream path matches text path",async()=>{const e=D(n),r=await(0,A.parseSpectronautText)(e),s=await o(e);(0,t.E3)(s.rowCount,r.rowCount);const c=a(r),u=a(s);(0,t.E3)(u.join(","),c.join(","));for(const e of c)(0,t.E3)(null!==s.col(`log2(${e})`),null!==r.col(`log2(${e})`));(0,t.E3)(s.getTag("proteomics.source"),r.getTag("proteomics.source")),(0,t.E3)(s.getTag("proteomics.preNormalized"),r.getTag("proteomics.preNormalized"));const m=(0,l.f)(r),p=(0,l.f)(s);(0,t.E3)(null!==p,null!==m),m&&p&&((0,t.E3)(p.group1.columns.length,m.group1.columns.length),(0,t.E3)(p.group2.columns.length,m.group2.columns.length));const d=i(r),f=i(s);(0,t.E3)(f.map.size,d.map.size);for(const[e,n]of d.map){const o=f.map.get(e);(0,t.E3)(void 0!==o,!0);for(const e of c){const a=r.col(e),i=s.col(e),l=a.isNone(n),c=i.isNone(o);if((0,t.E3)(c,l),!l&&!c){const e=a.get(n),r=i.get(o);(0,t.E3)(Math.abs(e-r)<=.001,!0)}}}}),(0,t.t6)("streaming filter parity",async()=>{const e=D({...n,proteins:[{id:"KEEP1"},{id:"KEEP2"}],extraRows:[{id:"CON__C1",qValue:.001},{id:"REV__R1",qValue:.001},{id:"HIGHQ",qValue:.05},{id:"PROF",qValue:"Profiled"},{id:"EMPTYQ",qValue:""}]}),r=await o(e),s=r.col("PG.ProteinGroups"),a=new Set;for(let e=0;e<r.rowCount;e++)a.add(String(s.get(e)));(0,t.E3)(a.has("CON__C1"),!1),(0,t.E3)(a.has("REV__R1"),!1),(0,t.E3)(a.has("HIGHQ"),!1),(0,t.E3)(a.has("PROF"),!0),(0,t.E3)(a.has("EMPTYQ"),!0),(0,t.E3)(r.rowCount,4)}),(0,t.t6)("by-design-filtered rows are not counted malformed",async()=>{const e=D({...n,proteins:[{id:"KEEP1"},{id:"KEEP2"}],extraRows:[{id:"CON__C1",qValue:.001},{id:"REV__R1",qValue:.001},{id:"HIGHQ",qValue:.05}]}),{df:o,infos:r}=await c(e),s=o.col("PG.ProteinGroups"),a=new Set;for(let e=0;e<o.rowCount;e++)a.add(String(s.get(e)));(0,t.E3)(a.has("KEEP1"),!0),(0,t.E3)(a.has("KEEP2"),!0),(0,t.E3)(a.has("CON__C1"),!1),(0,t.E3)(a.has("REV__R1"),!1),(0,t.E3)(a.has("HIGHQ"),!1),(0,t.E3)(o.rowCount,2);const i=r.filter(e=>/malformed/i.test(e));(0,t.E3)(i.length,0)}),(0,t.t6)("truncated line is counted malformed",async()=>{const e=D({...n,proteins:[{id:"KEEP1"},{id:"KEEP2"}]})+"\nfile\tCondA\t1",{df:o,infos:r}=await c(e),s=o.col("PG.ProteinGroups"),a=new Set;for(let e=0;e<o.rowCount;e++)a.add(String(s.get(e)));(0,t.E3)(a.has("KEEP1"),!0),(0,t.E3)(a.has("KEEP2"),!0),(0,t.E3)(o.rowCount,2);const i=r.some(e=>/skipped \d+ malformed line\(s\)/.test(e));(0,t.E3)(i,!0)}),(0,t.t6)("empty-protein rows are filtered silently (streaming↔text parity)",async()=>{const e=D({...n,proteins:[{id:"KEEP1"},{id:"KEEP2"}],extraRows:[{id:"",qValue:.001},{id:"",qValue:.002}]}),{df:o,infos:r}=await c(e),s=o.col("PG.ProteinGroups"),a=new Set;for(let e=0;e<o.rowCount;e++)a.add(String(s.get(e)));(0,t.E3)(a.has("KEEP1"),!0),(0,t.E3)(a.has("KEEP2"),!0),(0,t.E3)(a.has(""),!1),(0,t.E3)(o.rowCount,2);const i=r.filter(e=>/malformed/i.test(e));(0,t.E3)(i.length,0)}),(0,t.t6)("both-numeric-casts-null rows are filtered silently (streaming↔text parity)",async()=>{const e=D({...n,proteins:[{id:"KEEP1"},{id:"KEEP2"}],extraRows:[{id:"NULLPAIR",quantity:"NaN",qValue:"NA"}]}),{df:o,infos:r}=await c(e);(0,t.E3)(o.rowCount,2);const s=r.filter(e=>/malformed/i.test(e));(0,t.E3)(s.length,0)}),(0,t.t6)("streaming tag set and groups",async()=>{const e=await o(D(n));(0,t.E3)(e.getTag("proteomics.source"),"spectronaut"),(0,t.E3)(e.getTag("proteomics.preNormalized"),"true");const r=(0,l.f)(e);(0,t.E3)(null!==r,!0),r&&((0,t.E3)(r.group1.columns.length,2),(0,t.E3)(r.group2.columns.length,2))}),(0,t.t6)("streaming output equals duckdb golden",async()=>{const e=JSON.parse(await r("spectronaut-hye-precursor-golden.json")),n=await r("spectronaut-hye-precursor.tsv"),s=await o(n),{map:l}=i(s),c=a(s),u=Object.keys(e);(0,t.E3)(u.length>0,!0);for(const n of u){const o=n.match(/^(.*?)((?:Cond[A-Za-z]+)_\d+)$/);(0,t.E3)(null!==o,!0);const r=o[1],a=o[2],i=l.get(r);(0,t.E3)(void 0!==i,!0);const c=s.col(a);(0,t.E3)(null!==c,!0),(0,t.E3)(c.isNone(i),!1);const u=c.get(i);(0,t.E3)(Math.abs(u-e[n].quantity)<=.001,!0)}const m=new Set;for(const[e,t]of l)for(const n of c)s.col(n).isNone(t)||m.add(`${e}${n}`);const p=new Set(u);(0,t.E3)(m.size,p.size);for(const e of m)(0,t.E3)(p.has(e),!0);for(const e of p)(0,t.E3)(m.has(e),!0)}),(0,t.t6)("duckdb fallback tooling is committed",async()=>{(0,t.E3)(!0,!0),(0,t.E3)(!0,!0),(0,t.E3)("-- Aggregate a long-form Spectronaut Report (peptide/precursor/fragment-level rows)\n-- down to one row per (protein-group × condition × replicate), in the shape\n-- packages/Proteomics/src/parsers/spectronaut-parser.ts expects.\n--\n-- This is the bundled, documented manual fallback (D-05) for a Spectronaut report\n-- too large for the in-browser streaming importer, AND the D-04 equivalence oracle\n-- the Wave-0 golden test pins to.\n--\n-- Template tokens __IN_PATH__ and __OUT_PATH__ are replaced by the shell wrapper\n-- before this script is passed to duckdb. (DuckDB's COPY ... TO does not accept\n-- variables, so we can't use SET VARIABLE here.)\n\n-- Streaming aggregation — duckdb spills to disk if it can't fit memory.\nPRAGMA memory_limit='8GB';\nPRAGMA threads=8;\n\nCOPY (\n SELECT\n \"PG.ProteinGroups\",\n -- DIVERGENCE FROM /tmp/spectronaut-aggregate.sql: the two carry-along\n -- any_value() SELECT terms for the gene-symbol and protein-accession columns\n -- (present in the /tmp original) were DROPPED here. The package's Spectronaut\n -- data (files/demo/spectronaut-hye-mix.tsv and the synthetic precursor\n -- fixture) does not carry those two columns and\n -- pivotSpectronaut/aggToPivotResult never consume them, so they are not part\n -- of the parity contract; keeping them would Binder-Error duckdb on the\n -- fixture (ignore_errors does NOT cover Binder Errors) and the entire Wave-0\n -- oracle chain (golden → sidecar → 12-03 golden test) would have no source.\n --\n -- ============================ WARNING ============================\n -- REFERENCE-FILE-ONLY: the CASE below is a one-off correction for the\n -- mislabeled reference file `2026-05-13 BP DMD WT.tsv` ONLY. Cross-tab\n -- against R.FileName showed every WT* filename tagged DMD and every DMD*\n -- filename tagged WT (24/24); this restores the convention so DE direction\n -- matches what the filenames imply. It is a STRUCTURAL NO-OP on any data\n -- whose R.Condition is not literally 'DMD'/'WT' — including the CondA/CondB\n -- synthetic fixture, which is exactly why this same script doubles as the\n -- D-04 golden oracle without perturbing the golden. The streaming TS\n -- aggregator MUST NOT port this flip (RESEARCH Pitfall 1 — the single\n -- highest-risk parity trap). Do not \"generalize\" or remove it either: the\n -- manual-fallback path still needs it for the mislabeled reference file.\n -- =================================================================\n CASE \"R.Condition\"\n WHEN 'DMD' THEN 'WT'\n WHEN 'WT' THEN 'DMD'\n ELSE \"R.Condition\"\n END AS \"R.Condition\",\n \"R.Replicate\",\n any_value(\"R.FileName\") AS \"R.FileName\",\n -- PG.Quantity is constant per (protein-group, run) in Spectronaut output;\n -- max() collapses the precursor-level duplicates safely.\n max(TRY_CAST(\"PG.Quantity\" AS DOUBLE)) AS \"PG.Quantity\",\n -- Best precursor q-value backing this protein in this run.\n min(TRY_CAST(\"EG.Qvalue\" AS DOUBLE)) AS \"EG.Qvalue\"\n FROM read_csv(\n '__IN_PATH__',\n delim='\\t',\n header=true,\n sample_size=-1, -- scan everything for type inference; columns are messy\n ignore_errors=true, -- tolerate stray malformed lines in a 2.6 GB file\n nullstr=['', 'NaN', 'NA']\n )\n WHERE\n -- Mirror the parser's precursor-level filter: drop EG rows with q-value > 0.01.\n -- Non-numeric q-values (e.g. 'Profiled') pass — same as the TS parser.\n (TRY_CAST(\"EG.Qvalue\" AS DOUBLE) IS NULL OR TRY_CAST(\"EG.Qvalue\" AS DOUBLE) <= 0.01)\n -- Drop decoys / contaminants up front; parser does this too but it's cheaper here.\n AND \"PG.ProteinGroups\" IS NOT NULL\n AND \"PG.ProteinGroups\" NOT LIKE 'CON\\_\\_%' ESCAPE '\\'\n AND \"PG.ProteinGroups\" NOT LIKE 'REV\\_\\_%' ESCAPE '\\'\n GROUP BY \"PG.ProteinGroups\", \"R.Condition\", \"R.Replicate\"\n) TO '__OUT_PATH__' (FORMAT csv, DELIMITER '\\t', HEADER);\n\n-- Summary so we can sanity-check the collapse ratio.\nSELECT\n count(*) AS output_rows,\n count(DISTINCT \"PG.ProteinGroups\") AS proteins,\n count(DISTINCT (\"R.Condition\" || '_' || \"R.Replicate\")) AS samples,\n list(DISTINCT \"R.Condition\") AS conditions\nFROM read_csv('__OUT_PATH__', delim='\\t', header=true);\n".includes("max(TRY_CAST"),!0),(0,t.E3)('#!/usr/bin/env bash\n# Collapse a long-form Spectronaut Report into the protein-group × sample shape\n# the Proteomics package\'s parseSpectronautText parser consumes.\n#\n# This is the documented MANUAL FALLBACK for a Spectronaut report too large for\n# the in-browser streaming importer: run it locally, then import the small\n# aggregated .tsv it produces. It is also the D-04 equivalence oracle the Wave-0\n# golden test pins to (see files/demo/README.md).\n#\n# Run: tools/spectronaut-aggregate.sh <input.tsv> [output.tsv]\n#\n# Requires the `duckdb` CLI on PATH (v1.3.0 used to derive the committed golden).\n\nset -euo pipefail\n\nif [[ $# -lt 1 ]]; then\n echo "Usage: $0 <input.tsv> [output.tsv]" >&2\n exit 1\nfi\n\nIN="$1"\nOUT="${2:-${IN%.tsv}.aggregated.tsv}"\nSQL="$(dirname "$0")/spectronaut-aggregate.sql"\n\nif [[ ! -f "$IN" ]]; then\n echo "Input not found: $IN" >&2\n exit 1\nfi\n\necho "Aggregating: $IN"\necho "Output: $OUT"\n\n# Substitute paths into the SQL template. DuckDB\'s COPY ... TO doesn\'t accept\n# variables, so we materialize the SQL first. SQL single-quote escaping: double up\n# any embedded \' in the paths.\nIN_ESC="${IN//\\\'/\\\'\\\'}"\nOUT_ESC="${OUT//\\\'/\\\'\\\'}"\nTMP_SQL="$(mktemp -t spectronaut-aggregate.XXXXXX.sql)"\ntrap \'rm -f "$TMP_SQL"\' EXIT\nsed -e "s|__IN_PATH__|${IN_ESC}|g" -e "s|__OUT_PATH__|${OUT_ESC}|g" "$SQL" > "$TMP_SQL"\n\nduckdb < "$TMP_SQL"\n\necho\necho "Input size: $(du -h "$IN" | cut -f1)"\necho "Output size: $(du -h "$OUT" | cut -f1)"\n'.includes("spectronaut-aggregate.sql"),!0)})});var L=n(86);function F(e,t){return[t.join("\t"),...e.map(e=>e.join("\t"))].join("\n")}const I=["Comparison (group1/group2)","PG.ProteinGroups","PG.Genes","AVG Log2 Ratio","Qvalue","Pvalue"];function M(e,t,n,o,r,s){return[e,t,n,o,r,s]}function O(t){for(const n of t.viewers)if(n.type===e.VIEWER.FILTERS)return n;return null}function R(t={}){const{withDisplayName:n=!0,withSourceId:o=!0,withFlags:r=!0,withProteinId:a=!0,comparisons:i=["T1 / Control","T2 / Control","T1 / Control","T2 / Control"]}=t,l=[e.Column.fromStrings("Comparison (group1/group2)",i),e.Column.fromList("double","log2FC",Array.from({length:i.length},(e,t)=>t-1.5))];if(a){const t=e.Column.fromStrings("Primary Protein ID",i.map((e,t)=>`P${1e4+t}`));t.semType=s.iu.PROTEIN_ID,l.push(t)}if(n){const t=e.Column.fromStrings("Display Name",i.map((e,t)=>`Gene${t+1}`));t.semType=s.iu.DISPLAY_NAME,l.push(t)}if(o){const t=e.Column.fromStrings("Source ID",i.map((e,t)=>`ENSG${1e4+t}`));t.semType=s.iu.SOURCE_ID,l.push(t)}return r&&l.push(e.Column.fromBitSet("Flags",e.BitSet.create(i.length,e=>e%2==0))),e.DataFrame.fromColumns(l)}function G(e){return[["Comparison (group1/group2)","PG.ProteinGroups","PG.Genes","AVG Log2 Ratio","Qvalue","Pvalue"].join("\t"),...e.map(e=>e.join("\t"))].join("\n")}function k(t){for(const n of t.viewers)if(n.type===e.VIEWER.FILTERS)return!0;return!1}(0,t.L1)("SpectronautCandidates",()=>{(0,t.t6)("parses standard rows",async()=>{const e=F([M("Treatment / Control","P04637","TP53","2.5","1e-5","1e-6"),M("Treatment / Control","P38398","BRCA1","-2.3","1e-4","1e-5")],I),n=await(0,L.R)(e);(0,t.E3)(n.rowCount,2)}),(0,t.t6)("sets proteomics.source to spectronaut-candidates",async()=>{const e=F([M("A / B","P04637","TP53","2.5","1e-5","1e-6")],I),n=await(0,L.R)(e);(0,t.E3)(n.getTag("proteomics.source"),"spectronaut-candidates")}),(0,t.t6)("sets de_complete and de_method tags",async()=>{const e=F([M("A / B","P04637","TP53","2.5","1e-5","1e-6")],I),n=await(0,L.R)(e);(0,t.E3)(n.getTag("proteomics.de_complete"),"true"),(0,t.E3)(n.getTag("proteomics.de_method"),"spectronaut")}),(0,t.t6)("names contrast groups from the Comparison string (volcano legend)",async()=>{const e=F([M("DMT / WT","P04637","TP53","2.5","1e-5","1e-6"),M("DMT / WT","P38398","BRCA1","-2.3","1e-4","1e-5")],I),n=await(0,L.R)(e),o=(0,l.f)(n);(0,t.E3)(null!=o,!0);const r=[o.group1.name,o.group2.name].sort();(0,t.E3)(r[0],"DMT"),(0,t.E3)(r[1],"WT"),(0,t.E3)(o.group1.columns.length,0),(0,t.E3)(o.group2.columns.length,0)}),(0,t.t6)("renames AVG Log2 Ratio to log2FC",async()=>{const e=F([M("A / B","P04637","TP53","2.5","1e-5","1e-6")],I),n=await(0,L.R)(e);(0,t.E3)(null!==n.col("log2FC"),!0),(0,t.E3)(n.col("AVG Log2 Ratio"),null),(0,t.E3)(Math.abs(n.col("log2FC").get(0)-2.5)<.01,!0)}),(0,t.t6)("renames Qvalue to adj.p-value",async()=>{const e=F([M("A / B","P04637","TP53","2.5","0.001","0.0001")],I),n=await(0,L.R)(e);(0,t.E3)(null!==n.col("adj.p-value"),!0),(0,t.E3)(n.col("Qvalue"),null),(0,t.E3)(Math.abs(n.col("adj.p-value").get(0)-.001)<1e-6,!0)}),(0,t.t6)("renames Pvalue to p-value when present",async()=>{const e=F([M("A / B","P04637","TP53","2.5","0.001","0.0001")],I),n=await(0,L.R)(e);(0,t.E3)(null!==n.col("p-value"),!0),(0,t.E3)(n.col("Pvalue"),null)}),(0,t.t6)("works without a Pvalue column",async()=>{const e=F([["P04637","TP53","2.5","0.001"]],["PG.ProteinGroups","PG.Genes","AVG Log2 Ratio","Qvalue"]),n=await(0,L.R)(e);(0,t.E3)(n.rowCount,1),(0,t.E3)(n.col("p-value"),null),(0,t.E3)(null!==n.col("adj.p-value"),!0)}),(0,t.t6)("assigns canonical semantic types",async()=>{const e=F([M("A / B","P04637","TP53","2.5","0.001","0.0001")],I),n=await(0,L.R)(e);(0,t.E3)(n.col("PG.ProteinGroups").semType,s.iu.PROTEIN_ID),(0,t.E3)(n.col("PG.Genes").semType,s.iu.GENE_SYMBOL),(0,t.E3)(n.col("log2FC").semType,s.iu.LOG2FC),(0,t.E3)(n.col("adj.p-value").semType,s.iu.P_VALUE),(0,t.E3)(n.col("p-value").semType,s.iu.P_VALUE)}),(0,t.t6)("computes significant column from |log2FC| >= 1 and adj.p <= 0.05",async()=>{const e=F([M("A / B","P_sig_up","A","2.5","0.001","0.0001"),M("A / B","P_sig_down","B","-1.5","0.001","0.0001"),M("A / B","P_small_fc","C","0.3","0.001","0.0001"),M("A / B","P_big_qvalue","D","2.0","0.5","0.4"),M("A / B","P_just_inside","E","1.01","0.04","0.03")],I),n=(await(0,L.R)(e)).col("significant");(0,t.E3)(n.get(0),!0),(0,t.E3)(n.get(1),!0),(0,t.E3)(n.get(2),!1),(0,t.E3)(n.get(3),!1),(0,t.E3)(n.get(4),!0)}),(0,t.t6)("filters contam_ rows",async()=>{const e=F([M("A / B","P04637","TP53","2.5","0.001","0.0001"),M("A / B","contam_P99999","KRT1","0.1","0.5","0.4")],I),n=await(0,L.R)(e);(0,t.E3)(n.rowCount,1),(0,t.E3)(n.col("PG.ProteinGroups").get(0),"P04637")}),(0,t.t6)("filters rev_ decoy rows",async()=>{const e=F([M("A / B","P04637","TP53","2.5","0.001","0.0001"),M("A / B","rev_P12345","FAKE","0.1","0.5","0.4")],I),n=await(0,L.R)(e);(0,t.E3)(n.rowCount,1)}),(0,t.t6)("throws on missing protein-group column",async()=>{const e=F([["A / B","2.5","0.001"]],["Comparison","AVG Log2 Ratio","Qvalue"]);let n=!1;try{await(0,L.R)(e)}catch(e){n=!0,(0,t.E3)(String(e.message).includes("protein-group"),!0)}(0,t.E3)(n,!0)}),(0,t.t6)("throws on missing log2 ratio column",async()=>{const e=F([["P04637","TP53","0.001"]],["PG.ProteinGroups","PG.Genes","Qvalue"]);let n=!1;try{await(0,L.R)(e)}catch(e){n=!0,(0,t.E3)(String(e.message).includes("log2 ratio"),!0)}(0,t.E3)(n,!0)}),(0,t.t6)("throws on missing q-value column",async()=>{const e=F([["P04637","TP53","2.5"]],["PG.ProteinGroups","PG.Genes","AVG Log2 Ratio"]);let n=!1;try{await(0,L.R)(e)}catch(e){n=!0,(0,t.E3)(String(e.message).includes("q-value"),!0)}(0,t.E3)(n,!0)}),(0,t.t6)("accepts alternative column names (ProteinGroups, Log2 Ratio, Q-Value)",async()=>{const e=F([["P04637","TP53","2.5","0.001"]],["ProteinGroups","Genes","Log2 Ratio","Q-Value"]),n=await(0,L.R)(e);(0,t.E3)(n.rowCount,1),(0,t.E3)(null!==n.col("log2FC"),!0),(0,t.E3)(null!==n.col("adj.p-value"),!0)}),(0,t.t6)("keeps Comparison column for multi-comparison files",async()=>{const e=F([M("Treatment1 / Control","P04637","TP53","2.5","0.001","0.0001"),M("Treatment2 / Control","P04637","TP53","1.8","0.002","0.0005"),M("Treatment1 / Control","P38398","BRCA1","-2.3","0.001","0.0001")],I),n=await(0,L.R)(e);(0,t.E3)(n.rowCount,3),(0,t.E3)(null!==n.col("Comparison (group1/group2)"),!0)});const e=["Comparison (group1/group2)","PG.ProteinGroups","PG.Genes","AVG Log2 Ratio","Qvalue","Pvalue","AVG Group Quantity Numerator","AVG Group Quantity Denominator","Condition Numerator","Condition Denominator"];(0,t.t6)("flips reversed-comparison rows; canonical rows untouched",async()=>{const n=F([["DMD / WT","P1","G1","-2.0","0.001","0.0001","100","400","DMD","WT"],["WT / DMD","P2","G2","3.0","0.001","0.0001","800","100","WT","DMD"]],e),o=await(0,L.R)(n),r=o.col("Comparison (group1/group2)"),s=o.col("log2FC"),a=o.col("AVG Group Quantity Numerator"),i=o.col("AVG Group Quantity Denominator");(0,t.E3)(r.get(0),"DMD / WT"),(0,t.E3)(Math.abs(s.get(0)- -2)<1e-6,!0),(0,t.E3)(Math.abs(a.get(0)-100)<1e-4,!0),(0,t.E3)(Math.abs(i.get(0)-400)<1e-4,!0),(0,t.E3)(r.get(1),"DMD / WT"),(0,t.E3)(Math.abs(s.get(1)- -3)<1e-6,!0),(0,t.E3)(Math.abs(a.get(1)-100)<1e-4,!0),(0,t.E3)(Math.abs(i.get(1)-800)<1e-4,!0),(0,t.E3)(o.col("Condition Numerator").get(1),"DMD"),(0,t.E3)(o.col("Condition Denominator").get(1),"WT")}),(0,t.t6)("flips log2FC without AVG Group Quantity columns (no swap, no throw)",async()=>{const e=F([M("DMD / WT","P1","G1","-2.0","0.001","0.0001"),M("WT / DMD","P2","G2","3.0","0.001","0.0001")],I),n=await(0,L.R)(e),o=n.col("log2FC");(0,t.E3)(Math.abs(o.get(0)- -2)<1e-6,!0),(0,t.E3)(Math.abs(o.get(1)- -3)<1e-6,!0),(0,t.E3)(n.col("Comparison (group1/group2)").get(1),"DMD / WT"),(0,t.E3)(n.col("AVG Group Quantity Numerator"),null)}),(0,t.t6)("single-orientation file is not mirrored",async()=>{const e=F([M("Treatment / Control","P1","A","2.5","0.001","0.0001"),M("Treatment / Control","P2","B","-1.7","0.002","0.0005")],I),n=await(0,L.R)(e),o=n.col("log2FC");(0,t.E3)(Math.abs(o.get(0)-2.5)<1e-6,!0),(0,t.E3)(Math.abs(o.get(1)- -1.7)<1e-6,!0),(0,t.E3)(n.col("Comparison (group1/group2)").get(0),"Treatment / Control")}),(0,t.t6)("parses CSV when delimiter is comma",async()=>{const e=await(0,L.R)("PG.ProteinGroups,PG.Genes,AVG Log2 Ratio,Qvalue\nP04637,TP53,2.5,0.001\nP38398,BRCA1,-2.3,0.001");(0,t.E3)(e.rowCount,2),(0,t.E3)(null!==e.col("log2FC"),!0)}),(0,t.t6)("creates Primary Protein ID for semicolon-delimited IDs",async()=>{const e=F([M("A / B","P04637;Q9Y6R7","TP53","2.5","0.001","0.0001")],I),n=(await(0,L.R)(e)).col("Primary Protein ID");(0,t.E3)(null!==n,!0),(0,t.E3)(n.get(0),"P04637")})}),(0,t.L1)("Proteomics: 14-03",()=>{(0,t.t6)("filtersScopingNoFlags",async()=>{const e=R(),n=v.shell.addTableView(e);try{const o=(0,x.dockComparisonFilterIfMultiContrast)(n,e);(0,t.E3)(o,!0),(0,t.E3)(null!==O(n),!0)}finally{n.close()}}),(0,t.t6)("filtersScopingSingleContrast",async()=>{const e=R({comparisons:["T1 / Control","T1 / Control","T1 / Control"]}),n=v.shell.addTableView(e);try{const o=(0,x.dockComparisonFilterIfMultiContrast)(n,e);(0,t.E3)(o,!1),(0,t.E3)(O(n),null)}finally{n.close()}}),(0,t.t6)("filtersScopingFallbackToProteinIdWhenNoDisplayName",async()=>{const e=R({withDisplayName:!1,withSourceId:!1}),n=v.shell.addTableView(e);try{const o=(0,x.dockComparisonFilterIfMultiContrast)(n,e);(0,t.E3)(o,!0),(0,t.E3)(null!==O(n),!0)}finally{n.close()}})});const $=["Homo sapiens","Saccharomyces cerevisiae","Escherichia coli"];(0,t.L1)("SpectronautCandidates E2E",()=>{(0,t.t6)("parses HYE candidates fixture and reproduces expected DE signal",async()=>{const e=await je.files.readAsText("demo/spectronaut-hye-candidates.tsv"),n=await(0,L.R)(e);(0,t.E3)(n.rowCount,93),(0,t.E3)(n.getTag("proteomics.source"),"spectronaut-candidates"),(0,t.E3)(n.getTag("proteomics.de_complete"),"true"),(0,t.E3)(n.getTag("proteomics.de_method"),"spectronaut"),(0,t.E3)(null!==n.col("log2FC"),!0),(0,t.E3)(null!==n.col("adj.p-value"),!0),(0,t.E3)(null!==n.col("p-value"),!0),(0,t.E3)(null!==n.col("significant"),!0),(0,t.E3)(n.col("AVG Log2 Ratio"),null),(0,t.E3)(n.col("Qvalue"),null),(0,t.E3)(n.col("Pvalue"),null),(0,t.E3)(n.col("ProteinGroups").semType,s.iu.PROTEIN_ID),(0,t.E3)(n.col("log2FC").semType,s.iu.LOG2FC),(0,t.E3)(n.col("p-value").semType,s.iu.P_VALUE),(0,t.E3)(n.col("adj.p-value").semType,s.iu.P_VALUE);const o=n.col("log2FC"),r=n.col("significant");let a=0,i=0,l=0;for(let e=0;e<n.rowCount;e++)r.get(e)?o.get(e)>0?a++:i++:l++;(0,t.E3)(a,26),(0,t.E3)(i,17),(0,t.E3)(l,50);const c=n.col("Organisms"),u=new Set;for(let e=0;e<n.rowCount;e++){const t=c.get(e);"string"==typeof t&&u.add(t)}for(const e of $){const n=Array.from(u).some(t=>t.includes(e));(0,t.E3)(n,!0)}}),(0,t.t6)("multi-comparison file docks a Comparison Filters viewer",async()=>{const e=await(0,L.R)(G([["T1 / Control","P1","G1","2.0","0.001","0.0001"],["T2 / Control","P2","G2","-1.7","0.002","0.0005"],["T1 / Control","P3","G3","1.2","0.01","0.005"]])),n=v.shell.addTableView(e);try{const o=(0,x.dockComparisonFilterIfMultiContrast)(n,e);(0,t.E3)(o,!0),(0,t.E3)(k(n),!0)}finally{n.close()}}),(0,t.t6)("single-comparison file docks no Filters viewer",async()=>{const e=await(0,L.R)(G([["T1 / Control","P1","G1","2.0","0.001","0.0001"],["T1 / Control","P2","G2","-1.7","0.002","0.0005"]])),n=v.shell.addTableView(e);try{const o=(0,x.dockComparisonFilterIfMultiContrast)(n,e);(0,t.E3)(o,!1),(0,t.E3)(k(n),!1)}finally{n.close()}}),(0,t.t6)("candidates import auto-opens the volcano",async()=>{const n=await(0,L.R)(G([["T1 / Control","P1","G1","2.0","0.001","0.0001"],["T1 / Control","P2","G2","-1.7","0.002","0.0005"],["T1 / Control","P3","G3","0.1","0.9","0.8"]])),o=(0,x.openCandidatesAnalysisView)(n);try{let n=0,r=null;for(const t of o.viewers)t.type===e.VIEWER.SCATTER_PLOT&&(n++,r=t);(0,t.E3)(n,1),(0,t.E3)(r.props.xColumnName,"log2FC")}finally{o.close()}})});var B=n(119);function U(e,t){return[t.join("\t"),...e.map(e=>e.join("\t"))].join("\n")}const j=["Protein","Protein ID","Entry Name","Gene","Length","Organism","Protein Description","Sample1 Spectral Count","Sample1 Intensity","Sample1 MaxLFQ Intensity","Sample2 Spectral Count","Sample2 Intensity","Sample2 MaxLFQ Intensity"];function V(e,t,n,o,r,s){return[`sp|${e}|${t}_HUMAN`,e,`${t}_HUMAN`,t,"500","Homo sapiens",`${t} protein`,"12",n,o,"15",r,s]}(0,t.L1)("FragPipe",()=>{(0,t.t6)("parses standard rows",async()=>{const e=U([V("P12345","BRCA1","10000","12000","20000","24000"),V("Q67890","TP53","30000","36000","40000","48000")],j),n=await(0,B.p)(e);(0,t.E3)(n.rowCount,2)}),(0,t.t6)("filters contam_ rows",async()=>{const e=U([V("P12345","BRCA1","10000","12000","20000","24000"),V("contam_P99999","KRT1","30000","36000","40000","48000")],j),n=await(0,B.p)(e);(0,t.E3)(n.rowCount,1),(0,t.E3)(n.col("Protein ID").get(0),"P12345")}),(0,t.t6)("filters rev_ rows",async()=>{const e=U([V("P12345","BRCA1","10000","12000","20000","24000"),V("rev_P99999","DECOY","30000","36000","40000","48000")],j),n=await(0,B.p)(e);(0,t.E3)(n.rowCount,1)}),(0,t.t6)("filters CON__/REV__ rows for MaxQuant-style FASTAs",async()=>{const e=U([V("P12345","BRCA1","10000","12000","20000","24000"),V("CON__P99999","KRT1","30000","36000","40000","48000"),V("REV__P88888","FAKE1","50000","60000","70000","80000")],j),n=await(0,B.p)(e);(0,t.E3)(n.rowCount,1)}),(0,t.t6)("assigns semantic types",async()=>{const e=U([V("P12345","BRCA1","10000","12000","20000","24000")],j),n=await(0,B.p)(e);(0,t.E3)(n.col("Protein ID")?.semType,s.iu.PROTEIN_ID),(0,t.E3)(n.col("Gene")?.semType,s.iu.GENE_SYMBOL),(0,t.E3)(n.col("Sample1 MaxLFQ Intensity")?.semType,s.iu.INTENSITY)}),(0,t.t6)("prefers MaxLFQ for log2 transform",async()=>{const e=U([V("P12345","BRCA1","1024","2048","4096","8192")],j),n=await(0,B.p)(e);(0,t.E3)(null!==n.col("log2(Sample1 MaxLFQ Intensity)"),!0),(0,t.E3)(null!==n.col("log2(Sample2 MaxLFQ Intensity)"),!0),(0,t.E3)(n.col("log2(Sample1 Intensity)"),null);const o=n.col("log2(Sample1 MaxLFQ Intensity)");(0,t.E3)(Math.abs(o.get(0)-11)<.001,!0)}),(0,t.t6)("falls back to bare Intensity when no MaxLFQ present",async()=>{const e=U([["sp|P12345|BRCA1_HUMAN","P12345","BRCA1","12","1024","15","4096"]],["Protein","Protein ID","Gene","Sample1 Spectral Count","Sample1 Intensity","Sample2 Spectral Count","Sample2 Intensity"]),n=await(0,B.p)(e);(0,t.E3)(null!==n.col("log2(Sample1 Intensity)"),!0),(0,t.E3)(null!==n.col("log2(Sample2 Intensity)"),!0);const o=n.col("log2(Sample1 Intensity)");(0,t.E3)(Math.abs(o.get(0)-10)<.001,!0)}),(0,t.t6)("zero intensity produces FLOAT_NULL in log2",async()=>{const e=U([V("P12345","BRCA1","0","0","4096","8192")],j),n=(await(0,B.p)(e)).col("log2(Sample1 MaxLFQ Intensity)");(0,t.E3)(n.isNone(0),!0)}),(0,t.t6)("primary protein ID extracted from semicolon-delimited",async()=>{const e=U([["sp|P12345|BRCA1_HUMAN","P12345;Q67890","BRCA1_HUMAN","BRCA1;BRCA2","500","Homo sapiens","BRCA1 protein","12","10000","12000","15","20000","24000"]],j),n=await(0,B.p)(e),o=n.col("Primary Protein ID");(0,t.E3)(null!==o,!0),o&&(0,t.E3)(o.get(0),"P12345");const r=n.col("Primary Gene Name");(0,t.E3)(null!==r,!0),r&&(0,t.E3)(r.get(0),"BRCA1")}),(0,t.t6)("proteomics.source tag set to fragpipe",async()=>{const e=U([V("P12345","BRCA1","10000","12000","20000","24000")],j),n=await(0,B.p)(e);(0,t.E3)(n.getTag("proteomics.source"),"fragpipe")}),(0,t.t6)("intensity columns survive as raw plus log2 pair",async()=>{const e=U([V("P12345","BRCA1","10000","12000","20000","24000")],j),n=await(0,B.p)(e);(0,t.E3)(null!==n.col("Sample1 MaxLFQ Intensity"),!0),(0,t.E3)(null!==n.col("log2(Sample1 MaxLFQ Intensity)"),!0)})});const q={group1:{name:"Control",columns:["log2(Ctrl_1 MaxLFQ Intensity)","log2(Ctrl_2 MaxLFQ Intensity)"]},group2:{name:"Treatment",columns:["log2(Treat_1 MaxLFQ Intensity)","log2(Treat_2 MaxLFQ Intensity)"]}},Y=["TP53","AKT1","F2"],z=["BRCA1","PRKCD"],H=["EGFR","MTOR","HRAS"];(0,t.L1)("FragPipe E2E",()=>{(0,t.t6)("full pipeline (parse → normalize → impute → DE) on fragpipe-smoke-test.tsv",async()=>{const e=await je.files.readAsText("demo/fragpipe-smoke-test.tsv"),n=await(0,B.p)(e);(0,t.E3)(n.rowCount,8),(0,t.E3)(n.getTag("proteomics.source"),"fragpipe"),(0,t.E3)(n.col("Protein ID").semType,s.iu.PROTEIN_ID),(0,t.E3)(n.col("Gene").semType,s.iu.GENE_SYMBOL),(0,t.E3)(null!==n.col("log2(Ctrl_1 MaxLFQ Intensity)"),!0),(0,t.E3)(null!==n.col("log2(Treat_2 MaxLFQ Intensity)"),!0),(0,l.$Y)(n,q),(0,t.E3)(null!==n.getTag("proteomics.groups"),!0);const o=[...q.group1.columns,...q.group2.columns];(0,c.aj)(n,o),(0,t.E3)(n.getTag("proteomics.normalized"),"true");for(const e of o)(0,t.E3)(Math.abs(n.col(e).stats.med)<1e-4,!0);(0,u.Q2)(n,o),(0,t.E3)(n.getTag("proteomics.imputed"),"true"),(0,m.ps)(n,q.group1.columns,q.group2.columns,"Control","Treatment",1,.05),(0,t.E3)(n.getTag("proteomics.de_complete"),"true"),(0,t.E3)(null!==n.col("log2FC"),!0),(0,t.E3)(null!==n.col("p-value"),!0),(0,t.E3)(null!==n.col("adj.p-value"),!0),(0,t.E3)(null!==n.col("significant"),!0);const r={},a=n.col("Gene");for(let e=0;e<n.rowCount;e++)r[a.get(e)]=e;const i=n.col("log2FC"),p=n.col("significant");for(const e of Y)(0,t.E3)(i.get(r[e])>1,!0),(0,t.E3)(p.get(r[e]),!0);for(const e of z)(0,t.E3)(i.get(r[e])<-1,!0),(0,t.E3)(p.get(r[e]),!0);for(const e of H)(0,t.E3)(Math.abs(i.get(r[e]))<.5,!0),(0,t.E3)(p.get(r[e]),!1)})});var Q=n(623),W=n(70);function K(e){const t=v.dapi.userDataStorage.constructor.prototype,n=t.get,o=t.put;return e.get&&(t.get=e.get),e.put&&(t.put=e.put),()=>{t.get=n,t.put=o}}const J={Nucleus:"#FF6B6B",Cytoplasm:"#ECDC44",Mitochondria:"#45B7D1",ER:"#96CEB4",Golgi:"#FAAFFE","Plasma Membrane":"#DDA0DD",Lysosome:"#F39C12",Peroxisome:"#E17055",Ribosome:"#A29BFE",Extracellular:"#FD79A8",Vesicles:"#FDCB6E",Unknown:"#CCCCCC"};(0,t.L1)("SubcellularLocation",()=>{(0,t.t6)("SEMTYPE.SUBCELLULAR_LOCATION literal is stable",async()=>{(0,t.E3)(s.iu.SUBCELLULAR_LOCATION,"Proteomics-SubcellularLocation")}),(0,t.t6)("every ORGANISM_LIST code has an ORGANISM_TAXONOMY mapping",async()=>{for(const e of h.Ae)(0,t.E3)(typeof Q.JO[e.code],"number"),(0,t.E3)(Q.JO[e.code]>0,!0)}),(0,t.t6)("classifier: subcellular field used before GO fallback",async()=>{(0,t.E3)((0,Q.ZF)("Nucleus {ECO:0000269}.","mitochondrion [GO:0005739]"),"Nucleus")}),(0,t.t6)("classifier: GO used only when subcellular field has no match",async()=>{(0,t.E3)((0,Q.ZF)("","cytoplasm [GO:0005737]"),"Cytoplasm"),(0,t.E3)((0,Q.ZF)("phosphopyruvate hydratase complex","ribosome [GO:0005840]"),"Ribosome")}),(0,t.t6)("classifier: earliest character position wins across categories",async()=>{(0,t.E3)((0,Q.ZF)("Mitochondrion. Nucleus.",""),"Mitochondria"),(0,t.E3)((0,Q.ZF)("Nucleus. Mitochondrion.",""),"Nucleus")}),(0,t.t6)("classifier: ties broken by keyword-map insertion order (Nucleus before Cytoplasm)",async()=>{(0,t.E3)((0,Q.ZF)("nucleus",""),"Nucleus"),(0,t.E3)((0,Q.ZF)("cytoplasm",""),"Cytoplasm")}),(0,t.t6)("classifier: raw string not pre-stripped (matches inside SUBCELLULAR LOCATION: ... {ECO})",async()=>{(0,t.E3)((0,Q.ZF)("SUBCELLULAR LOCATION: Cytoplasm {ECO:0000269|PubMed:1234}. Nucleus {ECO:0000250}.",""),"Cytoplasm")}),(0,t.t6)("classifier: empty / no-match → Unknown",async()=>{(0,t.E3)((0,Q.ZF)("",""),"Unknown"),(0,t.E3)((0,Q.ZF)("some unrelated free text","nothing spatial here"),"Unknown")}),(0,t.t6)("LOCATION_COLORS: all 12 ARGB ints equal the locked hex conversion",async()=>{const e=Object.keys(J);(0,t.E3)(e.length,12);for(const n of e){const e=4278190080|parseInt(J[n].slice(1),16);(0,t.E3)(Q.Jn[n],e)}(0,t.E3)(Object.keys(Q.Jn).length,12)}),(0,t.t6)("mergeStreamTsv: header skipped, positional parse, reviewed beats unreviewed",async()=>{const e=["Entry\tSubcellular location [CC]\tGene Ontology (cellular component)\tReviewed\tGene Names (primary)","P1\tNucleus.\t\tunreviewed\tGENA","P1\tMitochondrion.\t\treviewed\tGENA","P2\t\t\tunreviewed\tGENB"].join("\n"),{locByAcc:n,geneByAcc:o}=(0,Q.y)(e);(0,t.E3)(n.get("P1"),"Mitochondria"),(0,t.E3)(n.get("P2"),"Unknown"),(0,t.E3)(o.get("P1"),"GENA"),(0,t.E3)(o.get("P2"),"GENB")}),(0,t.t6)("mergeStreamTsv: existing Unknown is overwritten by a later non-Unknown",async()=>{const e=["Entry\tSubcellular location [CC]\tGO\tReviewed\tGene","P9\t\t\tunreviewed\tG9","P9\tGolgi apparatus.\t\tunreviewed\tG9"].join("\n"),{locByAcc:n}=(0,Q.y)(e);(0,t.E3)(n.get("P9"),"Golgi")}),(0,t.t6)("runWithConcurrency caps in-flight tasks at the supplied limit",async()=>{let e=0,n=0;const o=new Array(20).fill(0).map((e,t)=>t);await(0,Q.Pd)(o,6,async()=>(e++,e>n&&(n=e),await new Promise(e=>setTimeout(e,5)),e--,null)),(0,t.E3)(n<=6,!0,"concurrentMax should be ≤ 6"),(0,t.E3)(n>=2,!0,"should have observed parallel execution")}),(0,t.t6)("getSubcellularLocations emits non-decreasing progress per phase",async()=>{const e=v.dapi.fetchProxy;v.dapi.fetchProxy=async e=>{const t=/accession%3A([A-Z0-9]+)/.exec(e),n=t?t[1]:"P00000";return{ok:!0,status:200,text:async()=>(e=>`Entry\tSubcellular location [CC]\tGO\tReviewed\tGene Names (primary)\n${e}\tNucleus.\t\treviewed\tGENE1\n`)(n)}};const n=K({get:async()=>({}),put:async()=>{}});try{const e=[];for(let t=0;t<250;t++)e.push(`TESTB${String(t).padStart(5,"0")}`);const n=[],o=(e,t,o)=>n.push({done:e,total:t,phase:o});await(0,Q.n0)(e,"hsapiens",o);const r=n.filter(e=>"fetch-acc"===e.phase);(0,t.E3)(r.length,3),(0,t.E3)(r[0].total,3);for(let e=1;e<r.length;e++)(0,t.E3)(r[e].done>=r[e-1].done,!0,"fetch-acc done should be non-decreasing");const s=r[r.length-1];(0,t.E3)(s.done,s.total,"last fetch-acc tuple should have done === total")}finally{v.dapi.fetchProxy=e,n()}}),(0,t.t6)("getSubcellularLocations writes the cache incrementally during fetch",async()=>{const e=v.dapi.fetchProxy;let n=0;v.dapi.fetchProxy=async e=>{const t=0===n++?1e3:6e3;await new Promise(e=>setTimeout(e,t));const o=/accession%3A([A-Z0-9]+)/.exec(e),r=o?o[1]:"P00000";return{ok:!0,status:200,text:async()=>(e=>`Entry\tSubcellular location [CC]\tGO\tReviewed\tGene Names (primary)\n${e}\tNucleus.\t\treviewed\tGENE1\n`)(r)}};let o=0;const r=K({get:async()=>({}),put:async()=>{o++}});try{const e=[];for(let t=0;t<150;t++)e.push(`TESTC${String(t).padStart(5,"0")}`);await(0,Q.n0)(e,"hsapiens"),(0,t.E3)(o>=2,!0,`userDataStorage.put should be called >= 2 times (got ${o})`)}finally{v.dapi.fetchProxy=e,r()}},{timeout:3e4}),(0,t.t6)("STORE export matches the documented userDataStorage key",async()=>{(0,t.E3)(Q.er,"proteomics-subcell-loc")}),(0,t.t6)("ensureLocationColumn short-circuits on accession-set hash match",async()=>{const n=v.dapi.fetchProxy;let o=0;v.dapi.fetchProxy=async e=>{o++;const t=/accession%3A([A-Z0-9]+)/.exec(e),n=t?t[1]:"TESTD00";return{ok:!0,status:200,text:async()=>(e=>`Entry\tSubcellular location [CC]\tGO\tReviewed\tGene Names (primary)\n${e}\tNucleus.\t\treviewed\tGENE1\n`)(n)}};const r=K({get:async()=>({}),put:async()=>{}});try{const n=e.Column.fromStrings("Primary Protein ID",["TESTD01","TESTD02","TESTD03","TESTD04","TESTD05"]);n.semType=s.iu.PROTEIN_ID;const r=e.DataFrame.fromColumns([n]);await(0,W.MC)(r);const a=o;(0,t.E3)(a>=1,!0,"first call should fetch from UniProt"),await(0,W.MC)(r),(0,t.E3)(o,a,"second call on same accession set should short-circuit (no new fetch)"),n.set(0,"TESTD99"),await(0,W.MC)(r),(0,t.E3)(o>a,!0,"third call with mutated accession should fetch again")}finally{v.dapi.fetchProxy=n,r()}}),(0,t.t6)("ensureLocationColumn forwards progress through fetch + emits init-column",async()=>{const n=v.dapi.fetchProxy;v.dapi.fetchProxy=async e=>{const t=/accession%3A([A-Z0-9]+)/.exec(e),n=t?t[1]:"TESTE00";return{ok:!0,status:200,text:async()=>(e=>`Entry\tSubcellular location [CC]\tGO\tReviewed\tGene Names (primary)\n${e}\tNucleus.\t\treviewed\tGENE1\n`)(n)}};const o=K({get:async()=>({}),put:async()=>{}});try{const n=e.Column.fromStrings("Primary Protein ID",["TESTE01","TESTE02","TESTE03"]);n.semType=s.iu.PROTEIN_ID;const o=e.DataFrame.fromColumns([n]),r=[],a=(e,t,n)=>r.push(n);await(0,W.MC)(o,a),(0,t.E3)(r.includes("fetch-acc"),!0,"progress should fire at least once with phase=fetch-acc"),(0,t.E3)(r.includes("init-column"),!0,"progress should fire with phase=init-column after bulk-init"),(0,t.E3)(r[r.length-1],"init-column","init-column should be the final progress phase")}finally{v.dapi.fetchProxy=n,o()}})});var Z=n(935);function X(t,n){return e.DataFrame.fromColumns([e.Column.fromStrings(t,n)])}(0,t.L1)("Organisms",()=>{(0,t.t6)("resolveOrganismCode maps scientific names (incl. strain-qualified) to codes",async()=>{(0,t.E3)((0,Z.qj)("Homo sapiens"),"hsapiens"),(0,t.E3)((0,Z.qj)("Rattus norvegicus"),"rnorvegicus"),(0,t.E3)((0,Z.qj)("Escherichia coli (strain K12)"),"ecoli"),(0,t.E3)((0,Z.qj)("Saccharomyces cerevisiae (strain ATCC 204508 / S288c)"),"scerevisiae")}),(0,t.t6)("resolveOrganismCode returns undefined for unsupported / empty",async()=>{(0,t.E3)(void 0===(0,Z.qj)("Sus scrofa"),!0),(0,t.E3)(void 0===(0,Z.qj)(""),!0),(0,t.E3)(void 0===(0,Z.qj)(null),!0),(0,t.E3)(void 0===(0,Z.qj)(void 0),!0)}),(0,t.t6)("every ORGANISM_LIST display resolves back to its own code",async()=>{for(const e of Z.Ae)(0,t.E3)((0,Z.qj)(e.display),e.code)}),(0,t.t6)("detectOrganismCode: single-species PG.Organisms column → that code",async()=>{const e=X("PG.Organisms",["Rattus norvegicus","Rattus norvegicus","Rattus norvegicus"]);(0,t.E3)((0,Z.Vr)(e),"rnorvegicus")}),(0,t.t6)('detectOrganismCode: works on a generically named "Organism" column',async()=>{const e=X("Organism",["Homo sapiens","Homo sapiens"]);(0,t.E3)((0,Z.Vr)(e),"hsapiens")}),(0,t.t6)("detectOrganismCode: mixed empties/unknowns but one species → that code",async()=>{const e=X("PG.Organisms",["","Homo sapiens","Sus scrofa",""]);(0,t.E3)((0,Z.Vr)(e),"hsapiens")}),(0,t.t6)("detectOrganismCode: multi-species (HYE-style mix) → undefined (do not guess)",async()=>{const e=X("PG.Organisms",["Homo sapiens","Escherichia coli (strain K12)","Saccharomyces cerevisiae"]);(0,t.E3)(void 0===(0,Z.Vr)(e),!0)}),(0,t.t6)("detectOrganismCode: no organism column → undefined",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Gene",["CDK1","CCNB1"])]);(0,t.E3)(void 0===(0,Z.Vr)(n),!0)})});var ee=n(871);function te(){const t=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["P1","P2","P3"]),e.Column.fromFloat32Array("Intensity_S1",new Float32Array([1e3,4e3,16e3])),e.Column.fromFloat32Array("Intensity_S2",new Float32Array([2e3,8e3,32e3]))]);return t.col("Protein ID").semType=s.iu.PROTEIN_ID,t.col("Intensity_S1").semType=s.iu.INTENSITY,t.col("Intensity_S2").semType=s.iu.INTENSITY,t}function ne(t=100){const n=new Float32Array(t),o=new Float32Array(t);for(let e=0;e<t;e++)n[e]=.1*(e-t/2),o[e]=.001+e/t*.5;const r=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",Array.from({length:t},(e,t)=>`P${t}`)),e.Column.fromFloat32Array("log2FC",n),e.Column.fromFloat32Array("adj.p-value",o)]);return r.col("Protein ID").semType=s.iu.PROTEIN_ID,r.col("log2FC").semType=s.iu.LOG2FC,r.col("adj.p-value").semType=s.iu.P_VALUE,r}(0,t.L1)("Log2 Scale",()=>{(0,t.t6)("getIntensityOriginals: only the pristine (non-log2) intensity columns",async()=>{const e=te();(0,d.Kh)(e,["Intensity_S1","Intensity_S2"]);const n=(0,ee.ye)(e);(0,t.E3)(n.length,2,"two originals"),(0,t.E3)(n.includes("Intensity_S1")&&n.includes("Intensity_S2"),!0,"includes both raw columns"),(0,t.E3)(n.some(e=>e.startsWith("log2(")),!1,"excludes the log2 copies")}),(0,t.t6)("detectCurrentLog2Applied: transform vs copy is read from the values",async()=>{const e=te();(0,d.Kh)(e,["Intensity_S1","Intensity_S2"]),(0,t.E3)((0,ee.IZ)(e,(0,ee.ye)(e)),"transform","log2(x) columns read as transform");const n=te();(0,d.l3)(n,["Intensity_S1","Intensity_S2"]),(0,t.E3)((0,ee.IZ)(n,(0,ee.ye)(n)),"copy","copied columns read as copy")}),(0,t.t6)("applyLog2Scale: transform→copy rebuilds values, clears stale tags, is idempotent",async()=>{const e=te();(0,d.Kh)(e,["Intensity_S1","Intensity_S2"]),e.setTag("proteomics.normalized","true"),e.setTag("proteomics.de_complete","true"),e.setTag("proteomics.de_method","t-test"),(0,t.E3)(Math.abs(e.col("log2(Intensity_S1)").get(0)-Math.log2(1e3))<.001,!0,"starts transformed");const n=(0,ee.DA)(e,!0);(0,t.E3)(n,!0,"a real scale change returns true"),(0,t.E3)(e.col("log2(Intensity_S1)").get(0),1e3,"value is now the raw copy"),(0,t.E3)((0,ee.IZ)(e,(0,ee.ye)(e)),"copy","now reads as copy"),(0,t.E3)(e.getTag("proteomics.normalized")||"","","normalized tag cleared"),(0,t.E3)(e.getTag("proteomics.de_complete")||"","","de_complete tag cleared"),(0,t.E3)(e.getTag("proteomics.de_method")||"","","de_method tag cleared"),(0,t.E3)((0,ee.ye)(e).length,2,"still exactly two originals"),(0,t.E3)((0,ee.DA)(e,!0),!1,"no-op when scale already matches returns false")}),(0,t.t6)("applyLog2Scale: copy→transform restores the log2 transform",async()=>{const e=te();(0,d.l3)(e,["Intensity_S1","Intensity_S2"]);const n=(0,ee.DA)(e,!1);(0,t.E3)(n,!0,"scale change returns true"),(0,t.E3)(Math.abs(e.col("log2(Intensity_S2)").get(2)-Math.log2(32e3))<.001,!0,"transform re-applied to raw value"),(0,t.E3)((0,ee.IZ)(e,(0,ee.ye)(e)),"transform","reads as transform")}),(0,t.t6)("getIntensityOriginals: empty when no intensity columns",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["P1","P2"])]);n.col("Protein ID").semType=s.iu.PROTEIN_ID,(0,t.E3)((0,ee.ye)(n).length,0,"no originals"),(0,t.E3)((0,ee.DA)(n,!0),!1,"applyLog2Scale is a no-op with nothing to rescale")})});const oe="Enriched in group1",re="Enriched in group2",se="Not significant";function ae(t){const n=[e.Column.fromStrings("Protein ID",["P1","P2","P3"]),e.Column.fromFloat32Array("log2FC",new Float32Array([2,-2,.1])),e.Column.fromFloat32Array("adj.p-value",new Float32Array([.001,.5,.2]))];!1!==t?.withPValue&&n.push(e.Column.fromFloat32Array("p-value",new Float32Array([.04,.001,.2])));const o=e.DataFrame.fromColumns(n);return o.col("log2FC").semType=s.iu.LOG2FC,o.col("adj.p-value").semType=s.iu.P_VALUE,o.col("Protein ID").semType=s.iu.PROTEIN_ID,o}(0,t.L1)("Volcano",()=>{(0,t.t6)("ensureNegLog10Column: stable name, values re-init in place on metric toggle",async()=>{const e=ae(),n=(0,W.CK)(e,"adj.p-value"),o=e.columns.length,r=e.col(n).get(0),s=(0,W.CK)(e,"p-value");(0,t.E3)(n,s),(0,t.E3)(e.columns.length,o);const a=e.col(s).get(0);(0,t.E3)(Math.abs(r-3)<1e-4,!0),(0,t.E3)(Math.abs(a- -Math.log10(.04))<1e-4,!0),(0,t.E3)(Math.abs(r-a)>1,!0)}),(0,t.t6)("ensureDirectionColumn: parameterized by metric, in-place, ARGB map",async()=>{const e=ae(),n=(0,W.EO)(e,1,.05,"adj.p-value"),o=e.columns.length;(0,t.E3)(e.col(n).get(0),oe),(0,t.E3)(e.col(n).get(1),se),(0,W.EO)(e,1,.05,"p-value"),(0,t.E3)(e.columns.length,o),(0,t.E3)(e.col(n).get(0),oe),(0,t.E3)(e.col(n).get(1),re)}),(0,t.t6)("p-value metric guarded when column absent — stays on adj.p-value",async()=>{const e=ae({withPValue:!1}),n=(0,W.CK)(e,"p-value");(0,t.E3)(Math.abs(e.col(n).get(0)-3)<1e-4,!0);const o=(0,W.EO)(e,1,.05,"p-value");(0,t.E3)(e.col(o).get(0),oe)}),(0,t.t6)("ensureLocationColumn: SEMTYPE + locked LOCATION_COLORS, no network needed",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["","",""]),e.Column.fromFloat32Array("log2FC",new Float32Array([1,2,3])),e.Column.fromFloat32Array("adj.p-value",new Float32Array([.1,.2,.3]))]);n.col("Protein ID").semType=s.iu.PROTEIN_ID;const o=await(0,W.MC)(n),r=n.col(o);(0,t.E3)(r.semType,s.iu.SUBCELLULAR_LOCATION),(0,t.E3)(r.get(0),"Unknown"),(0,t.E3)(Object.keys(Q.Jn).length,12)}),(0,t.t6)("createVolcanoPlot: axis-chip-hiding stylesheet + marker class (custom labels are sole titles)",async()=>{const e=ae(),n=(0,W.gO)(e,{topNLabels:0});(0,t.E3)(n.root.classList.contains("proteomics-volcano"),!0,"volcano marker class set");const o=document.getElementById("proteomics-volcano-styles");(0,t.E3)(null!==o,!0,"scoped stylesheet injected"),(0,t.E3)(o.textContent.includes(".d4-vertical")&&o.textContent.includes(".d4-bottom-center"),!0,"hides both axis chips"),(0,t.E3)(o.textContent.includes(".proteomics-volcano"),!0,"rule is scoped"),(0,t.E3)(o.textContent.includes(".d4-vertical-right"),!1,"color selector preserved")}),(0,t.t6)("recomputeVolcano: Y, class, threshold lines stay consistent across Q↔P toggle",async()=>{const e=ae(),n=(0,W.gO)(e,{fcThreshold:1,pThreshold:.05}),o=n.props.yColumnName;await(0,W.nj)(e,n,"p-value","significance",1,.05),(0,t.E3)(n.props.yColumnName,o),(0,t.E3)(n.props.colorColumnName,"direction"),(0,t.E3)(Math.abs(e.col(o).get(1)- -Math.log10(.001))<1e-4,!0),(0,t.E3)(e.col("direction").get(1),re);const r=e.meta.formulaLines.items.length;await(0,W.nj)(e,n,"adj.p-value","significance",1,.05),(0,t.E3)(Math.abs(e.col(o).get(1)- -Math.log10(.5))<1e-4,!0),(0,t.E3)(e.col("direction").get(1),se),(0,t.E3)(e.meta.formulaLines.items.length,r)}),(0,t.t6)("toggle wiring: every metric × colorDim combination drives recomputeVolcano",async()=>{const e=ae(),n=(0,W.gO)(e,{}),o=n.props.yColumnName;for(const r of["adj.p-value","p-value"])for(const s of["significance","location"])await(0,W.nj)(e,n,r,s,1,.05),(0,t.E3)(n.props.yColumnName,o),(0,t.E3)(n.props.colorColumnName,"location"===s?"Subcellular Location":"direction")}),(0,t.t6)("recomputeVolcano: location color dim sets the Subcellular Location column",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["",""]),e.Column.fromFloat32Array("log2FC",new Float32Array([1,-1])),e.Column.fromFloat32Array("adj.p-value",new Float32Array([.01,.9]))]);n.col("Protein ID").semType=s.iu.PROTEIN_ID;const o=(0,W.gO)(n,{});await(0,W.nj)(n,o,"adj.p-value","location",1,.05),(0,t.E3)(o.props.colorColumnName,"Subcellular Location"),(0,t.E3)(n.col("Subcellular Location").semType,s.iu.SUBCELLULAR_LOCATION)}),(0,t.t6)("showVolcanoBusy attaches overlay, updateVolcanoBusy mutates, hideVolcanoBusy detaches",async()=>{const e=ae(),n=(0,W.gO)(e,{topNLabels:0});try{(0,t.E3)(null==n.root.querySelector("[data-volcano-busy]"),!0,"overlay should not exist before showVolcanoBusy"),(0,W.DI)(n,"Classifying subcellular locations…");const e=n.root.querySelector("[data-volcano-busy]");(0,t.E3)(null!=e,!0,"overlay should attach"),(0,t.E3)((e.textContent??"").includes("Classifying"),!0,"overlay should show the initial label"),(0,W.Bb)(n,"Fetching subcellular locations","15/80 chunks");const o=n.root.querySelector("[data-volcano-busy]").textContent??"";(0,t.E3)(o.includes("Fetching"),!0,"label should update"),(0,t.E3)(o.includes("15/80"),!0,"detail should update"),(0,W.kX)(n),(0,t.E3)(null==n.root.querySelector("[data-volcano-busy]"),!0,"overlay should be removed after hideVolcanoBusy")}finally{n.root.querySelectorAll("[data-volcano-busy], [data-volcano-counter], [data-volcano-axis-x], [data-volcano-axis-y]").forEach(e=>e.remove())}}),(0,t.t6)("ensureLocationColumn short-circuits warm-cache path within one tick",async()=>{const n=e.Column.fromStrings("Primary Protein ID",["P12345","P67890","P11111"]);n.semType=s.iu.PROTEIN_ID;const o=e.DataFrame.fromColumns([n,e.Column.fromFloat32Array("log2FC",new Float32Array([1.5,-2,.5])),e.Column.fromFloat32Array("adj.p-value",new Float32Array([.001,.01,.5]))]),r=function(e){const t=v.dapi.userDataStorage.constructor.prototype,n=t.get,o=t.put;return e.get&&(t.get=e.get),e.put&&(t.put=e.put),()=>{t.get=n,t.put=o}}({get:async()=>({P12345:"Cytoplasm",P67890:"Nucleus",P11111:"Membrane",__schema_v:"13-04-1"}),put:async()=>{}});try{const e=[],n=(t,n,o)=>{e.push(`${o}:${t}/${n}`)};await(0,W.MC)(o,n);const r=o.col("Subcellular Location")?.getTag("proteomics.location_acc_hash");(0,t.E3)(null!=r&&r.length>0,!0,"hash tag should be set after first ensureLocationColumn call"),e.length=0;const s=performance.now();await(0,W.MC)(o,n);const a=performance.now()-s;(0,t.E3)(a<50,!0,`short-circuit path should complete in <50ms; took ${a}ms`),(0,t.E3)(1===e.length&&"init-column:1/1"===e[0],!0,`short-circuit should emit exactly one init-column tick; got ${JSON.stringify(e)}`)}finally{r()}}),(0,t.t6)("axis-max override: set/get round-trips, pins symmetric X + 0-based Y, empty clears",async()=>{const e=ae(),n=(0,W.gO)(e,{topNLabels:0});(0,t.E3)(null===(0,W.GE)(e).xMax,!0,"xMax defaults to null"),(0,t.E3)(null===(0,W.GE)(e).yMax,!0,"yMax defaults to null"),(0,W.S6)(e,5,8);const o=(0,W.GE)(e);(0,t.E3)(o.xMax,5,"xMax round-trips"),(0,t.E3)(o.yMax,8,"yMax round-trips"),(0,W.f0)(n,e),(0,t.E3)(n.props.xMin,-5,"X pins symmetric: xMin = -xMax"),(0,t.E3)(n.props.xMax,5,"X pins symmetric: xMax"),(0,t.E3)(n.props.yMin,0,"Y pins from 0"),(0,t.E3)(n.props.yMax,8,"Y pins to yMax"),(0,W.S6)(e,null,null),(0,t.E3)(null===(0,W.GE)(e).xMax,!0,"xMax cleared"),(0,t.E3)(null===(0,W.GE)(e).yMax,!0,"yMax cleared"),(0,W.f0)(n,e),(0,t.E3)(Number.isFinite(n.props.xMax)&&n.props.xMax>=2&&n.props.xMax<3,!0,`X resets to a finite fit-to-data bound; got ${n.props.xMax}`),(0,t.E3)(Number.isFinite(n.props.xMin)&&n.props.xMin<=-2&&n.props.xMin>-3,!0,`X min resets symmetric-ish to data; got ${n.props.xMin}`),(0,t.E3)(n.props.yMin,0,"Y still starts at 0 after reset"),(0,t.E3)(Number.isFinite(n.props.yMax),!0,"Y max resets to a finite bound"),(0,W.S6)(e,-3,0),(0,t.E3)(null===(0,W.GE)(e).xMax,!0,"negative xMax rejected"),(0,t.E3)(null===(0,W.GE)(e).yMax,!0,"zero yMax rejected")}),(0,t.t6)("axis-max override: survives a metric recompute (tag-based state)",async()=>{const e=ae({withPValue:!0});(0,l.$Y)(e,{group1:{name:"A",columns:[]},group2:{name:"B",columns:[]}});const n=(0,W.gO)(e,{topNLabels:0});(0,W.S6)(e,4,6),await(0,W.nj)(e,n,"p-value","significance",1,.05),(0,t.E3)(n.props.xMin,-4,"X still pinned after recompute"),(0,t.E3)(n.props.xMax,4,"X still pinned after recompute"),(0,t.E3)(n.props.yMax,6,"Y still pinned after recompute")})}),(0,t.L1)("Proteomics: 14-02",()=>{(0,t.t6)("volcanoDirectionStrings: categories derive from proteomics.groups tag",async()=>{const e=ae();(0,l.$Y)(e,{group1:{name:"DMD",columns:[]},group2:{name:"WT",columns:[]}});const n=(0,W.EO)(e,1,.05,"adj.p-value"),o=e.col(n).categories;(0,t.E3)(e.col(n).get(0),"Enriched in DMD"),(0,W.EO)(e,1,.05,"p-value"),(0,t.E3)(e.col(n).get(1),"Enriched in WT"),(0,t.E3)(e.col(n).get(2),"Not significant");for(const e of["up","down","not significant"])(0,t.E3)(o.includes(e),!1)}),(0,t.t6)('volcanoDirectionStringsFallback: no groups → "Enriched in group1/group2" + "Not significant"',async()=>{const e=ae(),n=(0,W.EO)(e,1,.05,"adj.p-value");(0,t.E3)(e.col(n).get(0),"Enriched in group1"),(0,W.EO)(e,1,.05,"p-value"),(0,t.E3)(e.col(n).get(1),"Enriched in group2"),(0,t.E3)(e.col(n).get(2),"Not significant")}),(0,t.t6)("volcanoDirectionColors: categorical color map carries exact ARGB ints",async()=>{const n=ae();(0,l.$Y)(n,{group1:{name:"DMD",columns:[]},group2:{name:"WT",columns:[]}});const o=(0,W.EO)(n,1,.05,"adj.p-value"),r=n.col(o).getTag(e.TAGS.COLOR_CODING_CATEGORICAL);(0,t.E3)(null!=r,!0);const s=JSON.parse(r);(0,t.E3)(s["Enriched in DMD"],W.PL.enrichedG1),(0,t.E3)(s["Enriched in WT"],W.PL.enrichedG2),(0,t.E3)(s["Not significant"],W.PL.notSig),(0,t.E3)(W.PL.enrichedG1,4294902015),(0,t.E3)(W.PL.enrichedG2,4278255615),(0,t.E3)(W.PL.notSig,4289374890)}),(0,t.t6)('volcanoTitle: synthesizes "Volcano Plot: g1 vs g2" from proteomics.groups',async()=>{const e=ae();(0,l.$Y)(e,{group1:{name:"DMD",columns:[]},group2:{name:"WT",columns:[]}});const n=(0,W.gO)(e,{topNLabels:0}).getOptions();(0,t.E3)(n.look.title,"Volcano Plot: DMD vs WT")}),(0,t.t6)('volcanoTitleFallback: no groups → "Volcano Plot"',async()=>{const e=ae(),n=(0,W.gO)(e,{topNLabels:0}).getOptions();(0,t.E3)(n.look.title,"Volcano Plot")}),(0,t.t6)("volcanoAxisLabels: X invariant; Y rewrites live on metric toggle",async()=>{const e=ae(),n=(0,W.gO)(e,{topNLabels:0}),o=n.root.querySelector("[data-volcano-axis-x]");(0,t.E3)(null!=o,!0),(0,t.E3)(o.textContent,"Log2 Fold Change");let r=n.root.querySelector("[data-volcano-axis-y]");(0,t.E3)(null!=r,!0),(0,t.E3)(r.textContent,"-Log10(Q-value)"),await(0,W.nj)(e,n,"p-value","significance",1,.05),r=n.root.querySelector("[data-volcano-axis-y]"),(0,t.E3)(r.textContent,"-Log10(p-value)"),await(0,W.nj)(e,n,"adj.p-value","significance",1,.05),r=n.root.querySelector("[data-volcano-axis-y]"),(0,t.E3)(r.textContent,"-Log10(Q-value)")}),(0,t.t6)("volcanoTopN: applyTopNLabels labels top-15 via the label column, not selection",async()=>{const e=ne(100),n=e.columns.addNewString("Gene name");n.init(e=>`G${e}`),n.semType=s.iu.GENE_SYMBOL;const o=(0,W.gO)(e,{topNLabels:0});(0,t.E3)(e.selection.trueCount,0);const r=e.col(W.bX);let a=0;for(let t=0;t<e.rowCount;t++)r.get(t).length>0&&a++;(0,t.E3)(a,0),(0,W.XC)(e,o,15),(0,t.E3)(e.selection.trueCount,0);const i=e.col(W.bX);for(let e=0;e<15;e++)(0,t.E3)(i.get(e).length>0,!0);for(let e=15;e<100;e++)(0,t.E3)(i.get(e).length,0);(0,t.E3)(o.props.labelColumnNames.includes(W.bX),!0)}),(0,t.t6)("volcanoLabelBindsToDisplayName: label text prefers DISPLAY_NAME over Gene name",async()=>{const e=ae(),n=e.columns.addNewString("Display Name");n.init(e=>`D${e}`),n.semType=s.iu.DISPLAY_NAME;const o=e.columns.addNewString("Gene name");o.init(e=>`G${e}`),o.semType=s.iu.GENE_SYMBOL;const r=(0,W.gO)(e);(0,t.E3)(r.props.labelColumnNames.includes(W.bX),!0);const a=e.col(W.bX);let i=0;for(let n=0;n<e.rowCount;n++){const e=a.get(n);e.length>0&&(i++,(0,t.E3)(e.startsWith("D"),!0))}(0,t.E3)(i>0,!0)}),(0,t.t6)("volcanoLabelFallbackToGeneName: no Display Name → label text uses Gene name",async()=>{const e=ae(),n=e.columns.addNewString("Gene name");n.init(e=>`G${e}`),n.semType=s.iu.GENE_SYMBOL;const o=(0,W.gO)(e);(0,t.E3)(o.props.labelColumnNames.includes(W.bX),!0);const r=e.col(W.bX);let a=0;for(let n=0;n<e.rowCount;n++){const e=r.get(n);e.length>0&&(a++,(0,t.E3)(e.startsWith("G"),!0))}(0,t.E3)(a>0,!0)}),(0,t.t6)("applyTopNLabelsExtraRows: labels top-N plus extra (search) rows; selection untouched",async()=>{const e=ne(50),n=e.columns.addNewString("Gene name");n.init(e=>`G${e}`),n.semType=s.iu.GENE_SYMBOL;const o=(0,W.gO)(e,{topNLabels:0});(0,W.XC)(e,o,5);const r=e.col(W.bX);for(let e=0;e<5;e++)(0,t.E3)(r.get(e).length>0,!0);(0,W.XC)(e,o,5,[40,41,42]);for(let e=0;e<5;e++)(0,t.E3)(r.get(e).length>0,!0);for(const e of[40,41,42])(0,t.E3)(r.get(e).length>0,!0);(0,t.E3)(e.selection.trueCount,0)}),(0,t.t6)("volcanoMetricTagPersistsViaRecompute: recomputeVolcano writes proteomics.volcano_metric",async()=>{const e=ae(),n=(0,W.gO)(e,{topNLabels:0});(0,t.E3)(e.getTag(W.j9),"adj.p-value"),await(0,W.nj)(e,n,"p-value","significance",1,.05),(0,t.E3)(e.getTag(W.j9),"p-value"),await(0,W.nj)(e,n,"adj.p-value","location",1,.05),(0,t.E3)(e.getTag(W.j9),"adj.p-value")}),(0,t.t6)("volcanoCounterRenders: heading + Total + per-direction rows",async()=>{const n=new Float32Array([3,2,-3,-2,.1,.5]),o=new Float32Array([.001,.01,.001,.01,.5,.3]),r=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["P0","P1","P2","P3","P4","P5"]),e.Column.fromFloat32Array("log2FC",n),e.Column.fromFloat32Array("adj.p-value",o)]);r.col("Protein ID").semType=s.iu.PROTEIN_ID,r.col("log2FC").semType=s.iu.LOG2FC,r.col("adj.p-value").semType=s.iu.P_VALUE,(0,l.$Y)(r,{group1:{name:"DMD",columns:[]},group2:{name:"WT",columns:[]}});const a=(0,W.gO)(r,{topNLabels:0}),i=()=>a.root.querySelector("[data-volcano-counter]")?.textContent??"";await(0,t.bk)(()=>i().includes("Visible Proteins"),"volcano counter overlay never rendered",3e3);const c=i();(0,t.E3)(c.includes(`Total: ${r.filter.trueCount.toLocaleString()}`),!0),(0,t.E3)(c.includes("Enriched in DMD"),!0),(0,t.E3)(c.includes("Enriched in WT"),!0),(0,t.E3)(c.includes("Not significant"),!0)}),(0,t.t6)("volcanoCounterFilterRecompute: Total updates within one debounce window on filter change",async()=>{const e=ne(100),n=(0,W.gO)(e,{topNLabels:0});e.filter.setAll(!1),e.filter.set(0,!0),e.filter.set(1,!0),e.filter.fireChanged(),await(0,t.bk)(()=>(n.root.querySelector("[data-volcano-counter]")?.textContent??"").includes("Total: 2"),"volcano counter Total did not update to 2 after filter change",3e3)},{skipReason:"Quarantined: counter overlay not refreshing on filter change on newer Datagrok runtime — see BACKLOG"}),(0,t.t6)("volcanoCounterEmptyFilter: zero rows still renders Total: 0",async()=>{const e=ne(20),n=(0,W.gO)(e,{topNLabels:0});e.filter.setAll(!1),e.filter.fireChanged(),await(0,t.bk)(()=>(n.root.querySelector("[data-volcano-counter]")?.textContent??"").includes("Total: 0"),"volcano counter Total did not reach 0 on empty filter",3e3)},{skipReason:"Quarantined: counter overlay not refreshing on filter change on newer Datagrok runtime — see BACKLOG"}),(0,t.t6)("volcanoCounterSubscriptionsDisposedOnReentry: only one overlay remains after re-create",async()=>{const e=ne(50);(0,W.gO)(e,{topNLabels:0});const n=(0,W.gO)(e,{topNLabels:0}).root.querySelectorAll("[data-volcano-counter]");(0,t.E3)(n.length,1)}),(0,t.t6)("volcanoCounterLocationMode: per-location rows after color switch",async()=>{const e=ne(20);e.col("Protein ID").semType=s.iu.PROTEIN_ID;const n=(0,W.gO)(e,{topNLabels:0});await(0,W.nj)(e,n,"adj.p-value","location",1,.05),await(0,t.bk)(()=>(n.root.querySelector("[data-volcano-counter]")?.textContent??"").includes("Unknown"),"volcano counter did not show a location row after color switch",3e3)}),(0,t.t6)("volcanoOptionsPreloadMetric: readVolcanoState reflects last recompute metric",async()=>{const e=ae(),n=(0,W.gO)(e,{topNLabels:0});(0,t.E3)((0,W.ur)(e,n).metric,"adj.p-value"),await(0,W.nj)(e,n,"p-value","significance",1,.05),(0,t.E3)((0,W.ur)(e,n).metric,"p-value"),await(0,W.nj)(e,n,"adj.p-value","significance",1,.05),(0,t.E3)((0,W.ur)(e,n).metric,"adj.p-value")}),(0,t.t6)("volcanoOptionsPreloadColorDim: readVolcanoState reflects current colorColumnName",async()=>{const e=ne(20);e.col("Protein ID").semType=s.iu.PROTEIN_ID;const n=(0,W.gO)(e,{topNLabels:0});(0,t.E3)((0,W.ur)(e,n).colorDim,"significance"),await(0,W.nj)(e,n,"adj.p-value","location",1,.05),(0,t.E3)((0,W.ur)(e,n).colorDim,"location"),await(0,W.nj)(e,n,"adj.p-value","significance",1,.05),(0,t.E3)((0,W.ur)(e,n).colorDim,"significance")})});var ie=n(117);function le(e,t={}){const n=t.status??200,o=new Headers;return null!=t.retryAfter&&o.set("Retry-After",t.retryAfter),new Response(null==e?null:JSON.stringify(e),{status:n,headers:o})}async function ce(e,t){const n=v.dapi,o=Object.getPrototypeOf(n),r=Object.prototype.hasOwnProperty.call(n,"fetchProxy"),s=r?n.fetchProxy:void 0,a=o.fetchProxy;n.fetchProxy=e,o.fetchProxy=e;try{await t()}finally{r?n.fetchProxy=s:delete n.fetchProxy,o.fetchProxy=a}}async function ue(e,t){const n=v.dapi.userDataStorage,o=Object.getPrototypeOf(n),r=o.get,s=o.put;o.get=async t=>e.get(t)??null,o.put=async(t,n)=>{e.set(t,n)};try{await t()}finally{o.get=r,o.put=s}}async function me(e){const t=[],n=v.shell,o=n.warning;n.warning=e=>{t.push(e)};try{await e()}finally{n.warning=o}return t}function pe(e){return{native:e.native??`NS:${e.name}`,name:e.name,source:e.source,p_value:e.p_value,significant:e.significant??!0,term_size:e.term_size??100,query_size:e.query_size??50,intersection_size:e.intersection_size??5,effective_domain_size:e.effective_domain_size??2e4,precision:e.precision??.1,recall:e.recall??.05,intersections:e.intersections??[]}}(0,t.L1)("Proteomics: 14-01",()=>{(0,t.t6)("geneLabelResolverSemTypes: SEMTYPE constants are the locked strings",async()=>{(0,t.E3)(s.iu.DISPLAY_NAME,"Proteomics-DisplayName"),(0,t.E3)(s.iu.SOURCE_ID,"Proteomics-SourceId"),(0,t.E3)(s.iu.NUMERATOR_MEAN,"Proteomics-NumeratorMean"),(0,t.E3)(s.iu.DENOMINATOR_MEAN,"Proteomics-DenominatorMean");const e=new Set([s.iu.DISPLAY_NAME,s.iu.SOURCE_ID,s.iu.NUMERATOR_MEAN,s.iu.DENOMINATOR_MEAN,s.iu.PROTEIN_ID,s.iu.GENE_SYMBOL,s.iu.INTENSITY,s.iu.LOG2FC,s.iu.P_VALUE,s.iu.SUBCELLULAR_LOCATION]);(0,t.E3)(e.size,10)}),(0,t.t6)("geneLabelResolverDetectorMirror: SEMTYPE values are valid Column.semType strings",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Display Name",["Myh7†","Tnnt3"]),e.Column.fromStrings("Source ID",["ENSRNOG0001",""]),e.Column.fromFloat32Array("Numerator Mean",new Float32Array([1,2])),e.Column.fromFloat32Array("Denominator Mean",new Float32Array([1.5,2.5]))]);n.col("Display Name").semType=s.iu.DISPLAY_NAME,n.col("Source ID").semType=s.iu.SOURCE_ID,n.col("Numerator Mean").semType=s.iu.NUMERATOR_MEAN,n.col("Denominator Mean").semType=s.iu.DENOMINATOR_MEAN,(0,t.E3)(n.col("Display Name").semType,"Proteomics-DisplayName"),(0,t.E3)(n.col("Source ID").semType,"Proteomics-SourceId"),(0,t.E3)(n.col("Numerator Mean").semType,"Proteomics-NumeratorMean"),(0,t.E3)(n.col("Denominator Mean").semType,"Proteomics-DenominatorMean")}),(0,t.t6)("detectSpecies: maps prefixes per CK-omics species table",async()=>{(0,t.E3)((0,ie.eA)("ENSG00000123"),"homo_sapiens"),(0,t.E3)((0,ie.eA)("ENSMUSG00000456"),"mus_musculus"),(0,t.E3)((0,ie.eA)("MGP_C57BL6NJ_G0000001"),"mus_musculus"),(0,t.E3)((0,ie.eA)("ENSRNOG00000789"),"rattus_norvegicus"),(0,t.E3)((0,ie.eA)("ENSRNO00000001"),"rattus_norvegicus"),(0,t.E3)((0,ie.eA)("ENSDARG00000222"),"danio_rerio"),(0,t.E3)((0,ie.eA)("LOC123456"),null),(0,t.E3)((0,ie.eA)("RGD7890"),null),(0,t.E3)((0,ie.eA)("AABR07012345"),null)}),(0,t.t6)("isEnsemblEligible: filters LOC/RGD/AABR per CK-omics line 933",async()=>{(0,t.E3)((0,ie.oA)("ENSG00000001"),!0),(0,t.E3)((0,ie.oA)("ENSMUSG00000123"),!0),(0,t.E3)((0,ie.oA)("ENSRNOG00000456"),!0),(0,t.E3)((0,ie.oA)("ENSDARG00000789"),!0),(0,t.E3)((0,ie.oA)("MGP_C57BL6NJ_G0000001"),!0),(0,t.E3)((0,ie.oA)("LOC123456"),!1),(0,t.E3)((0,ie.oA)("RGD789"),!1),(0,t.E3)((0,ie.oA)("AABR07012345"),!1)}),(0,t.t6)("isPredicted: locked CK-omics prefix list",async()=>{(0,t.E3)((0,ie.no)("ENSRNOG00000001"),!0),(0,t.E3)((0,ie.no)("LOC987"),!0),(0,t.E3)((0,ie.no)("AABR07"),!0),(0,t.E3)((0,ie.no)("Myh7"),!1),(0,t.E3)((0,ie.no)("Tnnt3"),!1)}),(0,t.t6)("extractReadableDescription: strips Predicted-to prefixes and species suffixes",async()=>{(0,t.E3)((0,ie.qo)("Predicted to enable actin binding [Rattus norvegicus]"),"Actin binding"),(0,t.E3)((0,ie.qo)("Predicted to be involved in transport. Additional sentence."),"Transport"),(0,t.E3)((0,ie.qo)("Myosin heavy chain_RAT"),"Myosin heavy chain"),(0,t.E3)((0,ie.qo)(""),null),(0,t.E3)((0,ie.qo)(null),null),(0,t.E3)((0,ie.qo)("uncharacterized protein"),null)}),(0,t.t6)("applyMarkerRules: appends * and † per CK-omics line 1011",async()=>{(0,t.E3)((0,ie.KK)("Myh7",!1,!0),"Myh7†"),(0,t.E3)((0,ie.KK)("Myh7",!0,!0),"Myh7*†"),(0,t.E3)((0,ie.KK)("LOC123",!1,!0),"LOC123†"),(0,t.E3)((0,ie.KK)("Tnnt3",!1,!1),"Tnnt3"),(0,t.E3)((0,ie.KK)("Tnnt3",!0,!1),"Tnnt3*")}),(0,t.t6)("lookupEnsemblBatch: POSTs ids and parses response",async()=>{let e,n="";await ce(async(t,o)=>(n=t,e=o,le({ENSRNOG00000001:{external_name:"Myh7",description:"Myosin heavy chain 7"},ENSRNOG00000002:null})),async()=>{const o=await(0,ie.FH)(["ENSRNOG00000001","ENSRNOG00000002"]);(0,t.E3)(n,"https://rest.ensembl.org/lookup/id"),(0,t.E3)(e?.method,"POST");const r=JSON.parse(e?.body??"{}");(0,t.E3)(Array.isArray(r.ids),!0),(0,t.E3)(r.ids.length,2),(0,t.E3)(o.size,1),(0,t.E3)(o.get("ENSRNOG00000001")?.external_name,"Myh7")})}),(0,t.t6)("lookupEnsemblBatch: retries once on 429 with Retry-After",async()=>{let e=0;await ce(async()=>(e++,1===e?le(null,{status:429,retryAfter:"0"}):le({ENSG00000001:{external_name:"TP53"}})),async()=>{const n=await(0,ie.FH)(["ENSG00000001"]);(0,t.E3)(e,2),(0,t.E3)(n.get("ENSG00000001")?.external_name,"TP53")})}),(0,t.t6)("resolveGeneLabels: no-op path still creates Display Name + Source ID columns",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["P12345","Q67890","O11111"]),e.Column.fromStrings("Gene name",["Myh7","Tnnt3","Actb"])]);n.col("Gene name").semType=s.iu.GENE_SYMBOL,n.col("Protein ID").semType=s.iu.PROTEIN_ID,await ce(async()=>{throw new Error("should not fetch")},async()=>{await(0,ie.rv)(n)});const o=n.col("Display Name"),r=n.col("Source ID");(0,t.E3)(null!=o,!0),(0,t.E3)(null!=r,!0),(0,t.E3)(o.semType,"Proteomics-DisplayName"),(0,t.E3)(r.semType,"Proteomics-SourceId"),(0,t.E3)(o.get(0),"Myh7"),(0,t.E3)(o.get(1),"Tnnt3"),(0,t.E3)(r.get(0),"")}),(0,t.t6)("resolveGeneLabels: LOC/RGD/AABR keep raw ID + †, never sent to Ensembl",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Gene name",["LOC123","RGD456","AABR789"])]);n.col("Gene name").semType=s.iu.GENE_SYMBOL;let o=0;await ue(new Map,async()=>{await ce(async()=>(o++,le({})),async()=>{await(0,ie.rv)(n)})}),(0,t.E3)(o,0),(0,t.E3)(n.col("Display Name").get(0),"LOC123†"),(0,t.E3)(n.col("Display Name").get(1),"RGD456†"),(0,t.E3)(n.col("Display Name").get(2),"AABR789†"),(0,t.E3)(n.col("Source ID").get(0),"LOC123"),(0,t.E3)(n.col("Source ID").get(1),"RGD456"),(0,t.E3)(n.col("Source ID").get(2),"AABR789")}),(0,t.t6)("resolveGeneLabels: disambiguates duplicates with (Source ID) suffix and warns",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Gene name",["ENSRNOG00000001","ENSRNOG00000002","Actb"])]);n.col("Gene name").semType=s.iu.GENE_SYMBOL;const o=await me(async()=>{await ue(new Map,async()=>{await ce(async()=>le({ENSRNOG00000001:{external_name:"Myh7"},ENSRNOG00000002:{external_name:"Myh7"}}),async()=>{await(0,ie.rv)(n)})})});(0,t.E3)(n.col("Display Name").get(0),"Myh7† (ENSRNOG00000001)"),(0,t.E3)(n.col("Display Name").get(1),"Myh7† (ENSRNOG00000002)"),(0,t.E3)(n.col("Display Name").get(2),"Actb");const r=o.find(e=>e.includes("duplicate gene names"));(0,t.E3)(null!=r,!0)}),(0,t.t6)("resolveGeneLabels: cache short-circuits second call",async()=>{const n=new Map;let o=0;const r=async()=>(o++,le({ENSRNOG00000001:{external_name:"Myh7"}})),a=e.DataFrame.fromColumns([e.Column.fromStrings("Gene name",["ENSRNOG00000001"])]);a.col("Gene name").semType=s.iu.GENE_SYMBOL;const i=e.DataFrame.fromColumns([e.Column.fromStrings("Gene name",["ENSRNOG00000001"])]);i.col("Gene name").semType=s.iu.GENE_SYMBOL,await ue(n,async()=>{await ce(r,async()=>{await(0,ie.rv)(a);const e=o;await(0,ie.rv)(i),(0,t.E3)(o,e)})}),(0,t.E3)(i.col("Display Name").get(0),"Myh7†");const l=n.get(ie.I5)??{};(0,t.E3)(l.__schema_v,ie.Rw)}),(0,t.t6)("resolveGeneLabels: degrades gracefully on fetchProxy throw",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Gene name",["ENSRNOG00000001","Actb"])]);n.col("Gene name").semType=s.iu.GENE_SYMBOL;const o=await me(async()=>{await ue(new Map,async()=>{await ce(async()=>{throw new Error("network down")},async()=>{await(0,ie.rv)(n)})})});(0,t.E3)(n.col("Display Name").get(0),"ENSRNOG00000001†"),(0,t.E3)(n.col("Display Name").get(1),"Actb"),(0,t.E3)(n.col("Source ID").get(0),"ENSRNOG00000001");const r=o.find(e=>e.includes("Ensembl gene-label resolution unavailable"));(0,t.E3)(null!=r,!0)}),(0,t.t6)("parser integration: every parser produces Display Name + Source ID columns",async()=>{const e=await(0,r.E)(["Protein IDs\tMajority protein IDs\tGene names\tPotential contaminant\tReverse\tOnly identified by site\tLFQ intensity Sample1\tLFQ intensity Sample2\tiBAQ","P12345\tP12345\tBRCA1\t\t\t\t1000\t2000\t500"].join("\n"));(0,t.E3)(e.col("Display Name")?.semType,"Proteomics-DisplayName"),(0,t.E3)(e.col("Source ID")?.semType,"Proteomics-SourceId");const n=await(0,B.p)(["Protein\tGene\tDescription\tMaxLFQ Intensity Sample1\tMaxLFQ Intensity Sample2","P12345\tBRCA1\tProtein BRCA1\t1000\t2000"].join("\n"));(0,t.E3)(n.col("Display Name")?.semType,"Proteomics-DisplayName"),(0,t.E3)(n.col("Source ID")?.semType,"Proteomics-SourceId");const o=await(0,L.R)(["PG.ProteinGroups\tPG.Genes\tComparison (group1/group2)\tAVG Log2 Ratio\tQvalue\tPvalue","P12345\tBRCA1\tA / B\t2.5\t0.001\t0.0005"].join("\n"));(0,t.E3)(o.col("Display Name")?.semType,"Proteomics-DisplayName"),(0,t.E3)(o.col("Source ID")?.semType,"Proteomics-SourceId");const s=await(0,A.parseSpectronautText)(["PG.ProteinGroups\tPG.Genes\tR.Condition\tR.Replicate\tR.FileName\tPG.Qvalue\tPG.Quantity","P12345\tBRCA1\tCtrl\t1\tF1\t0.0001\t1000","P12345\tBRCA1\tCtrl\t2\tF2\t0.0001\t1200","P12345\tBRCA1\tTrt\t1\tF3\t0.0001\t2000","P12345\tBRCA1\tTrt\t2\tF4\t0.0001\t2400"].join("\n"));(0,t.E3)(s.col("Display Name")?.semType,"Proteomics-DisplayName"),(0,t.E3)(s.col("Source ID")?.semType,"Proteomics-SourceId")}),(0,t.t6)("resolveGeneLabels: three-level fallback uses description when external_name missing",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Gene name",["ENSRNOG00000099"])]);n.col("Gene name").semType=s.iu.GENE_SYMBOL,await ue(new Map,async()=>{await ce(async()=>le({ENSRNOG00000099:{description:"Predicted to enable kinase activity [Rattus norvegicus]"}}),async()=>{await(0,ie.rv)(n)})}),(0,t.E3)(n.col("Display Name").get(0),"Predicted to enable kinase activity†"),(0,t.E3)(n.col("Source ID").get(0),"ENSRNOG00000099")})}),(0,t.L1)("Proteomics: 14-05",()=>{(0,t.t6)("smartPathwayFilter constants match CK-omics literal lists",async()=>{(0,t.E3)(h.zy.length,6),(0,t.E3)(h.zy.includes("localization"),!0),(0,t.E3)(h.zy.includes("cellular component organization"),!0),(0,t.E3)(h.zy.includes("transport"),!0),(0,t.E3)(h.zy.includes("cellular process"),!0),(0,t.E3)(h.zy.includes("biological process"),!0),(0,t.E3)(h.zy.includes("metabolic process"),!0),(0,t.E3)(h._W.length,4),(0,t.E3)(h._W.includes("actin"),!0),(0,t.E3)(h._W.includes("vesicle"),!0),(0,t.E3)(h._W.includes("endocytosis"),!0),(0,t.E3)(h._W.includes("cytoskeleton"),!0)}),(0,t.t6)("smartFilterDropsGenericParentWhenChildKept",async()=>{const e=[pe({name:"actin cytoskeleton organization",source:"GO:BP",p_value:.001}),pe({name:"cellular component organization",source:"GO:BP",p_value:.002}),pe({name:"vesicle docking",source:"GO:BP",p_value:.003}),pe({name:"transport",source:"GO:BP",p_value:.004}),pe({name:"protein phosphorylation",source:"GO:BP",p_value:.005})],{kept:n,stats:o}=(0,h.AB)(e,15);(0,t.E3)(n.length,3),(0,t.E3)(o.total,5),(0,t.E3)(o.kept,3),(0,t.E3)(o.droppedParents,2),(0,t.E3)(o.cappedAtN,15);const r=n.map(e=>e.name);(0,t.E3)(r.includes("actin cytoskeleton organization"),!0),(0,t.E3)(r.includes("vesicle docking"),!0),(0,t.E3)(r.includes("protein phosphorylation"),!0),(0,t.E3)(r.includes("cellular component organization"),!1),(0,t.E3)(r.includes("transport"),!1)}),(0,t.t6)("smartFilterKeepsGenericParentWhenNoChildFirst",async()=>{const e=[pe({name:"biological process",source:"GO:BP",p_value:.001}),pe({name:"actin filament organization",source:"GO:BP",p_value:.002}),pe({name:"protein folding",source:"GO:BP",p_value:.003})],{kept:n,stats:o}=(0,h.AB)(e,15);(0,t.E3)(n.length,3),(0,t.E3)(o.droppedParents,0)}),(0,t.t6)("smartFilterCapsGoBpAt15",async()=>{const e=[];for(let t=0;t<30;t++)e.push(pe({name:`pathway ${t}`,source:"GO:BP",p_value:.001*(t+1)}));const{kept:n,stats:o}=(0,h.AB)(e,15);(0,t.E3)(n.length,15),(0,t.E3)(o.total,30),(0,t.E3)(o.kept,15),(0,t.E3)(o.droppedParents,0);for(const e of n){const n=parseInt(e.name.replace("pathway ",""));(0,t.E3)(n<15,!0)}}),(0,t.t6)("smartFilterHonorsCustomCap (M3 — configurable max terms per source)",async()=>{const e=[];for(let t=0;t<30;t++)e.push(pe({name:`bp ${t}`,source:"GO:BP",p_value:.001*(t+1)}));for(let t=0;t<30;t++)e.push(pe({name:`kegg ${t}`,source:"KEGG",p_value:.01*(t+1)}));const{kept:n,stats:o}=(0,h.AB)(e,5);(0,t.E3)(n.length,10,"custom cap 5 applied to each partition"),(0,t.E3)(o.cappedAtN,5,"stats echo the custom cap"),(0,t.E3)(n.filter(e=>"GO:BP"===e.source).length,5,"GO:BP capped at 5"),(0,t.E3)(n.filter(e=>"KEGG"===e.source).length,5,"non-GO:BP capped at 5")}),(0,t.t6)("smartFilterCombinedCapForNonGoBp (Assumption A4)",async()=>{const e=[];for(let t=0;t<5;t++)e.push(pe({name:`bp ${t}`,source:"GO:BP",p_value:.001*(t+1)}));const n=["KEGG","REAC","WP"];for(let t=0;t<20;t++)e.push(pe({name:`other ${t}`,source:n[t%3],p_value:.01*(t+1)}));const{kept:o,stats:r}=(0,h.AB)(e,15);(0,t.E3)(o.length,20),(0,t.E3)(r.total,25),(0,t.E3)(r.kept,20);const s=o.filter(e=>"GO:BP"!==e.source);(0,t.E3)(s.length,15)}),(0,t.t6)("smartFilterPreservesPValueSortOrder",async()=>{const e=[pe({name:"a",source:"GO:BP",p_value:.005}),pe({name:"b",source:"KEGG",p_value:.001}),pe({name:"c",source:"GO:BP",p_value:.003}),pe({name:"d",source:"REAC",p_value:.002})],{kept:n}=(0,h.AB)(e,15);for(let e=1;e<n.length;e++)(0,t.E3)(n[e-1].p_value<=n[e].p_value,!0)}),(0,t.t6)("smartFilterEmptyInput",async()=>{const{kept:e,stats:n}=(0,h.AB)([],15);(0,t.E3)(e.length,0),(0,t.E3)(n.total,0),(0,t.E3)(n.kept,0),(0,t.E3)(n.droppedParents,0),(0,t.E3)(n.cappedAtN,15)}),(0,t.t6)("smartFilterStatsCount",async()=>{const e=[pe({name:"actin organization",source:"GO:BP",p_value:.001}),pe({name:"biological process",source:"GO:BP",p_value:.002}),pe({name:"metabolic process",source:"GO:BP",p_value:.003})],{kept:n,stats:o}=(0,h.AB)(e,15);(0,t.E3)(o.total,e.length),(0,t.E3)(o.kept,n.length),(0,t.E3)(o.droppedParents,2),(0,t.E3)(o.cappedAtN,15)}),(0,t.t6)("smartFilter empty GO:BP, only other sources",async()=>{const e=[];for(let t=0;t<25;t++)e.push(pe({name:`kegg ${t}`,source:"KEGG",p_value:.001*(t+1)}));const{kept:n,stats:o}=(0,h.AB)(e,15);(0,t.E3)(n.length,15),(0,t.E3)(o.droppedParents,0)}),(0,t.t6)("smartFilter non-GO:BP path also sorts by p ASC",async()=>{const e=[pe({name:"kegg_high",source:"KEGG",p_value:.1}),pe({name:"kegg_low",source:"KEGG",p_value:.001}),pe({name:"reac_mid",source:"REAC",p_value:.05})],{kept:n}=(0,h.AB)(e,2);(0,t.E3)(n.length,2),(0,t.E3)(n[0].name,"kegg_low"),(0,t.E3)(n[1].name,"reac_mid")})});var de=n(498);function fe(t={}){const{groupColsExist:n=!0,withGroupsTag:o=!0,withProteinId:r=!0,row0AllNan:a=!1}=t,i=[];if(r){const t=e.Column.fromStrings("Primary Protein ID",["P11111","P22222","P33333"]);t.semType=s.iu.PROTEIN_ID,i.push(t)}if(n){const t=a?[NaN,1,1]:[1,1.5,2],n=a?[NaN,3,1]:[3,2.5,2.5],o=a?[NaN,4,4]:[5,4,5],r=a?[NaN,6,4]:[7,6,5.5],s=e.Column.fromList("double","Sample1",t),l=e.Column.fromList("double","Sample2",n),c=e.Column.fromList("double","Sample3",o),u=e.Column.fromList("double","Sample4",r);a&&(s.set(0,null),l.set(0,null),c.set(0,null),u.set(0,null)),i.push(s,l,c,u)}const c=e.DataFrame.fromColumns(i);return o&&n&&(0,l.$Y)(c,{group1:{name:"Control",columns:["Sample1","Sample2"]},group2:{name:"Treatment",columns:["Sample3","Sample4"]}}),c.name=`panel-fixture-${Math.random().toString(36).slice(2,8)}`,c}function ge(e){return{accession:e,proteinDescription:{recommendedName:{fullName:{value:"Mock Protein"}}},genes:[{geneName:{value:"MOCK1"}}],organism:{scientificName:"Homo sapiens"},comments:[],uniProtKBCrossReferences:[]}}(0,t.L1)("Proteomics: 14-04",()=>{(0,t.t6)("uniprotPanelPerGroupBarsRender",async()=>{const e=fe(),n=v.shell.addTableView(e);try{const e=(0,de.A$)(ge("P11111"),"P11111");(0,t.E3)(e.textContent?.includes("Per-Group Quantities"),!0);const n=e.querySelectorAll("rect");(0,t.E3)(n.length,2);const o=Array.from(e.querySelectorAll("text")).map(e=>e.textContent??"").filter(e=>e.includes("(n=2)")).length;(0,t.E3)(o,2);const r=Array.from(e.querySelectorAll("div")).filter(e=>null===e.querySelector(":scope > div")).map(e=>e.textContent??"").filter(e=>/mean=.*SD=/.test(e));(0,t.E3)(r.length,2)}finally{n.close()}}),(0,t.t6)("uniprotPanelPerGroupBarsEmptyState",async()=>{const e=fe({withGroupsTag:!1}),n=v.shell.addTableView(e);try{const e=(0,de.A$)(ge("P11111"),"P11111"),n=e.querySelectorAll("rect");(0,t.E3)(n.length,0),(0,t.E3)(e.textContent?.includes("Per-Group Quantities"),!1)}finally{n.close()}}),(0,t.t6)("uniprotPanelPerGroupBarsColors",async()=>{const e=fe(),n=v.shell.addTableView(e);try{const e=(0,de.A$)(ge("P11111"),"P11111").querySelectorAll("rect");(0,t.E3)(e.length,2),(0,t.E3)(e[0].getAttribute("fill"),"#FF00FF"),(0,t.E3)(e[1].getAttribute("fill"),"#00FFFF")}finally{n.close()}}),(0,t.t6)("uniprotPanelPerGroupMeanSDComputation",async()=>{const n=[],o=e.Column.fromStrings("Primary Protein ID",["P11111"]);o.semType=s.iu.PROTEIN_ID,n.push(o),n.push(e.Column.fromList("double","S1",[1])),n.push(e.Column.fromList("double","S2",[3])),n.push(e.Column.fromList("double","S3",[5])),n.push(e.Column.fromList("double","S4",[7]));const r=e.DataFrame.fromColumns(n);(0,l.$Y)(r,{group1:{name:"Control",columns:["S1","S2"]},group2:{name:"Treatment",columns:["S3","S4"]}}),r.name="mean-sd-fixture";const a=v.shell.addTableView(r);try{const e=(0,de.nT)(r,"P11111");(0,t.E3)(null!==e,!0);const n=Array.from(e.querySelectorAll("div")).map(e=>e.textContent??"").filter(e=>/mean=.*SD=/.test(e));(0,t.E3)(n.length,2);const o=n.find(e=>e.startsWith("Control:")),s=n.find(e=>e.startsWith("Treatment:"));(0,t.E3)(void 0!==o,!0),(0,t.E3)(void 0!==s,!0),(0,t.E3)(o.includes("mean=2.00"),!0),(0,t.E3)(o.includes("SD=1.41"),!0),(0,t.E3)(s.includes("mean=6.00"),!0),(0,t.E3)(s.includes("SD=1.41"),!0)}finally{a.close()}}),(0,t.t6)("uniprotPanelPerGroupBarsAllNanProtein",async()=>{const e=fe({row0AllNan:!0}),n=v.shell.addTableView(e);try{const n=(0,de.nT)(e,"P11111");(0,t.E3)(null!==n,!0),(0,t.E3)(n.tagName.toLowerCase(),"div"),(0,t.E3)((n.textContent??"").includes("No per-group quantities available"),!0),(0,t.E3)(n.querySelectorAll("rect").length,0)}finally{n.close()}}),(0,t.t6)("findHostDataFrameForProteinPrefersActiveTable",async()=>{const e=fe(),n=fe(),o=v.shell.addTableView(e),r=v.shell.addTableView(n);try{const e=(0,de.xh)("P11111");(0,t.E3)(null!==e,!0);const n=v.shell.tv?.dataFrame;(0,t.E3)(e===n,!0)}finally{o.close(),r.close()}})});var he=n(644);function ye(){const t=[],n=e.Column.fromStrings("Primary Protein ID",["P1","P2","P3","P4","P5"]);n.semType=s.iu.PROTEIN_ID,t.push(n);const o=e.Column.fromStrings("Display Name",["Gene1","Gene2","Gene3","Gene4","Gene5"]);o.semType=s.iu.DISPLAY_NAME,t.push(o),t.push(e.Column.fromList("double","S1",[1,2,3,4,5])),t.push(e.Column.fromList("double","S2",[3,4,5,6,7])),t.push(e.Column.fromList("double","S3",[5,6,7,8,9])),t.push(e.Column.fromList("double","S4",[7,8,9,10,11])),t.push(e.Column.fromStrings("direction",["Enriched in Control","Enriched in Treatment","Not significant","Enriched in Control","Enriched in Treatment"]));const r=e.DataFrame.fromColumns(t);return(0,l.$Y)(r,{group1:{name:"Control",columns:["S1","S2"]},group2:{name:"Treatment",columns:["S3","S4"]}}),r.name=`correlation-fixture-${Math.random().toString(36).slice(2,8)}`,r}(0,t.L1)("Proteomics: 14-04",()=>{(0,t.t6)("groupMeanColumnsCreated",async()=>{const e=ye();(0,he.hy)(e,{group1:{name:"Control",columns:["S1","S2"]},group2:{name:"Treatment",columns:["S3","S4"]}});const n=e.col("Numerator Mean"),o=e.col("Denominator Mean");(0,t.E3)(null!==n,!0),(0,t.E3)(null!==o,!0),(0,t.E3)(n.semType,s.iu.NUMERATOR_MEAN),(0,t.E3)(o.semType,s.iu.DENOMINATOR_MEAN),(0,t.E3)(n.length,e.rowCount),(0,t.E3)(o.length,e.rowCount),(0,t.E3)(Math.abs(n.get(0)-2)<1e-6,!0),(0,t.E3)(Math.abs(o.get(0)-6)<1e-6,!0),(0,t.E3)(Math.abs(n.get(4)-6)<1e-6,!0),(0,t.E3)(Math.abs(o.get(4)-10)<1e-6,!0)}),(0,t.t6)("groupMeanColumnsReRunSafe",async()=>{const e=ye(),n={group1:{name:"Control",columns:["S1","S2"]},group2:{name:"Treatment",columns:["S3","S4"]}};(0,he.hy)(e,n),(0,he.hy)(e,n);const o=e.columns.toList().filter(e=>"Numerator Mean"===e.name).length,r=e.columns.toList().filter(e=>"Denominator Mean"===e.name).length;(0,t.E3)(o,1),(0,t.E3)(r,1);const s=e.col("Numerator Mean");(0,t.E3)(Math.abs(s.get(0)-2)<1e-6,!0)}),(0,t.t6)("pearsonPerfectCorrelation",async()=>{const e=(0,he.nc)([1,2,3,4,5],[2,4,6,8,10]);(0,t.E3)(Math.abs(e-1)<1e-9,!0)}),(0,t.t6)("pearsonNoCorrelation",async()=>{const e=(0,he.nc)([1,2,3,4,5],[3,1,4,1,5]);(0,t.E3)(Math.abs(e)<.6,!0)}),(0,t.t6)("spearmanRankTies",async()=>{const e=(0,he.CN)([1,2,2,3,4],[1,2,2,3,4]);(0,t.E3)(Math.abs(e-1)<1e-9,!0)}),(0,t.t6)("createGroupMeanCorrelationFactory",async()=>{const e=ye(),n=(0,he.Z7)(e);(0,t.E3)(null!==n,!0);const o=n.getOptions?.(),r=o?.look?.title??"";(0,t.E3)(r.includes("r="),!0),(0,t.E3)(r.includes("ρ="),!0),(0,t.E3)(n.props.xColumnName,"Numerator Mean"),(0,t.E3)(n.props.yColumnName,"Denominator Mean"),(0,t.E3)(n.props.colorColumnName,"direction")}),(0,t.t6)("correlationDiagonalLine",async()=>{const e=ye();(0,he.Z7)(e);const n=e.meta.formulaLines.items.find(e=>{const t=e.formula??"";return"string"==typeof t&&t.includes("Numerator Mean")&&t.includes("Denominator Mean")});(0,t.E3)(void 0!==n,!0),(0,t.E3)(n.color,"#888888")}),(0,t.t6)("correlationLabelBindsToDisplayName",async()=>{const e=ye(),n=(0,he.Z7)(e);(0,t.E3)(n.props.labelColumnNames?.includes("Display Name"),!0)})});const Ee=["proteomics.source","proteomics.de_method","proteomics.de_complete","proteomics.groups","proteomics.published","proteomics.published_at","proteomics.published_by","proteomics.published_target","proteomics.published_de_method","proteomics.published_fc_threshold","proteomics.published_p_threshold","proteomics.published_version","proteomics.published_id","proteomics.published_includes_enrichment"],we=[["Protein ID",s.iu.PROTEIN_ID],["Gene Name",s.iu.GENE_SYMBOL],["log2FC",s.iu.LOG2FC],["adj.p-value",s.iu.P_VALUE]];function ve(e,t){let n;try{n="string"==typeof t?t:JSON.stringify(t)}catch{n=String(t)}const o=`[publish-spike] ${e}: ${n}`;console.log(o),v.shell.info(o)}async function _e(e,t){try{await t(),ve(`cleanup:${e}`,"ok")}catch(t){ve(`cleanup:${e}:error`,`${t?.message??t}`)}}(0,t.L1)("Publishing-Spike",()=>{(0,t.t6)("save+open roundtrip — enumerate survivors",async()=>{const n=Date.now(),o=`spike-pub-${n}`,r=new Date(n).toISOString(),s=`spike-publish-roundtrip-${n}`;ve("boot",{projectName:s,publishedId:o,nowIso:r});const a=function(t,n){const o=Array.from({length:10},(e,t)=>`P${String(t+1).padStart(5,"0")}`),r=Array.from({length:10},(e,t)=>`GENE${t+1}`),s=new Float32Array([3,2.5,2,1.5,.5,-.4,-1.6,-2.2,-2.8,.1]),a=new Float32Array([1e-4,.001,.005,.02,.04,.1,.001,5e-4,1e-4,.3]),i=new Float32Array([.001,.005,.01,.04,.08,.2,.005,.001,5e-4,.5]),l=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",o),e.Column.fromStrings("Gene Name",r),e.Column.fromFloat32Array("log2FC",s),e.Column.fromFloat32Array("p-value",a),e.Column.fromFloat32Array("adj.p-value",i),e.Column.fromStrings("significant",["up","up","up","up","ns","ns","down","down","down","ns"]),e.Column.fromStrings("direction",["Enriched in Treatment","Enriched in Treatment","Enriched in Treatment","Enriched in Treatment","Not significant","Not significant","Enriched in Control","Enriched in Control","Enriched in Control","Not significant"])]);for(const[e,t]of we)l.col(e).semType=t;l.name="spike-source";const c={"proteomics.source":"generic","proteomics.de_method":"limma","proteomics.de_complete":"true","proteomics.groups":JSON.stringify({group1:{name:"Control",columns:[]},group2:{name:"Treatment",columns:[]}}),"proteomics.published":"true","proteomics.published_at":n,"proteomics.published_by":"spike-operator","proteomics.published_target":"SPIKE-TARGET-A","proteomics.published_de_method":"limma","proteomics.published_fc_threshold":"1.0","proteomics.published_p_threshold":"0.05","proteomics.published_version":"1","proteomics.published_id":t,"proteomics.published_includes_enrichment":"false"};for(const[e,t]of Object.entries(c))l.setTag(e,t);return l}(o,r),i=v.shell.addTableView(a);await(0,t.cb)(100);let l=null;try{const t=i;if("function"==typeof t.scatterPlot)l=t.scatterPlot({x:"log2FC",y:"adj.p-value"});else{l=e.Viewer.scatterPlot(a,{x:"log2FC",y:"adj.p-value"});let t=!1;try{t=Array.from(i.viewers).includes(l)}catch{}l&&!t&&i.addViewer(l)}}catch(e){ve("scatter-add-error",`${e?.message??e}`)}await(0,t.cb)(100);const c=e.Project.create();c.name=s;try{c.options["proteomics.superseded_by"]="dummy-id-A",c.options.custom_option="hello"}catch(e){ve("project-options-set-error",`${e?.message??e}`)}const u=i.dataFrame.getTableInfo(),m=i.getInfo();c.addChild(u),c.addChild(m);let p=null,d=null,f=!1;try{await v.dapi.tables.uploadDataFrame(i.dataFrame),await v.dapi.tables.save(u),p=u.id,await v.dapi.views.save(m),await v.dapi.projects.save(c),d=c.id,f=!0,ve("save:ok",{projectId:d,tableInfoId:p})}catch(e){ve("save:error",`${e?.message??e}`)}if(!f||!d){ve("halt","save sequence failed — skipping reopen and downstream probes");try{v.shell.closeAll()}catch{}return}try{v.shell.closeAll()}catch(e){ve("closeAll-error",`${e?.message??e}`)}await(0,t.cb)(100);let g=null;try{g=await v.dapi.projects.find(d),await g.open()}catch(e){ve("reopen:error",`${e?.message??e}`)}if(!g)return void ve("halt","reopen failed — skipping enumeration");try{await(0,t.bk)(()=>!!v.shell.tv&&!!v.shell.tv.dataFrame,"TableView did not materialize after Project.open()",5e3)}catch(e){ve("await-tv-error",`${e?.message??e}`)}const h=v.shell.tv,y=h?.dataFrame??null;if(ve("df.name survived",y?.name??"(no dataFrame)"),y){const e={};for(const t of Ee)e[t]=y.getTag(t)??null;ve("proteomics.* tags survived",e);const t={};for(const[e]of we){const n=y.col(e);t[e]=n?n.semType??null:"(column missing)"}ve("Proteomics-* semTypes survived",t),ve("reopened columns shape",y.columns.toList().map(e=>({name:e.name,type:e.type,semType:e.semType??null})))}try{const e=g.options??{},t=e["proteomics.superseded_by"],n=e.custom_option;let o=[];try{o=Object.keys(e)}catch{}ve("project.options",{"proteomics.superseded_by":t??null,custom_option:n??null,keys:o,rawJson:(()=>{try{return JSON.stringify(e)}catch{return"(unstringifiable)"}})()})}catch(e){ve("project.options:error",`${e?.message??e}`)}ve("viewers after reopen",function(){const e=[],t=v.shell.tv;if(!t)return e;for(const n of t.viewers){let t,o,r,s=null;try{s=n.getOptions?n.getOptions()?.look??n.getOptions():null}catch(e){s=`getOptions-threw:${e?.message??e}`}try{t=n.props?.xColumnName}catch{}try{o=n.props?.yColumnName}catch{}try{r=n.props?.colorColumnName}catch{}e.push({type:n.type,xColumnName:t,yColumnName:o,colorColumnName:r,props:s})}return e}());try{const e=await v.dapi.permissions.get(g);let t=[];try{t=Object.keys(e)}catch{}let n="(unstringifiable)";try{n=JSON.stringify(e)}catch{}ve("permissions.get keys",t),ve("permissions.get json",n)}catch(e){ve("permissions.get:error",`${e?.message??e}`)}let E=null,w=null;try{E=await v.dapi.spaces.createRootSpace(`Spike-Reviews-${n}`),ve("umbrella-space",{id:E.id,friendlyName:E.friendlyName});const e=v.dapi.spaces.id(E.id);w=await e.addSubspace(`Spike-Review-Inherit-${n}`),ve("inherited-child-space",{id:w.id,friendlyName:w.friendlyName});const t=v.dapi.spaces.id(w.id);try{await t.addEntity(g.id),ve("inherited-child:addEntity","ok")}catch(e){ve("inherited-child:addEntity:error",`${e?.message??e}`)}try{const e=(await v.dapi.users.current()).group??null;e?(await v.dapi.permissions.grant(E,e,!1),ve("umbrella-space:grant-view",{group:e.friendlyName??e.name??"(unnamed)"})):ve("umbrella-space:grant-skipped","no user.group found")}catch(e){ve("umbrella-space:grant:error",`${e?.message??e}`)}try{const e=await v.dapi.permissions.get(g);let t=[];try{t=Object.keys(e)}catch{}ve("permissions.get(childProject) after umbrella-grant",{keys:t,json:(()=>{try{return JSON.stringify(e)}catch{return"(unstringifiable)"}})()})}catch(e){ve("childProject:permissions.get:error",`${e?.message??e}`)}}catch(e){ve("space-probe:error",`${e?.message??e}`)}try{const e=await v.dapi.projects.filter('name like "spike-publish-roundtrip-%"').list();ve('filter "like" result',{count:Array.isArray(e)?e.length:"(non-array)",firstName:Array.isArray(e)&&e.length>0?e[0].name??null:null})}catch(e){ve("filter:like:error",`${e?.message??e}`)}try{const e=await v.dapi.projects.filter('name contains "spike-publish-roundtrip"').list();ve('filter "contains" result',{count:Array.isArray(e)?e.length:"(non-array)",firstName:Array.isArray(e)&&e.length>0?e[0].name??null:null})}catch(e){ve("filter:contains:error",`${e?.message??e}`)}const _=p;try{await v.dapi.projects.delete(g),ve("projects.delete","ok")}catch(e){ve("projects.delete:error",`${e?.message??e}`)}if(_)try{const e=await v.dapi.tables.find(_);ve("tables.find(tableInfoId) after project.delete",{resolved:!!e,name:e?e.name??null:null})}catch(e){ve("tables.find:after-delete:error",`${e?.message??e}`)}w&&await _e("inherited-child-space",()=>v.dapi.spaces.delete(w)),E&&await _e("umbrella-space",()=>v.dapi.spaces.delete(E)),await _e("project (idempotent)",async()=>{try{const e=await v.dapi.projects.find(d);e&&await v.dapi.projects.delete(e)}catch{}}),ve("done","spike enumeration complete — read output above")})});var Ce=n(771),be=n(807),Te=n(691),Pe=n(649);const Se="pub-roundtrip-",Ne=.05;function Ae(){const t=new Float32Array([3.2,2.6,2.1,1.7,1.3,.2,-1.7,-2.3,-2.9,-3.4]),n=new Float32Array([1e-4,5e-4,.001,.005,.02,.5,.005,.001,5e-4,1e-4]),o=new Float32Array([5e-4,.0015,.005,.01,.04,.6,.01,.005,.0015,5e-4]),r=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["P10001","P10002","P10003","P10004","P10005","P10006","P10007","P10008","P10009","P10010"]),e.Column.fromStrings("Gene Name",["ALPHA","BETA","GAMMA","DELTA","EPSILON","ZETA","ETA","THETA","IOTA","KAPPA"]),e.Column.fromFloat32Array("log2FC",t),e.Column.fromFloat32Array("p-value",n),e.Column.fromFloat32Array("adj.p-value",o),e.Column.fromStrings("significant",["yes","yes","yes","yes","yes","no","yes","yes","yes","yes"]),e.Column.fromStrings("direction",["Up","Up","Up","Up","Up","NS","Down","Down","Down","Down"])]);return r.col("Protein ID").semType=s.iu.PROTEIN_ID,r.col("Gene Name").semType=s.iu.GENE_SYMBOL,r.col("log2FC").semType=s.iu.LOG2FC,r.col("adj.p-value").semType=s.iu.P_VALUE,r.setTag("proteomics.source","generic"),r.setTag("proteomics.de_method","limma"),r.setTag("proteomics.de_complete","true"),r.setTag("proteomics.groups",JSON.stringify({group1:{name:"Control",columns:["s1","s2","s3"]},group2:{name:"Treatment",columns:["s4","s5","s6"]}})),r.name="fixture-no-enrichment",r}function xe(){const t=Ae();t.setTag("proteomics.source","spectronaut-candidates"),t.setTag("proteomics.de_method","spectronaut"),t.name="fixture-with-enrichment";const n=new Float32Array([.005,.01,.015,.02,.03,.05]),o=e.DataFrame.fromColumns([e.Column.fromStrings("Term Name",["Term A","Term B","Term C","Term D","Term E","Term F"]),e.Column.fromStrings("Source",["GO:BP","KEGG","GO:BP","GO:BP","KEGG","REAC"]),e.Column.fromFloat32Array("FDR",n),e.Column.fromStrings("Intersection",["ALPHA,BETA,GAMMA","DELTA,EPSILON","ETA,THETA","IOTA,KAPPA","ALPHA,DELTA","BETA,GAMMA,ETA"])]);return o.setTag("proteomics.enrichment","true"),o.name="enrichment-fixture",{protein:t,enrichment:o}}async function De(){const t=e.Group.defaultGroupsIds?.Test;if(t)try{const e=await v.dapi.groups.find(t);if(e)return e}catch{}const n=v.shell.user?.group?.id,o=await v.dapi.groups.list();return(o??[]).find(e=>e&&!e.hidden&&!e.personal&&e.id!==n)||(o??[])[0]}function Le(e,t,n,o,r){return{expectedName:e,expectedProjectName:t,expectedAllowlist:n,expectedMeta:{...o},expectVolcano:!0,expectEnrichment:r,expectFormulaLines:!0}}async function Fe(e){if(e)try{await v.dapi.projects.delete(e)}catch(t){console.warn(`[publish-roundtrip] project cleanup failed (${e?.name}): ${t}`)}}async function Ie(e){const t=v.dapi,n=`Proteomics-Review-${(0,Ce.fz)(e)}`;try{const e=(await t.spaces.list()??[]).find(e=>"Proteomics-Reviews"===e?.name||"Proteomics-Reviews"===e?.friendlyName);if(!e)return;const o=(await t.spaces.id(e.id).children.filter("Project",!1).list()??[]).find(e=>e?.friendlyName===n||e?.name===n);o&&await t.spaces.delete(o)}catch(e){console.warn(`[publish-roundtrip] child-space cleanup failed (${n}): ${e}`)}}function Me(){const e=v.shell.tv;return e?e.dataFrame.columns.toList().map(e=>e.name).filter(e=>!e.startsWith("_meta_")&&!e.startsWith("~")):[]}function Oe(e,t,n,o){const r=e.options?.[Ce.L6.PUBLISHED_ID]??"",s=t.getTag("proteomics.de_method")??"t-test";return{target:n,publishedAt:new Date,publishedBy:v.shell.user?.friendlyName??"",publishedByEmail:v.shell.user?.email??null,deMethod:s,fcThreshold:1,pThreshold:Ne,version:1,publishId:r,includesEnrichment:o,supersedes:null,supersededBy:null}}function Re(){const t=Date.UTC(2026,5,1),n=[];for(let e=0;e<5;e++)n.push(t+864e5*e);const o=e.Column.fromList(e.COLUMN_TYPE.DATE_TIME,"acquisition_datetime",n),r=e.Column.fromFloat32Array("metric",new Float32Array([4.8,5.1,4.9,5.2,5]));return e.DataFrame.fromColumns([o,r])}function Ge(e){try{v.dapi.files.writeAsText("System:AppData/Proteomics/spike/spike-result.md",e)}catch(e){}try{v.shell.info(e.split("\n")[0])}catch(e){}console.log("[SPC spike] outcome\n"+e)}function ke(e,t,n){let o=0,r=0;for(;0===o;)o=e();for(;0===r;)r=e();return t+n*Math.sqrt(-2*Math.log(o))*Math.cos(2*Math.PI*r)}function $e(e,t,n,o){const r=function(e){let t=e>>>0;return()=>(t=Math.imul(t,1664525)+1013904223>>>0,t/4294967295)}(e),s=[];for(let e=0;e<t;e++)s.push(ke(r,n,o));return s}function Be(){const e="undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"test-"+Math.random().toString(16).slice(2);return`System:AppData/Proteomics/spc-test/${String(e).replace(/[^A-Za-z0-9._-]/g,"-")}`}async function Ue(e){try{await v.dapi.files.delete(e)}catch(e){}}(0,t.L1)("Publishing",()=>{(0,t.t6)("assertPublishedShape round-trip on synthetic fixture (no-enrichment) — formula lines survive reopen",async()=>{const n=Ae(),o=v.shell.addTableView(n);await(0,t.cb)(100);try{o.scatterPlot?.({x:"log2FC",y:"adj.p-value"})}catch{}await(0,t.cb)(100);const r=`${Se}t1-${Date.now()}`,s={target:r,reviewerGroup:await De(),note:"Phase 15 roundtrip Test 1",priorVersion:null};let a=null;try{a=await(0,be.M)(n,s),(0,t.E3)(!!a,!0);const o=a.name,i=Oe(a,n,r,!1),l=Me(),c=Le(`${n.name}_published_${(new Date).toISOString().slice(0,10)}`,o,l,i,!1);await(0,Te.F)(a,c);const u=v.shell.tv;(0,t.E3)(!!u,!0);const m=u?Array.from(u.viewers).find(t=>t.type===e.VIEWER.SCATTER_PLOT):null;(0,t.E3)(!!m,!0);const p=[];try{const e=u.dataFrame.meta?.formulaLines?.items??[];for(const t of e)"string"==typeof t?.formula&&p.push(t.formula)}catch{}try{const e=m.getOptions?.(),t=e?.look?.formulaLines,n="string"==typeof t?JSON.parse(t):t;if(Array.isArray(n))for(const e of n)"string"==typeof e?.formula&&p.push(e.formula)}catch{}const d=p.some(e=>e.includes(String(1))||e.includes("-1")),f=p.some(e=>e.includes(String(Ne))||e.includes(String(-Math.log10(Ne)))||e.includes("log10"));(0,t.E3)(d,!0),(0,t.E3)(f,!0)}finally{await Fe(a),await Ie(r)}}),(0,t.t6)("assertPublishedShape round-trip on Spectronaut Candidates fixture (with-enrichment); cross-DF subscription re-established on reopen",async()=>{const{protein:e,enrichment:n}=xe(),o=v.shell.addTableView(e);await(0,t.cb)(50),v.shell.addTableView(n),await(0,t.cb)(100);try{v.shell.v=o}catch{}try{o.scatterPlot?.({x:"log2FC",y:"adj.p-value"})}catch{}await(0,t.cb)(100);const r=`${Se}t2-${Date.now()}`,s={target:r,reviewerGroup:await De(),note:"Phase 15 roundtrip Test 2",priorVersion:null};let a=null;try{a=await(0,be.M)(e,s),(0,t.E3)(!!a,!0);const n=a.name,o=Oe(a,e,r,!0),i=Me(),l=Le(`${e.name}_published_${(new Date).toISOString().slice(0,10)}`,n,i,o,!0);await(0,Te.F)(a,l);const c=v.shell.tables;(0,t.E3)(Array.isArray(c),!0);const u=(c??[]).find(e=>"true"===e.getTag(Ce.L6.PUBLISHED)&&"true"!==e.getTag("proteomics.enrichment")),m=(c??[]).find(e=>"true"===e.getTag("proteomics.enrichment"));if((0,t.E3)(!!u,!0),(0,t.E3)(!!m,!0),await(0,t.cb)(300),"true"!==m.getTag("proteomics.enrichment_wired"))try{await(0,Pe.I)(u)}catch{}(0,t.E3)(m.getTag("proteomics.enrichment_wired"),"true"),u.selection.setAll(!1,!1);const p=u.selection.trueCount;m.currentRowIdx=0,await(0,t.cb)(150);const d=u.selection.trueCount;(0,t.E3)(d>p,!0)}finally{await Fe(a),await Ie(r)}}),(0,t.t6)("workspace restore (Step 10) brings back BOTH the protein and enrichment views",async()=>{const{protein:e,enrichment:n}=xe(),o=v.shell.addTableView(e);await(0,t.cb)(50),v.shell.addTableView(n),await(0,t.cb)(100);try{v.shell.v=o}catch{}await(0,t.cb)(50);const r=`${Se}restore-${Date.now()}`,s={target:r,reviewerGroup:await De(),note:"restore test",priorVersion:null,verify:!1};let a=null;try{a=await(0,be.M)(e,s),(0,t.E3)(!!a,!0),await(0,t.cb)(200);const o=e.dart,r=n.dart;let i=!1,l=!1;for(const e of v.shell.tableViews){const t=e.dataFrame?.dart;t===o&&(i=!0),t===r&&(l=!0)}(0,t.E3)(i,!0),(0,t.E3)(l,!0),(0,t.E3)(v.shell.tv?.dataFrame?.dart,o)}finally{await Fe(a),await Ie(r)}}),(0,t.t6)("source mutation after publish leaves clone unchanged (Pitfall 1)",async()=>{const e=Ae(),n=e.col("log2FC").get(0),o=`${Se}t3-${Date.now()}`;v.shell.addTableView(e),await(0,t.cb)(100);const r={target:o,reviewerGroup:await De(),note:"",priorVersion:null};let s=null;try{s=await(0,be.M)(e,r),(0,t.E3)(!!s,!0);const a=s.id;v.shell.closeAll(),await(0,t.cb)(100);const i=await v.dapi.projects.find(a);await i.open(),await(0,t.bk)(()=>!!v.shell.tv&&!!v.shell.tv.dataFrame,"reopened1 TableView never materialized",5e3);const l=v.shell.tv.dataFrame.col("log2FC").get(0);(0,t.E3)(l,n),e.col("log2FC").set(0,999.999);try{e.columns.remove("Gene Name")}catch{}e.setTag(Ce.L6.PUBLISHED_TARGET,"CHANGED-TARGET"),v.shell.closeAll(),await(0,t.cb)(100);const c=await v.dapi.projects.find(a);await c.open(),await(0,t.bk)(()=>!!v.shell.tv&&!!v.shell.tv.dataFrame,"reopened2 TableView never materialized",5e3);const u=v.shell.tv.dataFrame,m=u.col("log2FC").get(0);(0,t.E3)(m,n),(0,t.E3)(!!u.col("Gene Name"),!0);const p=u.getTag(Ce.L6.PUBLISHED_TARGET);(0,t.E3)("CHANGED-TARGET"===p,!1),(0,t.E3)(p===o,!0)}finally{await Fe(s),await Ie(o)}}),(0,t.t6)("republish creates v2 with bidirectional superseded_by + supersedes pointers (W-8 dual-write)",async()=>{const e=Ae(),n=`${Se}t4-${Date.now()}`;v.shell.addTableView(e),await(0,t.cb)(100);const o=await De(),r={target:n,reviewerGroup:o,note:"v1",priorVersion:null};let s=null,a=null;try{s=await(0,be.M)(e,r),(0,t.E3)(!!s,!0);const i=s.id,l=s.name;(0,t.E3)(/-v1-\d{4}-\d{2}-\d{2}$/.test(l),!0),await(0,t.cb)(200);const c={target:n,reviewerGroup:o,note:"v2",priorVersion:s};a=await(0,be.M)(e,c),(0,t.E3)(!!a,!0);const u=a.id,m=a.name;(0,t.E3)(/-v2-\d{4}-\d{2}-\d{2}$/.test(m),!0),v.shell.closeAll(),await(0,t.cb)(100);const p=await v.dapi.projects.find(u);await p.open(),await(0,t.bk)(()=>!!v.shell.tv&&!!v.shell.tv.dataFrame,"v2 reopen",5e3);const d=p.options??{};(0,t.E3)(d[Ce.L6.SUPERSEDES],i),v.shell.closeAll(),await(0,t.cb)(100);const f=await v.dapi.projects.find(i);await f.open(),await(0,t.bk)(()=>!!v.shell.tv&&!!v.shell.tv.dataFrame,"v1 reopen",5e3);const g=f.options??{};(0,t.E3)(g[Ce.L6.SUPERSEDED_BY],u);const h=v.shell.tv.dataFrame;(0,t.E3)(h.getTag(Ce.L6.SUPERSEDED_BY),u);const y=h.col(Ce.MD.SUPERSEDED_BY);if(y){const e=y.get(0);""!==e&&null!=e&&(0,t.E3)(String(e),u)}const E=await v.dapi.projects.find(i);(0,t.E3)(!!E,!0)}finally{await Fe(a),await Fe(s),await Ie(n)}}),(0,t.t6)("verify-and-rollback rejects Edit-inherited grant with exact D-03 error string",async()=>{const e=v.dapi,n=`Test-Proteomics-Reviews-${Date.now()}`,o=await e.spaces.createRootSpace(n),r=v.shell.user?.group;try{await v.dapi.permissions.grant(o,r,!0);const s=Ae();v.shell.addTableView(s),await(0,t.cb)(100);const a=`${Se}t5-${Date.now()}`,i={target:a,reviewerGroup:r,note:"negative test",priorVersion:null,umbrellaName:n};let l="",c=null;try{c=await(0,be.M)(s,i)}catch(e){l=String(e?.message??e??"")}(0,t.E3)(l.length>0,!0);const u=l.includes("Reviewer group already has elevated access via Space inheritance");(0,t.E3)(u,!0);try{const n="Proteomics-Review-%",o=(await e.projects.filter(`name like "${n}"`).list()??[]).filter(e=>"string"==typeof e?.name&&e.name.includes(a));(0,t.E3)(o.length,0)}catch{}c&&await Fe(c)}finally{await async function(){try{await(async()=>{await e.spaces.delete(o)})()}catch{}}()}})}),(0,t.L1)("SPC",()=>{(0,t.t6)("SPC:spike_formula_line_dashed_on_datetime",async()=>{const n=Re(),o=e.Viewer.lineChart(n,{xColumnName:"acquisition_datetime",yColumnNames:["metric"]});let r="FAIL",s="",a="";try{const e=o.meta?.formulaLines;if(e&&"function"==typeof e.addLine){e.addLine({formula:"${metric} = 5",style:"dashed",color:"#666666",width:1,visible:!0,title:"UCL"});const t=e.items,n=t&&t[0]?t[0].style:void 0;s="items[0].style="+String(n),"dashed"===n?r="PASS":a='style honored !== "dashed" (observed: '+String(n)+")"}else a="viewer.meta.formulaLines.addLine not addressable on lineChart"}catch(e){a=e&&e.message?e.message:String(e)}Ge(`OUTCOME: ${r}\nObservation: ${s}\n`+(a?`PlatformError: ${a}\n`:"")+"Test: SPC:spike_formula_line_dashed_on_datetime\n"+`Timestamp: ${(new Date).toISOString()}\n`),(0,t.E3)(!0,!0)}),(0,t.t6)("SPC:spike_three_lines_ucl_cl_lcl",async()=>{const n=Re(),o=e.Viewer.lineChart(n,{xColumnName:"acquisition_datetime",yColumnNames:["metric"]}),r=[{formula:"${metric} = 5.4",style:"dashed",color:"#666666",width:1,visible:!0,title:"UCL"},{formula:"${metric} = 5.0",style:"solid",color:"#666666",width:1,visible:!0,title:"CL"},{formula:"${metric} = 4.6",style:"dashed",color:"#666666",width:1,visible:!0,title:"LCL"}];let s=0,a="",i=0;try{const e=o.meta?.formulaLines;if(e&&"function"==typeof e.addLine){for(const t of r)try{e.addLine(t),s++}catch(e){a=e&&e.message?e.message:String(e)}const t=e.items??[];for(const e of t)e&&"dashed"===e.style&&i++}else a="viewer.meta.formulaLines.addLine not addressable on lineChart"}catch(e){a=e&&e.message?e.message:String(e)}Ge(`## Secondary observation: three-lines UCL/CL/LCL\nAdded: ${s}/3\nDashedHonored: ${i}\n`+(a?`PlatformError: ${a}\n`:"")+"Test: SPC:spike_three_lines_ucl_cl_lcl\n"+`Timestamp: ${(new Date).toISOString()}\n`),(0,t.E3)(!0,!0)})}),(0,t.L1)("SPC",()=>{(0,t.t6)("SPC:median_intensity",async()=>{const o=await Promise.resolve().then(n.bind(n,655)),r=e.DataFrame.fromColumns([e.Column.fromFloat32Array("log2(s1)",new Float32Array([10,11,12,13,14])),e.Column.fromFloat32Array("log2(s2)",new Float32Array([11,12,13,14,15]))]);r.col("log2(s1)").semType="Proteomics-Intensity",r.col("log2(s2)").semType="Proteomics-Intensity";const s=o.computeSpcMetrics(r,{group1:{name:"Control",columns:["log2(s1)"]},group2:{name:"Treatment",columns:["log2(s2)"]}},{instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z"});(0,t.E3)(typeof s.median_intensity,"number"),(0,t.E3)(Math.abs(s.median_intensity-12.5)<.6,!0)}),(0,t.t6)("SPC:missing_pct",async()=>{const o=await Promise.resolve().then(n.bind(n,655)),r=e.Column.fromFloat32Array("log2(s1)",new Float32Array([10,NaN,12,NaN])),s=e.Column.fromFloat32Array("log2(s2)",new Float32Array([NaN,11,NaN,14])),a=e.DataFrame.fromColumns([r,s]);a.col("log2(s1)").semType="Proteomics-Intensity",a.col("log2(s2)").semType="Proteomics-Intensity";const i=o.computeSpcMetrics(a,{group1:{name:"Control",columns:["log2(s1)"]},group2:{name:"Treatment",columns:["log2(s2)"]}},{instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z"});(0,t.E3)(Math.abs(i.missing_pct-50)<.001,!0)}),(0,t.t6)("SPC:control_corr",async()=>{const o=await Promise.resolve().then(n.bind(n,655)),r=e.Column.fromFloat32Array("log2(c1)",new Float32Array([1,2,3,4,5])),s=e.Column.fromFloat32Array("log2(c2)",new Float32Array([2,4,6,8,10])),a=e.Column.fromFloat32Array("log2(c3)",new Float32Array([3,6,9,12,15])),i=e.Column.fromFloat32Array("log2(t1)",new Float32Array([5,4,3,2,1])),l=e.DataFrame.fromColumns([r,s,a,i]);[r,s,a,i].forEach(e=>e.semType="Proteomics-Intensity");const c=o.computeSpcMetrics(l,{group1:{name:"Control",columns:["log2(c1)","log2(c2)","log2(c3)"]},group2:{name:"Treatment",columns:["log2(t1)"]}},{instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z"});(0,t.E3)(Math.abs(c.control_corr-1)<.001,!0)}),(0,t.t6)("SPC:protein_count",async()=>{const o=await Promise.resolve().then(n.bind(n,655)),r=e.Column.fromFloat32Array("log2(s1)",new Float32Array([10,NaN,12,NaN,14])),s=e.Column.fromFloat32Array("log2(s2)",new Float32Array([NaN,NaN,13,99,15])),a=e.DataFrame.fromColumns([r,s]);a.col("log2(s1)").semType="Proteomics-Intensity",a.col("log2(s2)").semType="Proteomics-Intensity";const i=o.computeSpcMetrics(a,{group1:{name:"Control",columns:["log2(s1)"]},group2:{name:"Treatment",columns:["log2(s2)"]}},{instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z"});(0,t.E3)(i.protein_count,4)}),(0,t.t6)("SPC:nelson_default",async()=>{const e=await Promise.resolve().then(n.bind(n,655)),o=e.defaultRulesEnabled();(0,t.E3)(o.nelson_1,!0),(0,t.E3)(o.nelson_5,!0),(0,t.E3)(o.nelson_2,!1),(0,t.E3)(o.nelson_3,!1),(0,t.E3)(o.nelson_4,!1),(0,t.E3)(o.nelson_6,!1),(0,t.E3)(o.nelson_7,!1),(0,t.E3)(o.nelson_8,!1);const r=e.evaluateNelsonRules([9.5,10.2,9.8,10.4,10.1],10,1,o);(0,t.E3)(r.status,"pass"),(0,t.E3)(Array.isArray(r.rulesTripped),!0),(0,t.E3)(r.rulesTripped.length,0)}),(0,t.t6)("SPC:nelson_rule_1_3sigma",async()=>{const e=await Promise.resolve().then(n.bind(n,655)),o=e.defaultRulesEnabled(),r=e.evaluateNelsonRules([9.5,10.2,9.8,10.4,15],10,1,o);(0,t.E3)(r.status,"out_of_control"),(0,t.E3)(r.rulesTripped.includes("nelson_1"),!0)}),(0,t.t6)("SPC:nelson_rule_5_2of3",async()=>{const e=await Promise.resolve().then(n.bind(n,655)),o=e.defaultRulesEnabled(),r=e.evaluateNelsonRules([10,9.9,12.4,10,12.3],10,1,o);(0,t.E3)(r.rulesTripped.includes("nelson_5"),!0),(0,t.E3)(r.status,"flagged")}),(0,t.t6)("SPC:false_alarm_rate",async()=>{const e=await Promise.resolve().then(n.bind(n,655)),o=e.defaultRulesEnabled();let r=0;for(let t=1;t<=200;t++){const n=$e(t,8,10,1);e.evaluateNelsonRules(n,10,1,o).rulesTripped.length>0&&r++}const s=r/200;(0,t.E3)(s<.05,!0)}),(0,t.t6)("SPC:status_tags",async()=>{const o=await Promise.resolve().then(n.bind(n,655)),r=e.DataFrame.create(1),s={median_intensity:22.31,missing_pct:12.6,control_corr:.94,protein_count:4820,sample_count:3,computed_at:(new Date).toISOString()};o.setSpcStatus(r,s,{status:"flagged",rulesTripped:["nelson_5@control_corr"]}),(0,t.E3)(r.getTag("proteomics.spc_status"),"flagged"),(0,t.E3)(JSON.parse(r.getTag("proteomics.spc_metrics")).protein_count,4820),(0,t.E3)(JSON.parse(r.getTag("proteomics.spc_rules_tripped"))[0],"nelson_5@control_corr")}),(0,t.t6)("SPC:classification",async()=>{const e=await Promise.resolve().then(n.bind(n,655));(0,t.E3)(e.classifyStatus([]),"pass"),(0,t.E3)(e.classifyStatus(["nelson_1@median_intensity"]),"out_of_control"),(0,t.E3)(e.classifyStatus(["nelson_5@control_corr"]),"flagged"),(0,t.E3)(e.classifyStatus(["nelson_5@control_corr","nelson_1@protein_count"]),"out_of_control")}),(0,t.t6)("SPC:baseline_outlier_removal",async()=>{const e=(await Promise.resolve().then(n.bind(n,655))).computeIterativeBaseline([10.1,9.9,10.2,10,9.95,10.05,10.1,9.9,10.2,10,10.05,100],!0);(0,t.E3)(e.includedCount,11),(0,t.E3)(e.excludedIndices.includes(11),!0),(0,t.E3)(e.iterationTrace.length>=1,!0)}),(0,t.t6)("SPC:baseline_iteration_cap",async()=>{const e=(await Promise.resolve().then(n.bind(n,655))).computeIterativeBaseline([10,10.1,9.9,25,25.1,24.9,30,30.5,29.7],!0);(0,t.E3)(e.iterationTrace.length<=2,!0)}),(0,t.t6)("SPC:baseline_roundtrip",async()=>{const e=await Promise.resolve().then(n.bind(n,883)),o=Be();try{const n={instrument_id:"Q-rt",locked_at:(new Date).toISOString(),included_run_ids:["uuid-a","uuid-b"],excluded_run_ids:[],iteration_trace:[],metrics:{median_intensity:{mean:22.31,sd:.42},missing_pct:{mean:12.6,sd:1.1},control_corr:{mean:.94,sd:.018},protein_count:{mean:4820,sd:145}},rules_enabled:{median_intensity:{nelson_1:!0,nelson_5:!0},missing_pct:{nelson_1:!0,nelson_5:!0},control_corr:{nelson_1:!0,nelson_5:!0},protein_count:{nelson_1:!0,nelson_5:!0}}};await e.saveBaseline("Q-rt",n,{root:o});const r=await e.loadBaseline("Q-rt",{root:o});(0,t.E3)(r.metrics.median_intensity.mean,22.31),(0,t.E3)(r.included_run_ids[0],"uuid-a")}finally{await Ue(o)}}),(0,t.t6)("SPC:baseline_rebuild_overwrites",async()=>{const e=await Promise.resolve().then(n.bind(n,883)),o=Be();try{const n={instrument_id:"Q-X",locked_at:"A",included_run_ids:["1"],excluded_run_ids:[],iteration_trace:[],metrics:{},rules_enabled:{}},r={instrument_id:"Q-X",locked_at:"B",included_run_ids:["2"],excluded_run_ids:[],iteration_trace:[],metrics:{},rules_enabled:{}};await e.saveBaseline("Q-X",n,{root:o}),await e.saveBaseline("Q-X",r,{root:o});const s=await e.loadBaseline("Q-X",{root:o});(0,t.E3)(s.locked_at,"B"),(0,t.E3)(s.included_run_ids[0],"2")}finally{await Ue(o)}}),(0,t.t6)("SPC:rule_toggle_per_instrument",async()=>{const e=await Promise.resolve().then(n.bind(n,883)),o=Be();try{const n={instrument_id:"Q-rt",locked_at:"X",included_run_ids:[],excluded_run_ids:[],iteration_trace:[],metrics:{},rules_enabled:{median_intensity:{nelson_1:!0,nelson_5:!1,nelson_2:!0},missing_pct:{nelson_1:!0,nelson_5:!0},control_corr:{nelson_1:!0,nelson_5:!0},protein_count:{nelson_1:!0,nelson_5:!0}}};await e.saveBaseline("Q-rt",n,{root:o});const r=await e.loadBaseline("Q-rt",{root:o});(0,t.E3)(r.rules_enabled.median_intensity.nelson_5,!1),(0,t.E3)(r.rules_enabled.median_intensity.nelson_2,!0)}finally{await Ue(o)}}),(0,t.t6)("SPC:run_meta_helpers",async()=>{const{setRunMeta:o,getRunMeta:r}=await Promise.resolve().then(n.bind(n,655)),s=e.DataFrame.create(),a={instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z"};o(s,a),(0,t.E3)(JSON.stringify(r(s)),JSON.stringify(a))}),(0,t.t6)("SPC:annotation_dialog_persists_run_meta",async()=>{const o=await Promise.resolve().then(n.bind(n,252)),r=e.DataFrame.fromColumns([e.Column.fromFloat32Array("log2(c1)",new Float32Array([1,2,3])),e.Column.fromFloat32Array("log2(t1)",new Float32Array([4,5,6]))]);r.col("log2(c1)").semType="Proteomics-Intensity",r.col("log2(t1)").semType="Proteomics-Intensity",(0,t.E3)(typeof o.applyAnnotation,"function"),o.applyAnnotation(r,{group1:{name:"Control",columns:["log2(c1)"]},group2:{name:"Treatment",columns:["log2(t1)"]},runMeta:{instrument_id:"Q-99",acquisition_datetime:"2026-08-01T00:00:00.000Z"}});const s=r.getTag("proteomics.spc_run_meta");(0,t.E3)(typeof s,"string");const a=JSON.parse(s);(0,t.E3)(a.instrument_id,"Q-99"),(0,t.E3)(a.acquisition_datetime,"2026-08-01T00:00:00.000Z")}),(0,t.t6)("SPC:spectronaut_seed",async()=>{const e=await Promise.resolve().then(n.bind(n,53)),o={headerCsv:["PG.ProteinGroups\tR.Condition\tR.Replicate\tPG.Quantity\tEG.Qvalue\tR.FileName\tPG.Organisms\tR.RunDate\tR.InstrumentMethod",`P00001\tCtrl\t1\t1000\t0.001\trun1.raw\tHuman\t${r="2026-07-10T00:00:00.000Z"}\t${s="QExactive-01"}`,`P00002\tCtrl\t1\t2000\t0.002\trun1.raw\tHuman\t${r}\t${s}`].join("\n"),expectedSeed:{instrument_id:s,acquisition_datetime:r}};var r,s;const a=(await e.parseSpectronautText(o.headerCsv)).getTag("proteomics.spc_run_meta_seed");(0,t.E3)(typeof a,"string");const i=JSON.parse(a);(0,t.E3)(i.instrument_id,o.expectedSeed.instrument_id),(0,t.E3)(i.acquisition_datetime,o.expectedSeed.acquisition_datetime)}),(0,t.t6)("SPC:backfill_ordering",async()=>{const e=await Promise.resolve().then(n.bind(n,883)),o=Be();try{await e.upsertRun({run_id:"a",instrument_id:"Q-01",acquisition_datetime:"2026-07-20T00:00:00.000Z",run_label:"r-20",median_intensity:1,missing_pct:1,control_corr:1,protein_count:1,status:"pass",rules_tripped:[],source_project_id:null,source_df_name:"a",computed_at:(new Date).toISOString()},{root:o}),await e.upsertRun({run_id:"b",instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z",run_label:"r-10",median_intensity:1,missing_pct:1,control_corr:1,protein_count:1,status:"pass",rules_tripped:[],source_project_id:null,source_df_name:"b",computed_at:(new Date).toISOString()},{root:o}),await e.upsertRun({run_id:"c",instrument_id:"Q-01",acquisition_datetime:"2026-07-15T00:00:00.000Z",run_label:"r-15",median_intensity:1,missing_pct:1,control_corr:1,protein_count:1,status:"pass",rules_tripped:[],source_project_id:null,source_df_name:"c",computed_at:(new Date).toISOString()},{root:o});const n=await e.loadRuns("Q-01",{root:o});(0,t.E3)(n.length,3),(0,t.E3)(n[0].acquisition_datetime,"2026-07-10T00:00:00.000Z"),(0,t.E3)(n[1].acquisition_datetime,"2026-07-15T00:00:00.000Z"),(0,t.E3)(n[2].acquisition_datetime,"2026-07-20T00:00:00.000Z")}finally{await Ue(o)}},{skipReason:"Quarantined: userDataStorage write/read consistency — 3 sequential upserts read back 2 on newer Datagrok runtime — see BACKLOG"}),(0,t.t6)("SPC:candidates_refuse",async()=>{const o=await Promise.resolve().then(n.bind(n,655)),r=e.DataFrame.create(1);r.setTag("proteomics.source","spectronaut-candidates"),(0,t.E3)(typeof o.assertSpcEligible,"function");let s=!1,a="";try{o.assertSpcEligible(r)}catch(e){s=!0,a=String(e&&e.message?e.message:e)}(0,t.E3)(s,!0),(0,t.E3)(a.indexOf("SPC requires per-sample intensities")>=0,!0)}),(0,t.t6)("SPC:idempotent_upsert",async()=>{const e=await Promise.resolve().then(n.bind(n,883)),o=Be();try{const n={run_id:"r1",instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z",run_label:"first-call",median_intensity:22.31,missing_pct:12.6,control_corr:.94,protein_count:4820,status:"pass",rules_tripped:[],source_project_id:null,source_df_name:"first-call",computed_at:(new Date).toISOString()};await e.upsertRun(n,{root:o}),await e.upsertRun({...n,run_label:"second-call",median_intensity:23},{root:o});const r=await e.loadRuns("Q-01",{root:o});(0,t.E3)(r.length,1),(0,t.E3)(r[0].run_label,"second-call"),(0,t.E3)(r[0].median_intensity,23)}finally{await Ue(o)}}),(0,t.t6)("SPC:storage_bounded",async()=>{const e=await Promise.resolve().then(n.bind(n,883)),o=Be();try{for(let t=1;t<=2;t++)for(let n=0;n<52;n++){const r=String(1+n%28).padStart(2,"0"),s=String(1+Math.floor(n/4)%12).padStart(2,"0");await e.upsertRun({run_id:`i${t}-w${n}`,instrument_id:`Q-0${t}`,acquisition_datetime:`2026-${s}-${r}T00:00:00.000Z`,run_label:`wk${n}`,median_intensity:22,missing_pct:12,control_corr:.9,protein_count:4e3,status:"pass",rules_tripped:[],source_project_id:null,source_df_name:`wk${n}`,computed_at:(new Date).toISOString()},{root:o})}const n=await e.loadRuns("Q-01",{root:o}),r=await e.loadRuns("Q-02",{root:o});(0,t.E3)(n.length<=52,!0),(0,t.E3)(r.length<=52,!0)}finally{await Ue(o)}}),(0,t.t6)("SPC:schema_version",async()=>{const e=await Promise.resolve().then(n.bind(n,883)),o=Be();try{await e.upsertRun({run_id:"r1",instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z",run_label:"r",median_intensity:1,missing_pct:1,control_corr:1,protein_count:1,status:"pass",rules_tripped:[],source_project_id:null,source_df_name:"r",computed_at:(new Date).toISOString()},{root:o});const n=await e.readRunsMeta({root:o});(0,t.E3)(n["spc.runs.schema_version"],"1")}finally{await Ue(o)}}),(0,t.t6)("SPC:column_idempotent",async()=>{const o=await Promise.resolve().then(n.bind(n,655)),r=e.DataFrame.fromColumns([e.Column.fromFloat32Array("log2(s1)",new Float32Array([10,11,12])),e.Column.fromFloat32Array("log2(s2)",new Float32Array([11,12,13]))]);r.col("log2(s1)").semType="Proteomics-Intensity",r.col("log2(s2)").semType="Proteomics-Intensity";const s={group1:{name:"Control",columns:["log2(s1)"]},group2:{name:"Treatment",columns:["log2(s2)"]}},a={instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z"},i=o.computeSpcMetrics(r,s,a);o.setSpcStatus(r,i,{status:"pass",rulesTripped:[]});const l=r.columns.length,c=o.computeSpcMetrics(r,s,a);o.setSpcStatus(r,c,{status:"pass",rulesTripped:[]}),(0,t.E3)(r.columns.length,l)}),(0,t.t6)("SPC:belt_and_braces",async()=>{const o=await Promise.resolve().then(n.bind(n,655)),r=e.DataFrame.fromColumns([e.Column.fromFloat32Array("log2(s1)",new Float32Array([10,11,12])),e.Column.fromFloat32Array("log2(s2)",new Float32Array([11,12,13]))]);r.col("log2(s1)").semType="Proteomics-Intensity",r.col("log2(s2)").semType="Proteomics-Intensity";const s=o.computeSpcMetrics(r,{group1:{name:"Control",columns:["log2(s1)"]},group2:{name:"Treatment",columns:["log2(s2)"]}},{instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z"});o.setSpcStatus(r,s,{status:"pass",rulesTripped:[]});const a=r.col("~spc_metrics_meta");(0,t.E3)(null!==a,!0),r.setTag("proteomics.spc_metrics",""),(0,t.E3)(typeof o.recoverSpcMetricsFromColumn(r),"object")}),(0,t.t6)("SPC:drilldown_resolved",async()=>{const e=await Promise.resolve().then(n.bind(n,589)),o=await e.resolveDrillDown({run_id:"r1",instrument_id:"Q-01",source_project_id:"proj-abc",run_label:"r-abc"},{projectsFind:async e=>({id:e,open:()=>"opened:"+e})});(0,t.E3)(o.kind,"opened"),(0,t.E3)(o.id,"proj-abc")}),(0,t.t6)("SPC:drilldown_missing",async()=>{const e=await Promise.resolve().then(n.bind(n,589)),o=await e.resolveDrillDown({run_id:"r2",instrument_id:"Q-01",source_project_id:null,run_label:"r-zzz"},{projectsFind:async e=>null});(0,t.E3)(o.kind,"toast"),(0,t.E3)(o.message.indexOf("Source for")>=0,!0),(0,t.E3)(o.message.indexOf("r-zzz")>=0,!0)}),(0,t.t6)("SPC:dashboard_renders",async()=>{const o=await Promise.resolve().then(n.bind(n,589)),r=function(t){if(0===t.length)return e.DataFrame.create(0);const n=Object.keys(t[0]),o=[];for(const r of n){const n=t.map(e=>e[r]);"number"==typeof n.find(e=>null!=e)?o.push(e.Column.fromList(e.COLUMN_TYPE.FLOAT,r,n.map(e=>e??null))):o.push(e.Column.fromStrings(r,n.map(e=>null==e?"":String(e))))}return e.DataFrame.fromColumns(o)}([{run_id:"1",instrument_id:"Q-01",acquisition_datetime:"2026-07-01T00:00:00.000Z",run_label:"r1",median_intensity:22,missing_pct:12,control_corr:.9,protein_count:4800,status:"pass",source_project_id:null,source_df_name:"r1",computed_at:"X"},{run_id:"2",instrument_id:"Q-01",acquisition_datetime:"2026-07-08T00:00:00.000Z",run_label:"r2",median_intensity:22.5,missing_pct:12.2,control_corr:.93,protein_count:4810,status:"pass",source_project_id:null,source_df_name:"r2",computed_at:"X"}]),s=o.createSpcChartPanel(r,{metrics:{median_intensity:{mean:22.3,sd:.5},missing_pct:{mean:12,sd:1},control_corr:{mean:.92,sd:.02},protein_count:{mean:4800,sd:100}}},"median_intensity");(0,t.E3)(null!=s,!0)}),(0,t.t6)("SPC:formula_lines",async()=>{const e=(await Promise.resolve().then(n.bind(n,589))).computeControlLines({metrics:{median_intensity:{mean:22.3,sd:.5}}},"median_intensity");(0,t.E3)(e.ucl,23.8),(0,t.E3)(e.cl,22.3),(0,t.E3)(e.lcl,20.8)}),(0,t.t6)("SPC:pareto_descending",async()=>{const e=(await Promise.resolve().then(n.bind(n,589))).aggregateParetoCounts([{rules_tripped:["nelson_1@median_intensity","nelson_5@control_corr"]},{rules_tripped:["nelson_1@median_intensity"]},{rules_tripped:["nelson_1@median_intensity","nelson_5@control_corr"]},{rules_tripped:[]}]);(0,t.E3)(e.length>=2,!0);for(let n=1;n<e.length;n++)(0,t.E3)(e[n-1].count>=e[n].count,!0);(0,t.E3)(e[0].rule+"@"+e[0].metric,"nelson_1@median_intensity"),(0,t.E3)(e[0].count,3)}),t.bk,t.cb});const je=new e.Package;async function Ve(n,o,r){const s=await(0,t.N$)({category:n,test:o,testContext:r});return e.DataFrame.fromObjects(s)}async function qe(){await(0,t.Xb)(je,je.getModule("package-test.js"))}})(),proteomics_test=o})();
|
|
1
|
+
var proteomics_test;(()=>{var e={749(e,t,n){"use strict";n.d(t,{bk:()=>L,L1:()=>b,cb:()=>D,E3:()=>C,Xb:()=>P,N$:()=>S,t6:()=>_,CN:()=>m}),n(982);const o=DG.DataFrame.fromCsv('countries,fasta,smiles,molregno,LON,Zip Code,Street Address Line 1,ImageUrl,user_id,error_message,xray,flag,magnitude,CS-id,pdb_id,accel_a,time_offset,chart,fit,Questions,empty_number,empty_string\nBelgium,MSNFHNEHVMQFYRNNLKTKGVFGRQ,CC(C(=O)OCCCc1cccnc1)c2cccc(c2)C(=O)c3ccccc3,1480014,36.276729583740234,995042300,14016 ROUTE 31W,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,1,1,1QBS,1,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[2.497360340644872, 1.7058694986686864, 5.278052678195135, 0.16000320889028383],""points"":[{""x"":0.10000000149011612,""y"":2.374499797821045},{""x"":0.6000000238418579,""y"":2.6242473125457764},{""x"":1.100000023841858,""y"":2.367267608642578},{""x"":1.600000023841858,""y"":2.6723148822784424},{""x"":2.0999999046325684,""y"":2.6537344455718994},{""x"":2.5999999046325684,""y"":2.3651671409606934},{""x"":3.0999999046325684,""y"":2.5654284954071045},{""x"":3.5999999046325684,""y"":2.4160959720611572},{""x"":4.099999904632568,""y"":2.286726713180542},{""x"":4.599999904632568,""y"":2.5100042819976807},{""x"":5.099999904632568,""y"":1.6676985025405884},{""x"":5.599999904632568,""y"":0.680136501789093},{""x"":6.099999904632568,""y"":0.3391543924808502},{""x"":6.599999904632568,""y"":0.09038983285427094},{""x"":7.099999904632568,""y"":0.19802775979042053}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[7.525235855508179, 1.3186911876809984, 5.335672608564294, 0.7860743343958098],""points"":[{""x"":0.10000000149011612,""y"":7.988070487976074},{""x"":0.6000000238418579,""y"":7.018453121185303},{""x"":1.100000023841858,""y"":8.115279197692871},{""x"":1.600000023841858,""y"":7.486658096313477},{""x"":2.0999999046325684,""y"":7.396438121795654},{""x"":2.5999999046325684,""y"":7.477052211761475},{""x"":3.0999999046325684,""y"":6.913095474243164},{""x"":3.5999999046325684,""y"":8.01385498046875},{""x"":4.099999904632568,""y"":6.985900402069092},{""x"":4.599999904632568,""y"":6.970335960388184},{""x"":5.099999904632568,""y"":5.448817253112793},{""x"":5.599999904632568,""y"":2.5534818172454834},{""x"":6.099999904632568,""y"":1.893947958946228},{""x"":6.599999904632568,""y"":0.6340042352676392},{""x"":7.099999904632568,""y"":0.8403874039649963}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,100,abc\nBurundi,MDYKETLLMPKTDFPMRGGLPNKEPQIQEKW,COc1ccc2cc(ccc2c1)C(C)C(=O)Oc3ccc(C)cc3OC,1480015,36.276729583740234,995073444,80 STATE HIGHWAY 310,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,2,2,1ZP8,2,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[4.431460753103398, 2.1691498799246745, 5.266445597102774, 0.7825762827017926],""points"":[{""x"":0.10000000149011612,""y"":4.751083850860596},{""x"":0.6000000238418579,""y"":4.203000068664551},{""x"":1.100000023841858,""y"":4.415858745574951},{""x"":1.600000023841858,""y"":4.68414306640625},{""x"":2.0999999046325684,""y"":4.198400974273682},{""x"":2.5999999046325684,""y"":4.179222106933594},{""x"":3.0999999046325684,""y"":4.638473987579346},{""x"":3.5999999046325684,""y"":4.708553314208984},{""x"":4.099999904632568,""y"":4.291589260101318},{""x"":4.599999904632568,""y"":4.038082599639893},{""x"":5.099999904632568,""y"":3.4349939823150635},{""x"":5.599999904632568,""y"":1.2194708585739136},{""x"":6.099999904632568,""y"":1.1920831203460693},{""x"":6.599999904632568,""y"":0.5352635979652405},{""x"":7.099999904632568,""y"":0.3346920311450958}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[2.339458017970126, -1.0734184310171178, 4.746332950550934, 0.2482416857595658],""points"":[{""x"":0.10000000149011612,""y"":0.2139337658882141},{""x"":0.6000000238418579,""y"":0.4269562065601349},{""x"":1.100000023841858,""y"":0.2441573292016983},{""x"":1.600000023841858,""y"":0.146635964512825},{""x"":2.0999999046325684,""y"":0.08818462491035461},{""x"":2.5999999046325684,""y"":0.2560656666755676},{""x"":3.0999999046325684,""y"":0.42434045672416687},{""x"":3.5999999046325684,""y"":0.37111231684684753},{""x"":4.099999904632568,""y"":0.5581737160682678},{""x"":4.599999904632568,""y"":1.183590054512024},{""x"":5.099999904632568,""y"":1.5629843473434448},{""x"":5.599999904632568,""y"":2.3211288452148438},{""x"":6.099999904632568,""y"":2.229961633682251},{""x"":6.599999904632568,""y"":2.2560226917266846},{""x"":7.099999904632568,""y"":2.2142398357391357}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nCameroon,MIEVFLFGIVLGLIPITLAGLFVTAYLQYRRGDQLDL,COc1ccc2cc(ccc2c1)C(C)C(=O)OCCCc3cccnc3,1480016,36.26095962524414,995153596,30-56 WHITESTONE EXPY,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,3,3,2BDJ,3,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[4.6760652578642325, 0.9046956320756703, 5.651408971856738, 0.07738846012184185],""points"":[{""x"":0.10000000149011612,""y"":4.32425594329834},{""x"":0.6000000238418579,""y"":4.668442249298096},{""x"":1.100000023841858,""y"":4.379785060882568},{""x"":1.600000023841858,""y"":5.0345139503479},{""x"":2.0999999046325684,""y"":4.878653526306152},{""x"":2.5999999046325684,""y"":4.3451313972473145},{""x"":3.0999999046325684,""y"":4.336992263793945},{""x"":3.5999999046325684,""y"":5.037430286407471},{""x"":4.099999904632568,""y"":5.0092692375183105},{""x"":4.599999904632568,""y"":4.151902675628662},{""x"":5.099999904632568,""y"":3.4066951274871826},{""x"":5.599999904632568,""y"":2.3732759952545166},{""x"":6.099999904632568,""y"":1.673728108406067},{""x"":6.599999904632568,""y"":0.48574790358543396},{""x"":7.099999904632568,""y"":0.2783052325248718}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[2.938395863010111, -1.4658480661392117, 5.462702751996584, 0.3473139023615039],""points"":[{""x"":0.10000000149011612,""y"":0.4941710829734802},{""x"":0.6000000238418579,""y"":0.15323974192142487},{""x"":1.100000023841858,""y"":0.46373432874679565},{""x"":1.600000023841858,""y"":0.3370431363582611},{""x"":2.0999999046325684,""y"":0.5179030299186707},{""x"":2.5999999046325684,""y"":0.27899765968322754},{""x"":3.0999999046325684,""y"":0.22075064480304718},{""x"":3.5999999046325684,""y"":0.5789918899536133},{""x"":4.099999904632568,""y"":0.21169911324977875},{""x"":4.599999904632568,""y"":0.27857646346092224},{""x"":5.099999904632568,""y"":1.0906332731246948},{""x"":5.599999904632568,""y"":1.8520300388336182},{""x"":6.099999904632568,""y"":2.7177059650421143},{""x"":6.599999904632568,""y"":2.8680918216705322},{""x"":7.099999904632568,""y"":3.2413077354431152}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nCanada,MMELVLKTIIGPIVVGVVLRIVDKWLNKDK,CC(C(=O)NCCS)c1cccc(c1)C(=O)c2ccccc2,1480017,36.26095962524414,99515,30-56 WHITESTONE EXPY,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,4,4,1IAN,4,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[0.8597390975430008, 1.0957625732481946, 5.260537067987958, 0.07974187998177736],""points"":[{""x"":0.10000000149011612,""y"":0.8190152645111084},{""x"":0.6000000238418579,""y"":0.8421689867973328},{""x"":1.100000023841858,""y"":0.8740922212600708},{""x"":1.600000023841858,""y"":0.8924275040626526},{""x"":2.0999999046325684,""y"":0.8249067664146423},{""x"":2.5999999046325684,""y"":0.9327669143676758},{""x"":3.0999999046325684,""y"":0.8522974252700806},{""x"":3.5999999046325684,""y"":0.8174492716789246},{""x"":4.099999904632568,""y"":0.8394647240638733},{""x"":4.599999904632568,""y"":0.7139387726783752},{""x"":5.099999904632568,""y"":0.5561167597770691},{""x"":5.599999904632568,""y"":0.3276226818561554},{""x"":6.099999904632568,""y"":0.12479474395513535},{""x"":6.599999904632568,""y"":0.13006797432899475},{""x"":7.099999904632568,""y"":0.059702079743146896}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[5.760930219582546, 1.6591793293833013, 4.667155929720851, 0.7858109544121652],""points"":[{""x"":0.10000000149011612,""y"":6.156993389129639},{""x"":0.6000000238418579,""y"":5.236701965332031},{""x"":1.100000023841858,""y"":6.010560512542725},{""x"":1.600000023841858,""y"":5.495512962341309},{""x"":2.0999999046325684,""y"":6.087770462036133},{""x"":2.5999999046325684,""y"":5.79986572265625},{""x"":3.0999999046325684,""y"":5.597546577453613},{""x"":3.5999999046325684,""y"":5.520902156829834},{""x"":4.099999904632568,""y"":5.360654354095459},{""x"":4.599999904632568,""y"":3.5539746284484863},{""x"":5.099999904632568,""y"":1.577236294746399},{""x"":5.599999904632568,""y"":1.0001264810562134},{""x"":6.099999904632568,""y"":0.9305797815322876},{""x"":6.599999904632568,""y"":0.6033638715744019},{""x"":7.099999904632568,""y"":0.4203685522079468}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nColombia,MDRTDEVSNHTHDKPTLTWFEEIFEEYHSPFHN,FC(F)(F)c1ccc(OC2CCNCC2)cc1,1480029,36.3309440612793,995152050,1 COURT HOUSE SQUARE,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,5,5,4UJ1,5,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[6.4995088314153655, 2.4270351004539914, 5.178659535348579, 0.625653346241577],""points"":[{""x"":0.10000000149011612,""y"":6.496231555938721},{""x"":0.6000000238418579,""y"":6.42543363571167},{""x"":1.100000023841858,""y"":7.040063858032227},{""x"":1.600000023841858,""y"":6.1115403175354},{""x"":2.0999999046325684,""y"":6.680728435516357},{""x"":2.5999999046325684,""y"":6.406774520874023},{""x"":3.0999999046325684,""y"":6.611269474029541},{""x"":3.5999999046325684,""y"":5.889094352722168},{""x"":4.099999904632568,""y"":6.75344705581665},{""x"":4.599999904632568,""y"":6.361435890197754},{""x"":5.099999904632568,""y"":4.1666975021362305},{""x"":5.599999904632568,""y"":1.172118902206421},{""x"":6.099999904632568,""y"":0.801048994064331},{""x"":6.599999904632568,""y"":0.4640021026134491},{""x"":7.099999904632568,""y"":0.0010357667924836278}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[1.4734381347446401, 1.1649805188074196, 4.82958608866421, 0.09500545496710007],""points"":[{""x"":0.10000000149011612,""y"":1.5279096364974976},{""x"":0.6000000238418579,""y"":1.3559974431991577},{""x"":1.100000023841858,""y"":1.5246378183364868},{""x"":1.600000023841858,""y"":1.5567657947540283},{""x"":2.0999999046325684,""y"":1.4114240407943726},{""x"":2.5999999046325684,""y"":1.4045010805130005},{""x"":3.0999999046325684,""y"":1.4769829511642456},{""x"":3.5999999046325684,""y"":1.4875500202178955},{""x"":4.099999904632568,""y"":1.2991987466812134},{""x"":4.599999904632568,""y"":0.922961413860321},{""x"":5.099999904632568,""y"":0.6520044803619385},{""x"":5.599999904632568,""y"":0.15350978076457977},{""x"":6.099999904632568,""y"":0.1078903079032898},{""x"":6.599999904632568,""y"":0.17276449501514435},{""x"":7.099999904632568,""y"":0.14066608250141144}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nCosta Rica,MKSTKEEIQTIKTLLKDSRTAKYHKRLQIVL,CC(C)Cc1ccc(cc1)C(C)C(=O)N2CCCC2C(=O)OCCCc3ccccc3,1480018,36.3309440612793,995084218,4041 SOUTHWESTERN BLVD,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,6,6,2BPW,6,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[2.4833641843311227, -1.8945978742090062, 4.671127708092568, 0.24159861311815153],""points"":[{""x"":0.10000000149011612,""y"":0.0969524160027504},{""x"":0.6000000238418579,""y"":0.028483040630817413},{""x"":1.100000023841858,""y"":0.22087176144123077},{""x"":1.600000023841858,""y"":0.0068915546871721745},{""x"":2.0999999046325684,""y"":0.4305879771709442},{""x"":2.5999999046325684,""y"":0.44774115085601807},{""x"":3.0999999046325684,""y"":0.45346319675445557},{""x"":3.5999999046325684,""y"":0.2370593100786209},{""x"":4.099999904632568,""y"":0.4657953977584839},{""x"":4.599999904632568,""y"":1.155200719833374},{""x"":5.099999904632568,""y"":2.2294070720672607},{""x"":5.599999904632568,""y"":2.4311530590057373},{""x"":6.099999904632568,""y"":2.33846116065979},{""x"":6.599999904632568,""y"":2.608201026916504},{""x"":7.099999904632568,""y"":2.8136143684387207}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[5.224573521642033, 1.4454033924198528, 5.6014197746076535, 0.2823216054197577],""points"":[{""x"":0.10000000149011612,""y"":4.95027494430542},{""x"":0.6000000238418579,""y"":5.1754679679870605},{""x"":1.100000023841858,""y"":5.276752948760986},{""x"":1.600000023841858,""y"":5.589294910430908},{""x"":2.0999999046325684,""y"":5.616994857788086},{""x"":2.5999999046325684,""y"":5.120813846588135},{""x"":3.0999999046325684,""y"":5.340766906738281},{""x"":3.5999999046325684,""y"":4.876471042633057},{""x"":4.099999904632568,""y"":4.94999361038208},{""x"":4.599999904632568,""y"":5.162564754486084},{""x"":5.099999904632568,""y"":4.399557590484619},{""x"":5.599999904632568,""y"":2.7977969646453857},{""x"":6.099999904632568,""y"":1.0229872465133667},{""x"":6.599999904632568,""y"":0.48275601863861084},{""x"":7.099999904632568,""y"":0.10408931970596313}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nCuba,MHAILRYFIRRLFYHIFYKIYSLISKKHQSLPSDVRQF,COc1ccc2c(c1)c(CC(=O)N3CCCC3C(=O)Oc4ccc(C)cc4OC)c(C)n2C(=O)c5ccc(Cl)cc5,1480019,36.33115768432617,995081928,1227 US HIGHWAY 11,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,7,7,1QBS,7,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[3.320838679713925, -1.2421619987316728, 4.831325425225256, 0.3236011098403072],""points"":[{""x"":0.10000000149011612,""y"":0.3727470338344574},{""x"":0.6000000238418579,""y"":0.12365014106035233},{""x"":1.100000023841858,""y"":0.48422467708587646},{""x"":1.600000023841858,""y"":0.2264465093612671},{""x"":2.0999999046325684,""y"":0.16821794211864471},{""x"":2.5999999046325684,""y"":0.3879014551639557},{""x"":3.0999999046325684,""y"":0.5470244884490967},{""x"":3.5999999046325684,""y"":0.3419053554534912},{""x"":4.099999904632568,""y"":0.7655120491981506},{""x"":4.599999904632568,""y"":1.2346516847610474},{""x"":5.099999904632568,""y"":2.453336715698242},{""x"":5.599999904632568,""y"":2.9565491676330566},{""x"":6.099999904632568,""y"":3.335299491882324},{""x"":6.599999904632568,""y"":3.240290880203247},{""x"":7.099999904632568,""y"":3.1107218265533447}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[3.6401853521511094, 1.26211588875013, 5.399028074402744, 0.5089580830068091],""points"":[{""x"":0.10000000149011612,""y"":3.8585598468780518},{""x"":0.6000000238418579,""y"":3.6077206134796143},{""x"":1.100000023841858,""y"":3.855252265930176},{""x"":1.600000023841858,""y"":3.619039297103882},{""x"":2.0999999046325684,""y"":3.839388370513916},{""x"":2.5999999046325684,""y"":3.335283041000366},{""x"":3.0999999046325684,""y"":3.571141481399536},{""x"":3.5999999046325684,""y"":3.4155046939849854},{""x"":4.099999904632568,""y"":3.7316646575927734},{""x"":4.599999904632568,""y"":3.0680155754089355},{""x"":5.099999904632568,""y"":2.891066551208496},{""x"":5.599999904632568,""y"":1.6022753715515137},{""x"":6.099999904632568,""y"":0.7652576565742493},{""x"":6.599999904632568,""y"":0.6875326037406921},{""x"":7.099999904632568,""y"":0.5828871726989746}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nItaly,MSNFHNEHVMQFYRNNLKTKGVFGRQ,CC(C)Cc1ccc(cc1)C(C)C(=O)N2CCCC2C(=O)OCCO[N+](=O)[O-],1480020,36.33115768432617,99502,"168-46 91ST AVE., 2ND FLR",https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,8,8,1ZP8,8,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[2.293592105923809, 1.3781586549141835, 5.1025898038676605, 0.03493851245291291],""points"":[{""x"":0.10000000149011612,""y"":2.1287283897399902},{""x"":0.6000000238418579,""y"":2.267972230911255},{""x"":1.100000023841858,""y"":2.398442506790161},{""x"":1.600000023841858,""y"":2.5130622386932373},{""x"":2.0999999046325684,""y"":2.3255116939544678},{""x"":2.5999999046325684,""y"":2.127340793609619},{""x"":3.0999999046325684,""y"":2.47259783744812},{""x"":3.5999999046325684,""y"":2.131181478500366},{""x"":4.099999904632568,""y"":2.090421438217163},{""x"":4.599999904632568,""y"":2.02299165725708},{""x"":5.099999904632568,""y"":1.1105059385299683},{""x"":5.599999904632568,""y"":0.4494485855102539},{""x"":6.099999904632568,""y"":0.1375635862350464},{""x"":6.599999904632568,""y"":0.036351121962070465},{""x"":7.099999904632568,""y"":0.1619771122932434}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[5.953125499439879, 1.2528620255306528, 5.187637440149802, 0.3110348753260886],""points"":[{""x"":0.10000000149011612,""y"":5.6585283279418945},{""x"":0.6000000238418579,""y"":5.911152362823486},{""x"":1.100000023841858,""y"":5.924920082092285},{""x"":1.600000023841858,""y"":5.8469438552856445},{""x"":2.0999999046325684,""y"":5.929472923278809},{""x"":2.5999999046325684,""y"":6.190037727355957},{""x"":3.0999999046325684,""y"":6.236179828643799},{""x"":3.5999999046325684,""y"":6.141019344329834},{""x"":4.099999904632568,""y"":5.295210838317871},{""x"":4.599999904632568,""y"":5.265801906585693},{""x"":5.099999904632568,""y"":3.3722851276397705},{""x"":5.599999904632568,""y"":1.8299226760864258},{""x"":6.099999904632568,""y"":0.32690900564193726},{""x"":6.599999904632568,""y"":0.6274543404579163},{""x"":7.099999904632568,""y"":0.8441857099533081}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nRwanda,MPNSEPASLLELFNSIATQGELVRSLKAGNASK,CC(C)Cc1ccc(cc1)C(C)C(=O)N2CCCC2C(=O)OCCO,1480021,36.33137130737305,995037247,"168-46 91ST AVE., 2ND FLR",https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,9,9,2BDJ,9,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[3.8209972202654474, 1.3779216716448506, 5.299882228439686, 0.06040645519069608],""points"":[{""x"":0.10000000149011612,""y"":3.7821109294891357},{""x"":0.6000000238418579,""y"":3.542433023452759},{""x"":1.100000023841858,""y"":3.7008674144744873},{""x"":1.600000023841858,""y"":3.717301607131958},{""x"":2.0999999046325684,""y"":4.024452209472656},{""x"":2.5999999046325684,""y"":4.013899326324463},{""x"":3.0999999046325684,""y"":3.945094347000122},{""x"":3.5999999046325684,""y"":3.866621971130371},{""x"":4.099999904632568,""y"":3.7461626529693604},{""x"":4.599999904632568,""y"":3.3454740047454834},{""x"":5.099999904632568,""y"":2.61944317817688},{""x"":5.599999904632568,""y"":0.999405026435852},{""x"":6.099999904632568,""y"":0.46259793639183044},{""x"":6.599999904632568,""y"":0.054134611040353775},{""x"":7.099999904632568,""y"":0.05711187422275543}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[5.6318079657726035, 1.8495493770000595, 5.391793312471116, 0.17060707587348442],""points"":[{""x"":0.10000000149011612,""y"":5.458079814910889},{""x"":0.6000000238418579,""y"":5.554427146911621},{""x"":1.100000023841858,""y"":5.799983024597168},{""x"":1.600000023841858,""y"":5.364140033721924},{""x"":2.0999999046325684,""y"":5.864485740661621},{""x"":2.5999999046325684,""y"":5.4509806632995605},{""x"":3.0999999046325684,""y"":5.702574729919434},{""x"":3.5999999046325684,""y"":5.7314534187316895},{""x"":4.099999904632568,""y"":5.5123443603515625},{""x"":4.599999904632568,""y"":5.724395751953125},{""x"":5.099999904632568,""y"":4.354506969451904},{""x"":5.599999904632568,""y"":1.7307666540145874},{""x"":6.099999904632568,""y"":0.6305936574935913},{""x"":6.599999904632568,""y"":0.035183437168598175},{""x"":7.099999904632568,""y"":0.7575169205665588}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nSwitzerland,IRVVGRYLIEVWKAAGMDMDKVLFLWSSDEI,CN1CCC(CC1)Oc2ccc(cc2)C(F)(F)F,1480028,36.33137130737305,99504,92-11 179TH PLACE,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,9,10,1IAN,10,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[1.1190255865097471, 2.3163895161544437, 5.4968866182279195, 0.2035204047289052],""points"":[{""x"":0.10000000149011612,""y"":1.1057683229446411},{""x"":0.6000000238418579,""y"":1.1019697189331055},{""x"":1.100000023841858,""y"":1.0818607807159424},{""x"":1.600000023841858,""y"":1.062997817993164},{""x"":2.0999999046325684,""y"":1.046447515487671},{""x"":2.5999999046325684,""y"":1.1217249631881714},{""x"":3.0999999046325684,""y"":1.2166996002197266},{""x"":3.5999999046325684,""y"":1.215477705001831},{""x"":4.099999904632568,""y"":1.0581893920898438},{""x"":4.599999904632568,""y"":1.1747995615005493},{""x"":5.099999904632568,""y"":1.0181127786636353},{""x"":5.599999904632568,""y"":0.5344523191452026},{""x"":6.099999904632568,""y"":0.2569526433944702},{""x"":6.599999904632568,""y"":0.1912207305431366},{""x"":7.099999904632568,""y"":0.15060538053512573}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[3.1038581025805785, 2.0032224204185245, 5.087602825989163, 0.13277988512492753],""points"":[{""x"":0.10000000149011612,""y"":3.0498509407043457},{""x"":0.6000000238418579,""y"":2.805217742919922},{""x"":1.100000023841858,""y"":3.3415253162384033},{""x"":1.600000023841858,""y"":3.0549843311309814},{""x"":2.0999999046325684,""y"":3.250074863433838},{""x"":2.5999999046325684,""y"":3.0432586669921875},{""x"":3.0999999046325684,""y"":3.265852451324463},{""x"":3.5999999046325684,""y"":2.9475724697113037},{""x"":4.099999904632568,""y"":3.1929898262023926},{""x"":4.599999904632568,""y"":2.7460060119628906},{""x"":5.099999904632568,""y"":1.6175861358642578},{""x"":5.599999904632568,""y"":0.3006608486175537},{""x"":6.099999904632568,""y"":0.3444803059101105},{""x"":6.599999904632568,""y"":0.015537971630692482},{""x"":7.099999904632568,""y"":0.5527358055114746}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\n,,,,,,,,,,,,,,,,,,,,,');o.columns.add(DG.Column.fromList(DG.TYPE.BYTE_ARRAY,"BinaryImage",Array.from(new Uint8Array(11))));var r=function(e,t,n,o){return new(n||(n=Promise))(function(r,s){function a(e){try{l(o.next(e))}catch(e){s(e)}}function i(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,i)}l((o=o.apply(e,t||[])).next())})};const s=3e4,a=108e5,i=console.log.bind(console),l=console.info.bind(console),c=console.warn.bind(console),u=console.error.bind(console),m={},p="Auto Tests",d="Demo",f="Detectors",g="Core",h={};let y;var E;!function(e){e.notNull=function(e,t){if(null==e)throw new Error(`${t??"Value"} not defined`)}}(E||(E={}));class w{constructor(e,t,n){this.catchUnhandled=!0,this.report=!1,this.returnOnFail=!1,void 0!==e&&(this.catchUnhandled=e),void 0!==t&&(this.report=t),void 0!==n&&(this.returnOnFail=n)}}class v{constructor(e,t,n,o){var a;this.category=e,this.name=t,null!=o||(o={}),null!==(a=o.timeout)&&void 0!==a||(o.timeout=s),this.options=o,this.test=()=>r(this,void 0,void 0,function*(){return new Promise((e,t)=>r(this,void 0,void 0,function*(){var o;let r="";try{DG.Test.isInDebug;let e=yield n();try{r=null!==(o=null==e?void 0:e.toString())&&void 0!==o?o:""}catch(e){r="Can't convert test's result to string",console.error(`Can't convert test's result to string in the ${this.category}:${this.name} test`)}}catch(e){t(e)}e(r)}))})}}function _(e,t,n){null==m[y]&&(m[y]={}),null==m[y].tests&&(m[y].tests=[]),m[y].tests.push(new v(y,e,t,n))}function C(e,t=!0,n){if(n=n?`${n}, `:"",e!==t)throw new Error(`${n}Expected "${t}", got "${e}"`)}function b(e,t,n){var o;y=e,t(),m[y]&&(m[y].clear=null===(o=null==n?void 0:n.clear)||void 0===o||o,m[y].timeout=null==n?void 0:n.timeout,m[y].benchmarks=null==n?void 0:n.benchmarks,m[y].stressTests=null==n?void 0:n.stressTests,m[y].owner=null==n?void 0:n.owner)}function T(e,t){return e.replace(new RegExp(t.name,"gi"),t.nqName)}function P(e,t){var n,i,l,c,u,y,E,w,_,b;return r(this,void 0,void 0,function*(){const P=e.id;if(h[P])return;const S=t?t.tests:m;if("DevTools"===e.name||t&&"DevTools"===t._package.name)for(const e of window.dartTests){const t=e.name.split(/\s*\|\s*!/g);let o=null!==(n=t.pop())&&void 0!==n?n:e.name,r=t.length?g+": "+t.join(": "):g,a=o.split(" | ");o=a[a.length-1],a.unshift(r),a.pop(),r=a.join(": "),void 0===S[r]&&(S[r]={tests:[],clear:!0}),S[r].tests.push(new v(r,o,e.test,{isAggregated:!1,timeout:null!==(l=null===(i=e.options)||void 0===i?void 0:i.timeout)&&void 0!==l?l:s,skipReason:null===(c=e.options)||void 0===c?void 0:c.skipReason,owner:null===(u=e.options)||void 0===u?void 0:u.owner,benchmark:null!==(E=null===(y=e.options)||void 0===y?void 0:y.benchmark)&&void 0!==E&&E}))}const N=[],A=[],x=[],L=yield grok.dapi.functions.filter(`package.id = "${P}"`).list(),F=new RegExp(/skip:\s*([^,\s]+)|wait:\s*(\d+)|cat:\s*([^,\s]+)|timeout:\s*(\d+)/g);for(const t of L){const n=t.options.test,i=t.options.demoPath;if(n&&Array.isArray(n)&&n.length)for(let e=0;e<n.length;e++){const o=n[e].matchAll(F),i={};Array.from(o).forEach(e=>{e[0].startsWith("skip")?i.skip=e[1]:e[0].startsWith("wait")?i.wait=parseInt(e[2]):e[0].startsWith("cat")?i.cat=e[3]:e[0].startsWith("timeout")&&(i.timeout=parseInt(e[4]))});const l=new v(null!==(w=i.cat)&&void 0!==w?w:p,1===n.length?t.name:`${t.name} ${e+1}`,()=>r(this,void 0,void 0,function*(){const o=yield grok.functions.eval(T(n[e],t));if(i.wait&&(yield D(i.wait)),"boolean"==typeof o&&!o)throw`Failed: ${n[e]}, expected true, got ${o}`}),{skipReason:i.skip,timeout:DG.Test.isInBenchmark?null!==(_=i.benchmarkTimeout)&&void 0!==_?_:a:null!==(b=i.timeout)&&void 0!==b?b:s});if(i.cat){const e=i.cat;void 0===S[e]&&(S[e]={tests:[],clear:!0}),S[e].tests||(S[e].tests=[]),S[e].tests.push(l)}else N.push(l)}if(i){const e=t.options.demoWait?parseInt(t.options.demoWait):void 0,n=new v(d,t.friendlyName,()=>r(this,void 0,void 0,function*(){yield D(300),grok.shell.clearLastError(),yield t.apply(),yield D(e||2e3);const n=yield grok.shell.lastError;if(n)throw new Error(n)}),{skipReason:t.options.demoSkip});A.push(n)}if(t.hasTag("semTypeDetector")){let n=o;t.options.testData&&(n=yield grok.data.files.openTable(`System:AppData/${e.nqName}/${t.options.testData}`));const s=new v(f,t.friendlyName,()=>r(this,void 0,void 0,function*(){const o=[];console.log(`System:AppData/${e.nqName}/${t.options.testData}`);for(const e of n.clone().columns){const n=yield t.apply([e]);o.push(n||e.semType)}const r=o.filter(e=>e);C(r.length,1),t.options.testDataColumnName&&C(r[0],t.options.testDataColumnName)}),{skipReason:t.options.skipTest});x.push(s)}}h[P]=!0,N.length>0&&(S[p]={tests:N,clear:!0}),A.length>0&&(S[d]={tests:A,clear:!0}),x.length>0&&(S[f]={tests:x,clear:!1})})}function S(e){var t,n,o;return r(this,void 0,void 0,function*(){const p=(null==e?void 0:e.nodeOptions)?e.nodeOptions.package:grok.functions.getCurrentCall().func.package;if(!p)throw new Error("Can't run tests outside of the package");const d=null===(t=p.packageOwner)||void 0===t?void 0:t.match(/<([^>]*)>/),f=d?d[1]:"";null!=p&&(yield P(p));const g=[];console.log("Running tests..."),console.log(e),null!=e||(e={}),null!==(n=(o=e).testContext)&&void 0!==n||(o.testContext=new w),grok.shell.clearLastError();const h=function(){const e=[];return console.log=(...t)=>{e.push(...t),i(...t)},console.info=(...t)=>{e.push(...t),l(...t)},console.warn=(...t)=>{e.push(...t),c(...t)},console.error=(...t)=>{e.push(...t),u(...t)},e}();yield function(e,t){var n,o,s,a,m,d;return r(this,void 0,void 0,function*(){try{let l=null!=(null==t?void 0:t.skipToCategory),c=!1;for(const[u,h]of Object.entries(e)){if(null===(n=t.exclude)||void 0===n?void 0:n.some(e=>u.startsWith(e)))continue;if(null!=(null==t?void 0:t.category)&&!u.toLowerCase().startsWith(null==t?void 0:t.category.toLowerCase().trim()))continue;if(l)if(c)l=!1;else{if(null==(null==t?void 0:t.skipToCategory)||u.toLowerCase().trim()!==(null==t?void 0:t.skipToCategory.toLowerCase().trim()))continue;c=!0}const e=null===(o=h.tests)||void 0===o?void 0:o.every(e=>{var n;return(null===(n=e.options)||void 0===n?void 0:n.skipReason)||null!=(null==t?void 0:t.test)&&t.test.toLowerCase()!==e.name.toLowerCase()});if(!e){const e=(null!==(s=h.tests)&&void 0!==s?s:[]).filter(e=>{var n;return(null===(n=e.options)||void 0===n?void 0:n.skipReason)||null!=(null==t?void 0:t.test)&&t.test.toLowerCase()!==e.name.toLowerCase()}).length;i(`Package testing: Started {{${u}}}${e>0?` skipped {{${e}}}`:""}`),h.beforeStatus=yield y(h.before,u)}let w,v=null!==(a=h.tests)&&void 0!==a?a:[];t.stressTest&&(v=v.filter(e=>{var t;return null===(t=e.options)||void 0===t?void 0:t.stressTest}),v=x(v)),(null!==(d=null===(m=t.tags)||void 0===m?void 0:m.length)&&void 0!==d?d:0)>0&&(v=v.filter(e=>{var n,o;return null===(o=null===(n=e.options)||void 0===n?void 0:n.tags)||void 0===o?void 0:o.some(e=>{var n;return(null!==(n=null==t?void 0:t.tags)&&void 0!==n?n:[]).includes(e)})})),h.beforeStatus?(w=Array.from(v.map(e=>({date:(new Date).toISOString(),category:u,name:e.name,success:!1,result:"before() failed",ms:0,skipped:!1,logs:"",owner:f,package:p.name,widgetsDifference:0,flaking:DG.Test.isReproducing}))),w.forEach(e=>r(this,void 0,void 0,function*(){return yield grok.shell.reportTest("package",e)}))):w=yield E(h,t,l);const _=w.filter(e=>"skipped"!=e.result);if(e||(h.afterStatus=yield y(h.after,u)),h.afterStatus&&(i(`Package testing: Category after() {{${u}}} failed`),i(`Package testing: Result for {{${u}}} after: ${h.afterStatus}`),_.push({date:(new Date).toISOString(),category:u,name:"after",success:!1,result:h.afterStatus,ms:0,skipped:!1,logs:"",owner:f,package:p.name,widgetsDifference:0,flaking:DG.Test.isReproducing})),h.beforeStatus&&(i(`Package testing: Category before() {{${u}}} failed`),i(`Package testing: Result for {{${u}}} before: ${h.beforeStatus}`),_.push({date:(new Date).toISOString(),category:u,name:"before",success:!1,result:h.beforeStatus,ms:0,skipped:!1,logs:"",owner:f,package:p.name,widgetsDifference:0,flaking:DG.Test.isReproducing})),g.push(..._),t.returnOnFail&&_.some(e=>!e.success&&!e.skipped&&e.name!==t.skipToTest))break}}finally{console.log=i,console.info=l,console.warn=c,console.error=u}if(t.testContext.catchUnhandled&&!DG.Test.isInBenchmark){yield D(1e3);const e=yield grok.shell.lastError;if(null!=e){const t={logs:"",date:(new Date).toISOString(),category:"Unhandled exceptions",name:"Exception",result:null!=e?e:"",success:!e,ms:0,skipped:!1,owner:null!=f?f:"",package:p.name,widgetsDifference:0};i(`Package testing: Unhandled Exception: ${e}`),g.push(Object.assign(Object.assign({},t),{flaking:DG.Test.isReproducing&&!e})),t.package=p.name,yield grok.shell.reportTest("package",t)}}})}(m,e);for(let e of g)e.result=e.result.toString().replace(/"/g,"'"),null!=e.logs&&(e.logs=e.logs.toString().replace(/"/g,"'"));return g;function y(e,t){return r(this,void 0,void 0,function*(){let n;try{void 0!==e&&(yield F(()=>r(this,void 0,void 0,function*(){yield e()}),1e5,`before ${t}: timeout error`))}catch(e){n=yield N(e)}return n})}function E(e,t,n){var o,i,l,c,u,m,d,g,y,E,w,_,C,b,T,P,S,N;return r(this,void 0,void 0,function*(){let r=null!==(o=e.tests)&&void 0!==o?o:[];const x=[],D=v();if(e.clear){let o=n&&null!=t.skipToTest;for(let n=0;n<r.length;n++){r[n].options&&void 0===(null===(i=r[n].options)||void 0===i?void 0:i.benchmark)&&(r[n].options||(r[n].options={}),r[n].options.benchmark=null!==(l=e.benchmarks)&&void 0!==l&&l);let _=r[n];if(t.test&&t.test.toLowerCase()!==_.name.toLowerCase())continue;if(o){if(null==(null==t?void 0:t.skipToTest)||_.name.toLowerCase().trim()!==(null==t?void 0:t.skipToTest.toLowerCase().trim()))continue;o=!1}(null==_?void 0:_.options)&&(_.options.owner=null!==(d=null!==(m=null!==(u=null===(c=r[n].options)||void 0===c?void 0:c.owner)&&void 0!==u?u:null==e?void 0:e.owner)&&void 0!==m?m:f)&&void 0!==d?d:"");let C=yield A(_,null==t?void 0:t.test,h,DG.Test.isInBenchmark?null!==(y=null===(g=r[n].options)||void 0===g?void 0:g.benchmarkTimeout)&&void 0!==y?y:a:null!==(w=null===(E=r[n].options)||void 0===E?void 0:E.timeout)&&void 0!==w?w:s,p.name,t.verbose);if(C&&(x.push(Object.assign(Object.assign({},C),{widgetsDifference:v()-D})),t.returnOnFail&&t.skipToTest!==_.name&&!C.success&&!C.skipped))return x;t.nodeOptions||(grok.shell.closeAll(),DG.Balloon.closeAll())}}else{let o=n&&null!=t.skipToTest;for(let n=0;n<r.length;n++){let s=r[n];if(t.test&&t.test.toLowerCase()!==s.name.toLowerCase())continue;if(o){null!=(null==t?void 0:t.skipToTest)&&s.name.toLowerCase().trim()===(null==t?void 0:t.skipToTest.toLowerCase().trim())&&(o=!1);continue}(null==s?void 0:s.options)&&(s.options.owner=null!==(T=null!==(b=null!==(C=null===(_=r[n].options)||void 0===_?void 0:_.owner)&&void 0!==C?C:null==e?void 0:e.owner)&&void 0!==b?b:f)&&void 0!==T?T:"");let i=yield A(s,null==t?void 0:t.test,h,DG.Test.isInBenchmark?null!==(S=null===(P=r[n].options)||void 0===P?void 0:P.benchmarkTimeout)&&void 0!==S?S:a:null===(N=r[n].options)||void 0===N?void 0:N.timeout,p.name,t.verbose);if(i&&(x.push(Object.assign(Object.assign({},i),{widgetsDifference:v()-D})),t.returnOnFail&&t.skipToTest!==s.name&&!i.success&&!i.skipped))return x}}return x})}function v(){var e;if("undefined"!=typeof process)return 0;let t=-1;try{t=DG.Widget.getAll().length}catch(t){console.warn(null!==(e=t.message)&&void 0!==e?e:t)}return t}})}function N(e){return r(this,void 0,void 0,function*(){return`${e.toString()}\n${e.stack?yield DG.Logger.translateStackTrace(e.stack):""}`})}function A(e,t,n,o,a,l){var c,m,p,d,f,g,h,y,E,w,v,_,C,b;return r(this,void 0,void 0,function*(){let r;n.length=0;const T=null!=t&&e.name.toLowerCase()!==t.toLowerCase();let P=(null===(c=e.options)||void 0===c?void 0:c.skipReason)||T,S=T?"skipped":null===(m=e.options)||void 0===m?void 0:m.skipReason;if(DG.Test.isInBenchmark&&!(null===(p=e.options)||void 0===p?void 0:p.benchmark))return void i(`Package testing: Skipped {{${e.category}}} {{${e.name}}} doesnt available in benchmark mode`);P&&!DG.Test.isInBenchmark&&i(`Package testing: Skipped {{${e.category}}} {{${e.name}}}`),P||i(`Package testing: Started {{${e.category}}} {{${e.name}}}`);const A=Date.now(),x=new Date(A).toISOString();try{if(P)r={name:e.name,owner:null!==(f=null===(d=e.options)||void 0===d?void 0:d.owner)&&void 0!==f?f:"",category:e.category,logs:"",date:x,success:!0,result:S,ms:0,skipped:!0,package:null!=a?a:"",flaking:DG.Test.isReproducing};else{let t=null!=o?o:s;DG.Test.isProfiling&&console.profile(`${e.category}: ${e.name}`),r={name:e.name,owner:null!==(h=null===(g=e.options)||void 0===g?void 0:g.owner)&&void 0!==h?h:"",category:e.category,logs:"",date:x,success:!0,result:null!==(y=(yield F(e.test,t)).toString())&&void 0!==y?y:"OK",ms:0,skipped:!1,package:null!=a?a:"",flaking:DG.Test.isReproducing},DG.Test.isProfiling&&(console.profileEnd(`${e.category}: ${e.name}`),grok.shell.info(`Profiling of ${e.category}: ${e.name} finished \n Please ensure that you have opened DevTools (F12) / Performance panel before test starts.`))}}catch(t){u(t),r={name:e.name,owner:null!==(w=null===(E=e.options)||void 0===E?void 0:E.owner)&&void 0!==w?w:"",category:e.category,logs:"",date:x,success:!1,result:yield N(t),ms:0,skipped:!1,package:null!=a?a:"",flaking:!1}}if((null===(v=e.options)||void 0===v?void 0:v.isAggregated)&&r.result.constructor===DG.DataFrame){const e=r.result.col("success");if(e&&(r.success=e.stats.sum===e.length),!l){const e=r.result;e.columns.remove("stack"),e.rows.removeWhere(e=>e.get("success")),r.result=e}r.result=r.result.toCsv()}if(r.logs=n.join("\n"),r.ms=Date.now()-A,P||i(`Package testing: Finished {{${e.category}}} {{${e.name}}} with {{${r.success?"success":"error"}}} for ${r.ms} ms`),r.success||i(`Package testing: Result for {{${e.category}}} {{${e.name}}}: ${r.result}`),r.category=e.category,r.name=e.name,r.owner=null!==(C=null===(_=e.options)||void 0===_?void 0:_.owner)&&void 0!==C?C:"",!T){let t={success:r.success,result:r.result,ms:r.ms,date:r.date,skipped:r.skipped,category:e.category,name:e.name,logs:r.logs,owner:r.owner,flaking:DG.Test.isReproducing&&r.success,package:r.package};if(r.result.constructor==Object){const e=Object.keys(r.result).reduce((e,t)=>Object.assign(Object.assign({},e),{["result."+t]:r.result[t]}),{});t=Object.assign(Object.assign({},t),e)}t.result instanceof DG.DataFrame&&(t.result=JSON.stringify(null===(b=t.result)||void 0===b?void 0:b.toJson())||""),yield grok.shell.reportTest("package",t)}return r})}function x(e){const t=e.slice();return t.sort(()=>Math.random()-.5),t}function D(e){return r(this,void 0,void 0,function*(){yield new Promise(t=>setTimeout(t,e))})}function L(e,t="Timeout exceeded",n=500,o=50){return r(this,void 0,void 0,function*(){return new Promise((r,s)=>{setTimeout(()=>{clearInterval(a),s(new Error(t))},n);const a=setInterval(()=>{e()&&(clearInterval(a),r(null))},o)})})}function F(e,t,n="EXECUTION TIMEOUT"){return r(this,void 0,void 0,function*(){let o=null;const r=new Promise((e,r)=>{o=setTimeout(()=>{r(n)},t)});try{return yield Promise.race([e(),r])}finally{o&&clearTimeout(o)}})}DG.DataFrame.fromColumns([DG.Column.fromStrings("col",["val1","val2","val3"])])},353(e){e.exports=function(){"use strict";var e=6e4,t=36e5,n="millisecond",o="second",r="minute",s="hour",a="day",i="week",l="month",c="quarter",u="year",m="date",p="Invalid Date",d=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,f=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,g={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(e){var t=["th","st","nd","rd"],n=e%100;return"["+e+(t[(n-20)%10]||t[n]||t[0])+"]"}},h=function(e,t,n){var o=String(e);return!o||o.length>=t?e:""+Array(t+1-o.length).join(n)+e},y={s:h,z:function(e){var t=-e.utcOffset(),n=Math.abs(t),o=Math.floor(n/60),r=n%60;return(t<=0?"+":"-")+h(o,2,"0")+":"+h(r,2,"0")},m:function e(t,n){if(t.date()<n.date())return-e(n,t);var o=12*(n.year()-t.year())+(n.month()-t.month()),r=t.clone().add(o,l),s=n-r<0,a=t.clone().add(o+(s?-1:1),l);return+(-(o+(n-r)/(s?r-a:a-r))||0)},a:function(e){return e<0?Math.ceil(e)||0:Math.floor(e)},p:function(e){return{M:l,y:u,w:i,d:a,D:m,h:s,m:r,s:o,ms:n,Q:c}[e]||String(e||"").toLowerCase().replace(/s$/,"")},u:function(e){return void 0===e}},E="en",w={};w[E]=g;var v="$isDayjsObject",_=function(e){return e instanceof P||!(!e||!e[v])},C=function e(t,n,o){var r;if(!t)return E;if("string"==typeof t){var s=t.toLowerCase();w[s]&&(r=s),n&&(w[s]=n,r=s);var a=t.split("-");if(!r&&a.length>1)return e(a[0])}else{var i=t.name;w[i]=t,r=i}return!o&&r&&(E=r),r||!o&&E},b=function(e,t){if(_(e))return e.clone();var n="object"==typeof t?t:{};return n.date=e,n.args=arguments,new P(n)},T=y;T.l=C,T.i=_,T.w=function(e,t){return b(e,{locale:t.$L,utc:t.$u,x:t.$x,$offset:t.$offset})};var P=function(){function g(e){this.$L=C(e.locale,null,!0),this.parse(e),this.$x=this.$x||e.x||{},this[v]=!0}var h=g.prototype;return h.parse=function(e){this.$d=function(e){var t=e.date,n=e.utc;if(null===t)return new Date(NaN);if(T.u(t))return new Date;if(t instanceof Date)return new Date(t);if("string"==typeof t&&!/Z$/i.test(t)){var o=t.match(d);if(o){var r=o[2]-1||0,s=(o[7]||"0").substring(0,3);return n?new Date(Date.UTC(o[1],r,o[3]||1,o[4]||0,o[5]||0,o[6]||0,s)):new Date(o[1],r,o[3]||1,o[4]||0,o[5]||0,o[6]||0,s)}}return new Date(t)}(e),this.init()},h.init=function(){var e=this.$d;this.$y=e.getFullYear(),this.$M=e.getMonth(),this.$D=e.getDate(),this.$W=e.getDay(),this.$H=e.getHours(),this.$m=e.getMinutes(),this.$s=e.getSeconds(),this.$ms=e.getMilliseconds()},h.$utils=function(){return T},h.isValid=function(){return!(this.$d.toString()===p)},h.isSame=function(e,t){var n=b(e);return this.startOf(t)<=n&&n<=this.endOf(t)},h.isAfter=function(e,t){return b(e)<this.startOf(t)},h.isBefore=function(e,t){return this.endOf(t)<b(e)},h.$g=function(e,t,n){return T.u(e)?this[t]:this.set(n,e)},h.unix=function(){return Math.floor(this.valueOf()/1e3)},h.valueOf=function(){return this.$d.getTime()},h.startOf=function(e,t){var n=this,c=!!T.u(t)||t,p=T.p(e),d=function(e,t){var o=T.w(n.$u?Date.UTC(n.$y,t,e):new Date(n.$y,t,e),n);return c?o:o.endOf(a)},f=function(e,t){return T.w(n.toDate()[e].apply(n.toDate("s"),(c?[0,0,0,0]:[23,59,59,999]).slice(t)),n)},g=this.$W,h=this.$M,y=this.$D,E="set"+(this.$u?"UTC":"");switch(p){case u:return c?d(1,0):d(31,11);case l:return c?d(1,h):d(0,h+1);case i:var w=this.$locale().weekStart||0,v=(g<w?g+7:g)-w;return d(c?y-v:y+(6-v),h);case a:case m:return f(E+"Hours",0);case s:return f(E+"Minutes",1);case r:return f(E+"Seconds",2);case o:return f(E+"Milliseconds",3);default:return this.clone()}},h.endOf=function(e){return this.startOf(e,!1)},h.$set=function(e,t){var i,c=T.p(e),p="set"+(this.$u?"UTC":""),d=(i={},i[a]=p+"Date",i[m]=p+"Date",i[l]=p+"Month",i[u]=p+"FullYear",i[s]=p+"Hours",i[r]=p+"Minutes",i[o]=p+"Seconds",i[n]=p+"Milliseconds",i)[c],f=c===a?this.$D+(t-this.$W):t;if(c===l||c===u){var g=this.clone().set(m,1);g.$d[d](f),g.init(),this.$d=g.set(m,Math.min(this.$D,g.daysInMonth())).$d}else d&&this.$d[d](f);return this.init(),this},h.set=function(e,t){return this.clone().$set(e,t)},h.get=function(e){return this[T.p(e)]()},h.add=function(n,c){var m,p=this;n=Number(n);var d=T.p(c),f=function(e){var t=b(p);return T.w(t.date(t.date()+Math.round(e*n)),p)};if(d===l)return this.set(l,this.$M+n);if(d===u)return this.set(u,this.$y+n);if(d===a)return f(1);if(d===i)return f(7);var g=(m={},m[r]=e,m[s]=t,m[o]=1e3,m)[d]||1,h=this.$d.getTime()+n*g;return T.w(h,this)},h.subtract=function(e,t){return this.add(-1*e,t)},h.format=function(e){var t=this,n=this.$locale();if(!this.isValid())return n.invalidDate||p;var o=e||"YYYY-MM-DDTHH:mm:ssZ",r=T.z(this),s=this.$H,a=this.$m,i=this.$M,l=n.weekdays,c=n.months,u=n.meridiem,m=function(e,n,r,s){return e&&(e[n]||e(t,o))||r[n].slice(0,s)},d=function(e){return T.s(s%12||12,e,"0")},g=u||function(e,t,n){var o=e<12?"AM":"PM";return n?o.toLowerCase():o};return o.replace(f,function(e,o){return o||function(e){switch(e){case"YY":return String(t.$y).slice(-2);case"YYYY":return T.s(t.$y,4,"0");case"M":return i+1;case"MM":return T.s(i+1,2,"0");case"MMM":return m(n.monthsShort,i,c,3);case"MMMM":return m(c,i);case"D":return t.$D;case"DD":return T.s(t.$D,2,"0");case"d":return String(t.$W);case"dd":return m(n.weekdaysMin,t.$W,l,2);case"ddd":return m(n.weekdaysShort,t.$W,l,3);case"dddd":return l[t.$W];case"H":return String(s);case"HH":return T.s(s,2,"0");case"h":return d(1);case"hh":return d(2);case"a":return g(s,a,!0);case"A":return g(s,a,!1);case"m":return String(a);case"mm":return T.s(a,2,"0");case"s":return String(t.$s);case"ss":return T.s(t.$s,2,"0");case"SSS":return T.s(t.$ms,3,"0");case"Z":return r}return null}(e)||r.replace(":","")})},h.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},h.diff=function(n,m,p){var d,f=this,g=T.p(m),h=b(n),y=(h.utcOffset()-this.utcOffset())*e,E=this-h,w=function(){return T.m(f,h)};switch(g){case u:d=w()/12;break;case l:d=w();break;case c:d=w()/3;break;case i:d=(E-y)/6048e5;break;case a:d=(E-y)/864e5;break;case s:d=E/t;break;case r:d=E/e;break;case o:d=E/1e3;break;default:d=E}return p?d:T.a(d)},h.daysInMonth=function(){return this.endOf(l).$D},h.$locale=function(){return w[this.$L]},h.locale=function(e,t){if(!e)return this.$L;var n=this.clone(),o=C(e,t,!0);return o&&(n.$L=o),n},h.clone=function(){return T.w(this.$d,this)},h.toDate=function(){return new Date(this.valueOf())},h.toJSON=function(){return this.isValid()?this.toISOString():null},h.toISOString=function(){return this.$d.toISOString()},h.toString=function(){return this.$d.toUTCString()},g}(),S=P.prototype;return b.prototype=S,[["$ms",n],["$s",o],["$m",r],["$H",s],["$W",a],["$M",l],["$y",u],["$D",m]].forEach(function(e){S[e[1]]=function(t){return this.$g(t,e[0],e[1])}}),b.extend=function(e,t){return e.$i||(e(t,P,b),e.$i=!0),b},b.locale=C,b.isDayjs=_,b.unix=function(e){return b(1e3*e)},b.en=w[E],b.Ls=w,b.p={},b}()},982(e,t,n){var o;!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,o,r,s){for(var a,i,l,c,u,m,p,d,f,g,h,y,E;s>=64;){for(a=n[0],i=n[1],l=n[2],c=n[3],u=n[4],m=n[5],p=n[6],d=n[7],g=0;g<16;g++)h=r+4*g,e[g]=(255&o[h])<<24|(255&o[h+1])<<16|(255&o[h+2])<<8|255&o[h+3];for(g=16;g<64;g++)y=((f=e[g-2])>>>17|f<<15)^(f>>>19|f<<13)^f>>>10,E=((f=e[g-15])>>>7|f<<25)^(f>>>18|f<<14)^f>>>3,e[g]=(y+e[g-7]|0)+(E+e[g-16]|0);for(g=0;g<64;g++)y=(((u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7))+(u&m^~u&p)|0)+(d+(t[g]+e[g]|0)|0)|0,E=((a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10))+(a&i^a&l^i&l)|0,d=p,p=m,m=u,u=c+y|0,c=l,l=i,i=a,a=y+E|0;n[0]+=a,n[1]+=i,n[2]+=l,n[3]+=c,n[4]+=u,n[5]+=m,n[6]+=p,n[7]+=d,r+=64,s-=64}return r}var o=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 o=0;if(this.bytesHashed+=t,this.bufferLength>0){for(;this.bufferLength<64&&t>0;)this.buffer[this.bufferLength++]=e[o++],t--;64===this.bufferLength&&(n(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(t>=64&&(o=n(this.temp,this.state,e,o,t),t%=64);t>0;)this.buffer[this.bufferLength++]=e[o++],t--;return this},t.prototype.finish=function(e){if(!this.finished){var t=this.bytesHashed,o=this.bufferLength,r=t/536870912|0,s=t<<3,a=t%64<56?64:128;this.buffer[o]=128;for(var i=o+1;i<a-8;i++)this.buffer[i]=0;this.buffer[a-8]=r>>>24&255,this.buffer[a-7]=r>>>16&255,this.buffer[a-6]=r>>>8&255,this.buffer[a-5]=r>>>0&255,this.buffer[a-4]=s>>>24&255,this.buffer[a-3]=s>>>16&255,this.buffer[a-2]=s>>>8&255,this.buffer[a-1]=s>>>0&255,n(this.temp,this.state,this.buffer,0,a),this.finished=!0}for(i=0;i<8;i++)e[4*i+0]=this.state[i]>>>24&255,e[4*i+1]=this.state[i]>>>16&255,e[4*i+2]=this.state[i]>>>8&255,e[4*i+3]=this.state[i]>>>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=o;var r=function(){function e(e){this.inner=new o,this.outer=new o,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var t=new Uint8Array(this.blockSize);if(e.length>this.blockSize)(new o).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 o).update(e),n=t.digest();return t.clean(),n}function a(e,t){var n=new r(e).update(t),o=n.digest();return n.clean(),o}function i(e,t,n,o){var r=o[0];if(0===r)throw new Error("hkdf: cannot expand more");t.reset(),r>1&&t.update(e),n&&t.update(n),t.update(o),t.finish(e),o[0]++}e.HMAC=r,e.hash=s,e.default=s,e.hmac=a;var l=new Uint8Array(e.digestLength);e.hkdf=function(e,t,n,o){void 0===t&&(t=l),void 0===o&&(o=32);for(var s=new Uint8Array([1]),c=a(t,e),u=new r(c),m=new Uint8Array(u.digestLength),p=m.length,d=new Uint8Array(o),f=0;f<o;f++)p===m.length&&(i(m,u,n,s),p=0),d[f]=m[p++];return u.clean(),m.fill(0),s.fill(0),d},e.pbkdf2=function(e,t,n,o){for(var s=new r(e),a=s.digestLength,i=new Uint8Array(4),l=new Uint8Array(a),c=new Uint8Array(a),u=new Uint8Array(o),m=0;m*a<o;m++){var p=m+1;i[0]=p>>>24&255,i[1]=p>>>16&255,i[2]=p>>>8&255,i[3]=p>>>0&255,s.reset(),s.update(t),s.update(i),s.finish(c);for(var d=0;d<a;d++)l[d]=c[d];for(d=2;d<=n;d++){s.reset(),s.update(c).finish(c);for(var f=0;f<a;f++)l[f]^=c[f]}for(d=0;d<a&&m*a+d<o;d++)u[m*a+d]=l[d]}for(m=0;m<a;m++)l[m]=c[m]=0;for(m=0;m<4;m++)i[m]=0;return s.clean(),u}}(t);var r=t.default;for(var s in t)r[s]=t[s];"object"==typeof e.exports?e.exports=r:void 0===(o=function(){return r}.call(t,n,t,e))||(e.exports=o)}()},572(e){var t;e.exports=(t=function(e,t){var n=Array.prototype.concat,o=Array.prototype.slice,r=Object.prototype.toString;function s(t,n){var o=t>n?t:n;return e.pow(10,17-~~(e.log(o>0?o:-o)*e.LOG10E))}var a=Array.isArray||function(e){return"[object Array]"===r.call(e)};function i(e){return"[object Function]"===r.call(e)}function l(e){return"number"==typeof e&&e-e===0}function c(){return new c._init(arguments)}function u(){return 0}function m(){return 1}function p(e,t){return e===t?1:0}c.fn=c.prototype,c._init=function(e){if(a(e[0]))if(a(e[0][0])){i(e[1])&&(e[0]=c.map(e[0],e[1]));for(var t=0;t<e[0].length;t++)this[t]=e[0][t];this.length=e[0].length}else this[0]=i(e[1])?c.map(e[0],e[1]):e[0],this.length=1;else if(l(e[0]))this[0]=c.seq.apply(null,e),this.length=1;else{if(e[0]instanceof c)return c(e[0].toArray());this[0]=[],this.length=1}return this},c._init.prototype=c.prototype,c._init.constructor=c,c.utils={calcRdx:s,isArray:a,isFunction:i,isNumber:l,toVector:function(e){return n.apply([],e)}},c._random_fn=e.random,c.setRandom=function(e){if("function"!=typeof e)throw new TypeError("fn is not a function");c._random_fn=e},c.extend=function(e){var t,n;if(1===arguments.length){for(n in e)c[n]=e[n];return this}for(t=1;t<arguments.length;t++)for(n in arguments[t])e[n]=arguments[t][n];return e},c.rows=function(e){return e.length||1},c.cols=function(e){return e[0].length||1},c.dimensions=function(e){return{rows:c.rows(e),cols:c.cols(e)}},c.row=function(e,t){return a(t)?t.map(function(t){return c.row(e,t)}):e[t]},c.rowa=function(e,t){return c.row(e,t)},c.col=function(e,t){if(a(t)){var n=c.arange(e.length).map(function(){return new Array(t.length)});return t.forEach(function(t,o){c.arange(e.length).forEach(function(r){n[r][o]=e[r][t]})}),n}for(var o=new Array(e.length),r=0;r<e.length;r++)o[r]=[e[r][t]];return o},c.cola=function(e,t){return c.col(e,t).map(function(e){return e[0]})},c.diag=function(e){for(var t=c.rows(e),n=new Array(t),o=0;o<t;o++)n[o]=[e[o][o]];return n},c.antidiag=function(e){for(var t=c.rows(e)-1,n=new Array(t),o=0;t>=0;t--,o++)n[o]=[e[o][t]];return n},c.transpose=function(e){var t,n,o,r,s,i=[];for(a(e[0])||(e=[e]),n=e.length,o=e[0].length,s=0;s<o;s++){for(t=new Array(n),r=0;r<n;r++)t[r]=e[r][s];i.push(t)}return 1===i.length?i[0]:i},c.map=function(e,t,n){var o,r,s,i,l;for(a(e[0])||(e=[e]),r=e.length,s=e[0].length,i=n?e:new Array(r),o=0;o<r;o++)for(i[o]||(i[o]=new Array(s)),l=0;l<s;l++)i[o][l]=t(e[o][l],o,l);return 1===i.length?i[0]:i},c.cumreduce=function(e,t,n){var o,r,s,i,l;for(a(e[0])||(e=[e]),r=e.length,s=e[0].length,i=n?e:new Array(r),o=0;o<r;o++)for(i[o]||(i[o]=new Array(s)),s>0&&(i[o][0]=e[o][0]),l=1;l<s;l++)i[o][l]=t(i[o][l-1],e[o][l]);return 1===i.length?i[0]:i},c.alter=function(e,t){return c.map(e,t,!0)},c.create=function(e,t,n){var o,r,s=new Array(e);for(i(t)&&(n=t,t=e),o=0;o<e;o++)for(s[o]=new Array(t),r=0;r<t;r++)s[o][r]=n(o,r);return s},c.zeros=function(e,t){return l(t)||(t=e),c.create(e,t,u)},c.ones=function(e,t){return l(t)||(t=e),c.create(e,t,m)},c.rand=function(e,t){return l(t)||(t=e),c.create(e,t,c._random_fn)},c.identity=function(e,t){return l(t)||(t=e),c.create(e,t,p)},c.symmetric=function(e){var t,n,o=e.length;if(e.length!==e[0].length)return!1;for(t=0;t<o;t++)for(n=0;n<o;n++)if(e[n][t]!==e[t][n])return!1;return!0},c.clear=function(e){return c.alter(e,u)},c.seq=function(e,t,n,o){i(o)||(o=!1);var r,a=[],l=s(e,t),c=(t*l-e*l)/((n-1)*l),u=e;for(r=0;u<=t&&r<n;u=(e*l+c*l*++r)/l)a.push(o?o(u,r):u);return a},c.arange=function(e,n,o){var r,s=[];if(o=o||1,n===t&&(n=e,e=0),e===n||0===o)return[];if(e<n&&o<0)return[];if(e>n&&o>0)return[];if(o>0)for(r=e;r<n;r+=o)s.push(r);else for(r=e;r>n;r+=o)s.push(r);return s},c.slice=function(){function e(e,n,o,r){var s,a=[],i=e.length;if(n===t&&o===t&&r===t)return c.copy(e);if(r=r||1,(n=(n=n||0)>=0?n:i+n)===(o=(o=o||e.length)>=0?o:i+o)||0===r)return[];if(n<o&&r<0)return[];if(n>o&&r>0)return[];if(r>0)for(s=n;s<o;s+=r)a.push(e[s]);else for(s=n;s>o;s+=r)a.push(e[s]);return a}return function(t,n){var o,r;return l((n=n||{}).row)?l(n.col)?t[n.row][n.col]:e(c.rowa(t,n.row),(o=n.col||{}).start,o.end,o.step):l(n.col)?e(c.cola(t,n.col),(r=n.row||{}).start,r.end,r.step):(r=n.row||{},o=n.col||{},e(t,r.start,r.end,r.step).map(function(t){return e(t,o.start,o.end,o.step)}))}}(),c.sliceAssign=function(n,o,r){var s,a;if(l(o.row)){if(l(o.col))return n[o.row][o.col]=r;o.col=o.col||{},o.col.start=o.col.start||0,o.col.end=o.col.end||n[0].length,o.col.step=o.col.step||1,s=c.arange(o.col.start,e.min(n.length,o.col.end),o.col.step);var i=o.row;return s.forEach(function(e,t){n[i][e]=r[t]}),n}if(l(o.col)){o.row=o.row||{},o.row.start=o.row.start||0,o.row.end=o.row.end||n.length,o.row.step=o.row.step||1,a=c.arange(o.row.start,e.min(n[0].length,o.row.end),o.row.step);var u=o.col;return a.forEach(function(e,t){n[e][u]=r[t]}),n}return r[0].length===t&&(r=[r]),o.row.start=o.row.start||0,o.row.end=o.row.end||n.length,o.row.step=o.row.step||1,o.col.start=o.col.start||0,o.col.end=o.col.end||n[0].length,o.col.step=o.col.step||1,a=c.arange(o.row.start,e.min(n.length,o.row.end),o.row.step),s=c.arange(o.col.start,e.min(n[0].length,o.col.end),o.col.step),a.forEach(function(e,t){s.forEach(function(o,s){n[e][o]=r[t][s]})}),n},c.diagonal=function(e){var t=c.zeros(e.length,e.length);return e.forEach(function(e,n){t[n][n]=e}),t},c.copy=function(e){return e.map(function(e){return l(e)?e:e.map(function(e){return e})})};var d=c.prototype;return d.length=0,d.push=Array.prototype.push,d.sort=Array.prototype.sort,d.splice=Array.prototype.splice,d.slice=Array.prototype.slice,d.toArray=function(){return this.length>1?o.call(this):o.call(this)[0]},d.map=function(e,t){return c(c.map(this,e,t))},d.cumreduce=function(e,t){return c(c.cumreduce(this,e,t))},d.alter=function(e){return c.alter(this,e),this},function(e){for(var t=0;t<e.length;t++)(function(e){d[e]=function(t){var n,o=this;return t?(setTimeout(function(){t.call(o,d[e].call(o))}),this):(n=c[e](this),a(n)?c(n):n)}})(e[t])}("transpose clear symmetric rows cols dimensions diag antidiag".split(" ")),function(e){for(var t=0;t<e.length;t++)(function(e){d[e]=function(t,n){var o=this;return n?(setTimeout(function(){n.call(o,d[e].call(o,t))}),this):c(c[e](this,t))}})(e[t])}("row col".split(" ")),function(e){for(var t=0;t<e.length;t++)(function(e){d[e]=function(){return c(c[e].apply(null,arguments))}})(e[t])}("create zeros ones rand identity".split(" ")),c}(Math),function(e,t){var n=e.utils.isFunction;function o(e,t){return e-t}function r(e,n,o){return t.max(n,t.min(e,o))}e.sum=function(e){for(var t=0,n=e.length;--n>=0;)t+=e[n];return t},e.sumsqrd=function(e){for(var t=0,n=e.length;--n>=0;)t+=e[n]*e[n];return t},e.sumsqerr=function(t){for(var n,o=e.mean(t),r=0,s=t.length;--s>=0;)r+=(n=t[s]-o)*n;return r},e.sumrow=function(e){for(var t=0,n=e.length;--n>=0;)t+=e[n];return t},e.product=function(e){for(var t=1,n=e.length;--n>=0;)t*=e[n];return t},e.min=function(e){for(var t=e[0],n=0;++n<e.length;)e[n]<t&&(t=e[n]);return t},e.max=function(e){for(var t=e[0],n=0;++n<e.length;)e[n]>t&&(t=e[n]);return t},e.unique=function(e){for(var t={},n=[],o=0;o<e.length;o++)t[e[o]]||(t[e[o]]=!0,n.push(e[o]));return n},e.mean=function(t){return e.sum(t)/t.length},e.meansqerr=function(t){return e.sumsqerr(t)/t.length},e.geomean=function(n){var o=n.map(t.log),r=e.mean(o);return t.exp(r)},e.median=function(e){var t=e.length,n=e.slice().sort(o);return 1&t?n[t/2|0]:(n[t/2-1]+n[t/2])/2},e.cumsum=function(t){return e.cumreduce(t,function(e,t){return e+t})},e.cumprod=function(t){return e.cumreduce(t,function(e,t){return e*t})},e.diff=function(e){var t,n=[],o=e.length;for(t=1;t<o;t++)n.push(e[t]-e[t-1]);return n},e.rank=function(e){var t,n=[],r={};for(t=0;t<e.length;t++)r[l=e[t]]?r[l]++:(r[l]=1,n.push(l));var s=n.sort(o),a={},i=1;for(t=0;t<s.length;t++){var l,c=r[l=s[t]],u=(i+(i+c-1))/2;a[l]=u,i+=c}return e.map(function(e){return a[e]})},e.mode=function(e){var t,n=e.length,r=e.slice().sort(o),s=1,a=0,i=0,l=[];for(t=0;t<n;t++)r[t]===r[t+1]?s++:(s>a?(l=[r[t]],a=s,i=0):s===a&&(l.push(r[t]),i++),s=1);return 0===i?l[0]:l},e.range=function(t){return e.max(t)-e.min(t)},e.variance=function(t,n){return e.sumsqerr(t)/(t.length-(n?1:0))},e.pooledvariance=function(t){return t.reduce(function(t,n){return t+e.sumsqerr(n)},0)/(t.reduce(function(e,t){return e+t.length},0)-t.length)},e.deviation=function(t){for(var n=e.mean(t),o=t.length,r=new Array(o),s=0;s<o;s++)r[s]=t[s]-n;return r},e.stdev=function(n,o){return t.sqrt(e.variance(n,o))},e.pooledstdev=function(n){return t.sqrt(e.pooledvariance(n))},e.meandev=function(n){for(var o=e.mean(n),r=[],s=n.length-1;s>=0;s--)r.push(t.abs(n[s]-o));return e.mean(r)},e.meddev=function(n){for(var o=e.median(n),r=[],s=n.length-1;s>=0;s--)r.push(t.abs(n[s]-o));return e.median(r)},e.coeffvar=function(t){return e.stdev(t)/e.mean(t)},e.quartiles=function(e){var n=e.length,r=e.slice().sort(o);return[r[t.round(n/4)-1],r[t.round(n/2)-1],r[t.round(3*n/4)-1]]},e.quantiles=function(e,n,s,a){var i,l,c,u,m,p=e.slice().sort(o),d=[n.length],f=e.length;for(void 0===s&&(s=3/8),void 0===a&&(a=3/8),i=0;i<n.length;i++)c=f*(l=n[i])+(s+l*(1-s-a)),u=t.floor(r(c,1,f-1)),m=r(c-u,0,1),d[i]=(1-m)*p[u-1]+m*p[u];return d},e.percentile=function(e,t,n){var r=e.slice().sort(o),s=t*(r.length+(n?1:-1))+(n?0:1),a=parseInt(s),i=s-a;return a+1<r.length?r[a-1]+i*(r[a]-r[a-1]):r[a-1]},e.percentileOfScore=function(e,t,n){var o,r,s=0,a=e.length,i=!1;for("strict"===n&&(i=!0),r=0;r<a;r++)o=e[r],(i&&o<t||!i&&o<=t)&&s++;return s/a},e.histogram=function(n,o){o=o||4;var r,s=e.min(n),a=(e.max(n)-s)/o,i=n.length,l=[];for(r=0;r<o;r++)l[r]=0;for(r=0;r<i;r++)l[t.min(t.floor((n[r]-s)/a),o-1)]+=1;return l},e.covariance=function(t,n){var o,r=e.mean(t),s=e.mean(n),a=t.length,i=new Array(a);for(o=0;o<a;o++)i[o]=(t[o]-r)*(n[o]-s);return e.sum(i)/(a-1)},e.corrcoeff=function(t,n){return e.covariance(t,n)/e.stdev(t,1)/e.stdev(n,1)},e.spearmancoeff=function(t,n){return t=e.rank(t),n=e.rank(n),e.corrcoeff(t,n)},e.stanMoment=function(n,o){for(var r=e.mean(n),s=e.stdev(n),a=n.length,i=0,l=0;l<a;l++)i+=t.pow((n[l]-r)/s,o);return i/n.length},e.skewness=function(t){return e.stanMoment(t,3)},e.kurtosis=function(t){return e.stanMoment(t,4)-3};var s=e.prototype;!function(t){for(var o=0;o<t.length;o++)(function(t){s[t]=function(o,r){var a=[],i=0,l=this;if(n(o)&&(r=o,o=!1),r)return setTimeout(function(){r.call(l,s[t].call(l,o))}),this;if(this.length>1){for(l=!0===o?this:this.transpose();i<l.length;i++)a[i]=e[t](l[i]);return a}return e[t](this[0],o)}})(t[o])}("cumsum cumprod".split(" ")),function(t){for(var o=0;o<t.length;o++)(function(t){s[t]=function(o,r){var a=[],i=0,l=this;if(n(o)&&(r=o,o=!1),r)return setTimeout(function(){r.call(l,s[t].call(l,o))}),this;if(this.length>1){for("sumrow"!==t&&(l=!0===o?this:this.transpose());i<l.length;i++)a[i]=e[t](l[i]);return!0===o?e[t](e.utils.toVector(a)):a}return e[t](this[0],o)}})(t[o])}("sum sumsqrd sumsqerr sumrow product min max unique mean meansqerr geomean median diff rank mode range variance deviation stdev meandev meddev coeffvar quartiles histogram skewness kurtosis".split(" ")),function(t){for(var o=0;o<t.length;o++)(function(t){s[t]=function(){var o,r=[],a=0,i=this,l=Array.prototype.slice.call(arguments);if(n(l[l.length-1])){o=l[l.length-1];var c=l.slice(0,l.length-1);return setTimeout(function(){o.call(i,s[t].apply(i,c))}),this}o=void 0;var u=function(n){return e[t].apply(i,[n].concat(l))};if(this.length>1){for(i=i.transpose();a<i.length;a++)r[a]=u(i[a]);return r}return u(this[0])}})(t[o])}("quantiles percentileOfScore".split(" "))}(t,Math),function(e,t){e.gammaln=function(e){var n,o,r,s=0,a=[76.18009172947146,-86.50532032941678,24.01409824083091,-1.231739572450155,.001208650973866179,-5395239384953e-18],i=1.000000000190015;for(r=(o=n=e)+5.5,r-=(n+.5)*t.log(r);s<6;s++)i+=a[s]/++o;return t.log(2.5066282746310007*i/n)-r},e.loggam=function(e){var n,o,r,s,a,i,l,c=[.08333333333333333,-.002777777777777778,.0007936507936507937,-.0005952380952380952,.0008417508417508418,-.001917526917526918,.00641025641025641,-.02955065359477124,.1796443723688307,-1.3924322169059];if(n=e,l=0,1==e||2==e)return 0;for(e<=7&&(n=e+(l=t.floor(7-e))),o=1/(n*n),r=2*t.PI,a=c[9],i=8;i>=0;i--)a*=o,a+=c[i];if(s=a/n+.5*t.log(r)+(n-.5)*t.log(n)-n,e<=7)for(i=1;i<=l;i++)s-=t.log(n-1),n-=1;return s},e.gammafn=function(e){var n,o,r,s,a=[-1.716185138865495,24.76565080557592,-379.80425647094563,629.3311553128184,866.9662027904133,-31451.272968848367,-36144.413418691176,66456.14382024054],i=[-30.8402300119739,315.35062697960416,-1015.1563674902192,-3107.771671572311,22538.11842098015,4755.846277527881,-134659.9598649693,-115132.2596755535],l=!1,c=0,u=0,m=0,p=e;if(e>171.6243769536076)return 1/0;if(p<=0){if(!(s=p%1+36e-17))return 1/0;l=(1&p?-1:1)*t.PI/t.sin(t.PI*s),p=1-p}for(r=p,o=p<1?p++:(p-=c=(0|p)-1)-1,n=0;n<8;++n)m=(m+a[n])*o,u=u*o+i[n];if(s=m/u+1,r<p)s/=r;else if(r>p)for(n=0;n<c;++n)s*=p,p++;return l&&(s=l/s),s},e.gammap=function(t,n){return e.lowRegGamma(t,n)*e.gammafn(t)},e.lowRegGamma=function(n,o){var r,s=e.gammaln(n),a=n,i=1/n,l=i,c=o+1-n,u=1/1e-30,m=1/c,p=m,d=1,f=-~(8.5*t.log(n>=1?n:1/n)+.4*n+17);if(o<0||n<=0)return NaN;if(o<n+1){for(;d<=f;d++)i+=l*=o/++a;return i*t.exp(-o+n*t.log(o)-s)}for(;d<=f;d++)p*=(m=1/(m=(r=-d*(d-n))*m+(c+=2)))*(u=c+r/u);return 1-p*t.exp(-o+n*t.log(o)-s)},e.factorialln=function(t){return t<0?NaN:e.gammaln(t+1)},e.factorial=function(t){return t<0?NaN:e.gammafn(t+1)},e.combination=function(n,o){return n>170||o>170?t.exp(e.combinationln(n,o)):e.factorial(n)/e.factorial(o)/e.factorial(n-o)},e.combinationln=function(t,n){return e.factorialln(t)-e.factorialln(n)-e.factorialln(t-n)},e.permutation=function(t,n){return e.factorial(t)/e.factorial(t-n)},e.betafn=function(n,o){if(!(n<=0||o<=0))return n+o>170?t.exp(e.betaln(n,o)):e.gammafn(n)*e.gammafn(o)/e.gammafn(n+o)},e.betaln=function(t,n){return e.gammaln(t)+e.gammaln(n)-e.gammaln(t+n)},e.betacf=function(e,n,o){var r,s,a,i,l=1e-30,c=1,u=n+o,m=n+1,p=n-1,d=1,f=1-u*e/m;for(t.abs(f)<l&&(f=l),i=f=1/f;c<=100&&(f=1+(s=c*(o-c)*e/((p+(r=2*c))*(n+r)))*f,t.abs(f)<l&&(f=l),d=1+s/d,t.abs(d)<l&&(d=l),i*=(f=1/f)*d,f=1+(s=-(n+c)*(u+c)*e/((n+r)*(m+r)))*f,t.abs(f)<l&&(f=l),d=1+s/d,t.abs(d)<l&&(d=l),i*=a=(f=1/f)*d,!(t.abs(a-1)<3e-7));c++);return i},e.gammapinv=function(n,o){var r,s,a,i,l,c,u=0,m=o-1,p=e.gammaln(o);if(n>=1)return t.max(100,o+100*t.sqrt(o));if(n<=0)return 0;for(o>1?(l=t.log(m),c=t.exp(m*(l-1)-p),i=n<.5?n:1-n,r=(2.30753+.27061*(s=t.sqrt(-2*t.log(i))))/(1+s*(.99229+.04481*s))-s,n<.5&&(r=-r),r=t.max(.001,o*t.pow(1-1/(9*o)-r/(3*t.sqrt(o)),3))):r=n<(s=1-o*(.253+.12*o))?t.pow(n/s,1/o):1-t.log(1-(n-s)/(1-s));u<12;u++){if(r<=0)return 0;if((r-=s=(a=(e.lowRegGamma(o,r)-n)/(s=o>1?c*t.exp(-(r-m)+m*(t.log(r)-l)):t.exp(-r+m*t.log(r)-p)))/(1-.5*t.min(1,a*((o-1)/r-1))))<=0&&(r=.5*(r+s)),t.abs(s)<1e-8*r)break}return r},e.erf=function(e){var n,o,r,s,a=[-1.3026537197817094,.6419697923564902,.019476473204185836,-.00956151478680863,-.000946595344482036,.000366839497852761,42523324806907e-18,-20278578112534e-18,-1624290004647e-18,130365583558e-17,1.5626441722e-8,-8.5238095915e-8,6.529054439e-9,5.059343495e-9,-9.91364156e-10,-2.27365122e-10,96467911e-18,2394038e-18,-6886027e-18,894487e-18,313092e-18,-112708e-18,381e-18,7106e-18,-1523e-18,-94e-18,121e-18,-28e-18],i=a.length-1,l=!1,c=0,u=0;for(e<0&&(e=-e,l=!0),o=4*(n=2/(2+e))-2;i>0;i--)r=c,c=o*c-u+a[i],u=r;return s=n*t.exp(-e*e+.5*(a[0]+o*c)-u),l?s-1:1-s},e.erfc=function(t){return 1-e.erf(t)},e.erfcinv=function(n){var o,r,s,a,i=0;if(n>=2)return-100;if(n<=0)return 100;for(a=n<1?n:2-n,o=-.70711*((2.30753+.27061*(s=t.sqrt(-2*t.log(a/2))))/(1+s*(.99229+.04481*s))-s);i<2;i++)o+=(r=e.erfc(o)-a)/(1.1283791670955126*t.exp(-o*o)-o*r);return n<1?o:-o},e.ibetainv=function(n,o,r){var s,a,i,l,c,u,m,p,d,f,g=o-1,h=r-1,y=0;if(n<=0)return 0;if(n>=1)return 1;for(o>=1&&r>=1?(i=n<.5?n:1-n,u=(2.30753+.27061*(l=t.sqrt(-2*t.log(i))))/(1+l*(.99229+.04481*l))-l,n<.5&&(u=-u),m=(u*u-3)/6,p=2/(1/(2*o-1)+1/(2*r-1)),d=u*t.sqrt(m+p)/p-(1/(2*r-1)-1/(2*o-1))*(m+5/6-2/(3*p)),u=o/(o+r*t.exp(2*d))):(s=t.log(o/(o+r)),a=t.log(r/(o+r)),u=n<(l=t.exp(o*s)/o)/(d=l+(c=t.exp(r*a)/r))?t.pow(o*d*n,1/o):1-t.pow(r*d*(1-n),1/r)),f=-e.gammaln(o)-e.gammaln(r)+e.gammaln(o+r);y<10;y++){if(0===u||1===u)return u;if((u-=l=(c=(e.ibeta(u,o,r)-n)/(l=t.exp(g*t.log(u)+h*t.log(1-u)+f)))/(1-.5*t.min(1,c*(g/u-h/(1-u)))))<=0&&(u=.5*(u+l)),u>=1&&(u=.5*(u+l+1)),t.abs(l)<1e-8*u&&y>0)break}return u},e.ibeta=function(n,o,r){var s=0===n||1===n?0:t.exp(e.gammaln(o+r)-e.gammaln(o)-e.gammaln(r)+o*t.log(n)+r*t.log(1-n));return!(n<0||n>1)&&(n<(o+1)/(o+r+2)?s*e.betacf(n,o,r)/o:1-s*e.betacf(1-n,r,o)/r)},e.randn=function(n,o){var r,s,a,i,l;if(o||(o=n),n)return e.create(n,o,function(){return e.randn()});do{r=e._random_fn(),s=1.7156*(e._random_fn()-.5),l=(a=r-.449871)*a+(i=t.abs(s)+.386595)*(.196*i-.25472*a)}while(l>.27597&&(l>.27846||s*s>-4*t.log(r)*r*r));return s/r},e.randg=function(n,o,r){var s,a,i,l,c,u,m=n;if(r||(r=o),n||(n=1),o)return(u=e.zeros(o,r)).alter(function(){return e.randg(n)}),u;n<1&&(n+=1),s=n-1/3,a=1/t.sqrt(9*s);do{do{l=1+a*(c=e.randn())}while(l<=0);l*=l*l,i=e._random_fn()}while(i>1-.331*t.pow(c,4)&&t.log(i)>.5*c*c+s*(1-l+t.log(l)));if(n==m)return s*l;do{i=e._random_fn()}while(0===i);return t.pow(i,1/m)*s*l},function(t){for(var n=0;n<t.length;n++)(function(t){e.fn[t]=function(){return e(e.map(this,function(n){return e[t](n)}))}})(t[n])}("gammaln gammafn factorial factorialln".split(" ")),function(t){for(var n=0;n<t.length;n++)(function(t){e.fn[t]=function(){return e(e[t].apply(null,arguments))}})(t[n])}("randn".split(" "))}(t,Math),function(e,t){function n(e,n,o,r){for(var s,a=0,i=1,l=1,c=1,u=0,m=0;t.abs((l-m)/l)>r;)m=l,i=c+(s=-(n+u)*(n+o+u)*e/(n+2*u)/(n+2*u+1))*i,l=(a=l+s*a)+(s=(u+=1)*(o-u)*e/(n+2*u-1)/(n+2*u))*l,a/=c=i+s*c,i/=c,l/=c,c=1;return l/n}function o(n,o,r){var s=[.9815606342467192,.9041172563704749,.7699026741943047,.5873179542866175,.3678314989981802,.1252334085114689],a=[.04717533638651183,.10693932599531843,.16007832854334622,.20316742672306592,.2334925365383548,.24914704581340277],i=.5*n;if(i>=8)return 1;var l,c=2*e.normal.cdf(i,0,1,1,0)-1;c=c>=t.exp(-50/r)?t.pow(c,r):0;for(var u=i,m=(8-i)/(l=n>3?2:3),p=u+m,d=0,f=r-1,g=1;g<=l;g++){for(var h=0,y=.5*(p+u),E=.5*(p-u),w=1;w<=12;w++){var v,_=y+E*(6<w?s[(v=12-w+1)-1]:-s[(v=w)-1]),C=_*_;if(C>60)break;var b=2*e.normal.cdf(_,0,1,1,0)*.5-2*e.normal.cdf(_,n,1,1,0)*.5;b>=t.exp(-30/f)&&(h+=b=a[v-1]*t.exp(-.5*C)*t.pow(b,f))}d+=h*=2*E*r/t.sqrt(2*t.PI),u=p,p+=m}return(c+=d)<=t.exp(-30/o)?0:(c=t.pow(c,o))>=1?1:c}!function(t){for(var n=0;n<t.length;n++)(function(t){e[t]=function e(t,n,o){return this instanceof e?(this._a=t,this._b=n,this._c=o,this):new e(t,n,o)},e.fn[t]=function(n,o,r){var s=e[t](n,o,r);return s.data=this,s},e[t].prototype.sample=function(n){var o=this._a,r=this._b,s=this._c;return n?e.alter(n,function(){return e[t].sample(o,r,s)}):e[t].sample(o,r,s)},function(n){for(var o=0;o<n.length;o++)(function(n){e[t].prototype[n]=function(o){var r=this._a,s=this._b,a=this._c;return o||0===o||(o=this.data),"number"!=typeof o?e.fn.map.call(o,function(o){return e[t][n](o,r,s,a)}):e[t][n](o,r,s,a)}})(n[o])}("pdf cdf inv".split(" ")),function(n){for(var o=0;o<n.length;o++)(function(n){e[t].prototype[n]=function(){return e[t][n](this._a,this._b,this._c)}})(n[o])}("mean median mode variance".split(" "))})(t[n])}("beta centralF cauchy chisquare exponential gamma invgamma kumaraswamy laplace lognormal noncentralt normal pareto studentt weibull uniform binomial negbin hypgeom poisson triangular tukey arcsine".split(" ")),e.extend(e.beta,{pdf:function(n,o,r){return n>1||n<0?0:1==o&&1==r?1:o<512&&r<512?t.pow(n,o-1)*t.pow(1-n,r-1)/e.betafn(o,r):t.exp((o-1)*t.log(n)+(r-1)*t.log(1-n)-e.betaln(o,r))},cdf:function(t,n,o){return t>1||t<0?1*(t>1):e.ibeta(t,n,o)},inv:function(t,n,o){return e.ibetainv(t,n,o)},mean:function(e,t){return e/(e+t)},median:function(t,n){return e.ibetainv(.5,t,n)},mode:function(e,t){return(e-1)/(e+t-2)},sample:function(t,n){var o=e.randg(t);return o/(o+e.randg(n))},variance:function(e,n){return e*n/(t.pow(e+n,2)*(e+n+1))}}),e.extend(e.centralF,{pdf:function(n,o,r){var s;return n<0?0:o<=2?0===n&&o<2?1/0:0===n&&2===o?1:1/e.betafn(o/2,r/2)*t.pow(o/r,o/2)*t.pow(n,o/2-1)*t.pow(1+o/r*n,-(o+r)/2):(s=o*n/(r+n*o),o*(r/(r+n*o))/2*e.binomial.pdf((o-2)/2,(o+r-2)/2,s))},cdf:function(t,n,o){return t<0?0:e.ibeta(n*t/(n*t+o),n/2,o/2)},inv:function(t,n,o){return o/(n*(1/e.ibetainv(t,n/2,o/2)-1))},mean:function(e,t){return t>2?t/(t-2):void 0},mode:function(e,t){return e>2?t*(e-2)/(e*(t+2)):void 0},sample:function(t,n){return 2*e.randg(t/2)/t/(2*e.randg(n/2)/n)},variance:function(e,t){if(!(t<=4))return 2*t*t*(e+t-2)/(e*(t-2)*(t-2)*(t-4))}}),e.extend(e.cauchy,{pdf:function(e,n,o){return o<0?0:o/(t.pow(e-n,2)+t.pow(o,2))/t.PI},cdf:function(e,n,o){return t.atan((e-n)/o)/t.PI+.5},inv:function(e,n,o){return n+o*t.tan(t.PI*(e-.5))},median:function(e){return e},mode:function(e){return e},sample:function(n,o){return e.randn()*t.sqrt(1/(2*e.randg(.5)))*o+n}}),e.extend(e.chisquare,{pdf:function(n,o){return n<0?0:0===n&&2===o?.5:t.exp((o/2-1)*t.log(n)-n/2-o/2*t.log(2)-e.gammaln(o/2))},cdf:function(t,n){return t<0?0:e.lowRegGamma(n/2,t/2)},inv:function(t,n){return 2*e.gammapinv(t,.5*n)},mean:function(e){return e},median:function(e){return e*t.pow(1-2/(9*e),3)},mode:function(e){return e-2>0?e-2:0},sample:function(t){return 2*e.randg(t/2)},variance:function(e){return 2*e}}),e.extend(e.exponential,{pdf:function(e,n){return e<0?0:n*t.exp(-n*e)},cdf:function(e,n){return e<0?0:1-t.exp(-n*e)},inv:function(e,n){return-t.log(1-e)/n},mean:function(e){return 1/e},median:function(e){return 1/e*t.log(2)},mode:function(){return 0},sample:function(n){return-1/n*t.log(e._random_fn())},variance:function(e){return t.pow(e,-2)}}),e.extend(e.gamma,{pdf:function(n,o,r){return n<0?0:0===n&&1===o?1/r:t.exp((o-1)*t.log(n)-n/r-e.gammaln(o)-o*t.log(r))},cdf:function(t,n,o){return t<0?0:e.lowRegGamma(n,t/o)},inv:function(t,n,o){return e.gammapinv(t,n)*o},mean:function(e,t){return e*t},mode:function(e,t){if(e>1)return(e-1)*t},sample:function(t,n){return e.randg(t)*n},variance:function(e,t){return e*t*t}}),e.extend(e.invgamma,{pdf:function(n,o,r){return n<=0?0:t.exp(-(o+1)*t.log(n)-r/n-e.gammaln(o)+o*t.log(r))},cdf:function(t,n,o){return t<=0?0:1-e.lowRegGamma(n,o/t)},inv:function(t,n,o){return o/e.gammapinv(1-t,n)},mean:function(e,t){return e>1?t/(e-1):void 0},mode:function(e,t){return t/(e+1)},sample:function(t,n){return n/e.randg(t)},variance:function(e,t){if(!(e<=2))return t*t/((e-1)*(e-1)*(e-2))}}),e.extend(e.kumaraswamy,{pdf:function(e,n,o){return 0===e&&1===n?o:1===e&&1===o?n:t.exp(t.log(n)+t.log(o)+(n-1)*t.log(e)+(o-1)*t.log(1-t.pow(e,n)))},cdf:function(e,n,o){return e<0?0:e>1?1:1-t.pow(1-t.pow(e,n),o)},inv:function(e,n,o){return t.pow(1-t.pow(1-e,1/o),1/n)},mean:function(t,n){return n*e.gammafn(1+1/t)*e.gammafn(n)/e.gammafn(1+1/t+n)},median:function(e,n){return t.pow(1-t.pow(2,-1/n),1/e)},mode:function(e,n){if(e>=1&&n>=1&&1!==e&&1!==n)return t.pow((e-1)/(e*n-1),1/e)},variance:function(){throw new Error("variance not yet implemented")}}),e.extend(e.lognormal,{pdf:function(e,n,o){return e<=0?0:t.exp(-t.log(e)-.5*t.log(2*t.PI)-t.log(o)-t.pow(t.log(e)-n,2)/(2*o*o))},cdf:function(n,o,r){return n<0?0:.5+.5*e.erf((t.log(n)-o)/t.sqrt(2*r*r))},inv:function(n,o,r){return t.exp(-1.4142135623730951*r*e.erfcinv(2*n)+o)},mean:function(e,n){return t.exp(e+n*n/2)},median:function(e){return t.exp(e)},mode:function(e,n){return t.exp(e-n*n)},sample:function(n,o){return t.exp(e.randn()*o+n)},variance:function(e,n){return(t.exp(n*n)-1)*t.exp(2*e+n*n)}}),e.extend(e.noncentralt,{pdf:function(n,o,r){return t.abs(r)<1e-14?e.studentt.pdf(n,o):t.abs(n)<1e-14?t.exp(e.gammaln((o+1)/2)-r*r/2-.5*t.log(t.PI*o)-e.gammaln(o/2)):o/n*(e.noncentralt.cdf(n*t.sqrt(1+2/o),o+2,r)-e.noncentralt.cdf(n,o,r))},cdf:function(n,o,r){var s=1e-14;if(t.abs(r)<s)return e.studentt.cdf(n,o);var a=!1;n<0&&(a=!0,r=-r);for(var i=e.normal.cdf(-r,0,1),l=s+1,c=l,u=n*n/(n*n+o),m=0,p=t.exp(-r*r/2),d=t.exp(-r*r/2-.5*t.log(2)-e.gammaln(1.5))*r;m<200||c>s||l>s;)c=l,m>0&&(p*=r*r/(2*m),d*=r*r/(2*(m+.5))),i+=.5*(l=p*e.beta.cdf(u,m+.5,o/2)+d*e.beta.cdf(u,m+1,o/2)),m++;return a?1-i:i}}),e.extend(e.normal,{pdf:function(e,n,o){return t.exp(-.5*t.log(2*t.PI)-t.log(o)-t.pow(e-n,2)/(2*o*o))},cdf:function(n,o,r){return.5*(1+e.erf((n-o)/t.sqrt(2*r*r)))},inv:function(t,n,o){return-1.4142135623730951*o*e.erfcinv(2*t)+n},mean:function(e){return e},median:function(e){return e},mode:function(e){return e},sample:function(t,n){return e.randn()*n+t},variance:function(e,t){return t*t}}),e.extend(e.pareto,{pdf:function(e,n,o){return e<n?0:o*t.pow(n,o)/t.pow(e,o+1)},cdf:function(e,n,o){return e<n?0:1-t.pow(n/e,o)},inv:function(e,n,o){return n/t.pow(1-e,1/o)},mean:function(e,n){if(!(n<=1))return n*t.pow(e,n)/(n-1)},median:function(e,n){return e*(n*t.SQRT2)},mode:function(e){return e},variance:function(e,n){if(!(n<=2))return e*e*n/(t.pow(n-1,2)*(n-2))}}),e.extend(e.studentt,{pdf:function(n,o){return o=o>1e100?1e100:o,1/(t.sqrt(o)*e.betafn(.5,o/2))*t.pow(1+n*n/o,-(o+1)/2)},cdf:function(n,o){var r=o/2;return e.ibeta((n+t.sqrt(n*n+o))/(2*t.sqrt(n*n+o)),r,r)},inv:function(n,o){var r=e.ibetainv(2*t.min(n,1-n),.5*o,.5);return r=t.sqrt(o*(1-r)/r),n>.5?r:-r},mean:function(e){return e>1?0:void 0},median:function(){return 0},mode:function(){return 0},sample:function(n){return e.randn()*t.sqrt(n/(2*e.randg(n/2)))},variance:function(e){return e>2?e/(e-2):e>1?1/0:void 0}}),e.extend(e.weibull,{pdf:function(e,n,o){return e<0||n<0||o<0?0:o/n*t.pow(e/n,o-1)*t.exp(-t.pow(e/n,o))},cdf:function(e,n,o){return e<0?0:1-t.exp(-t.pow(e/n,o))},inv:function(e,n,o){return n*t.pow(-t.log(1-e),1/o)},mean:function(t,n){return t*e.gammafn(1+1/n)},median:function(e,n){return e*t.pow(t.log(2),1/n)},mode:function(e,n){return n<=1?0:e*t.pow((n-1)/n,1/n)},sample:function(n,o){return n*t.pow(-t.log(e._random_fn()),1/o)},variance:function(n,o){return n*n*e.gammafn(1+2/o)-t.pow(e.weibull.mean(n,o),2)}}),e.extend(e.uniform,{pdf:function(e,t,n){return e<t||e>n?0:1/(n-t)},cdf:function(e,t,n){return e<t?0:e<n?(e-t)/(n-t):1},inv:function(e,t,n){return t+e*(n-t)},mean:function(e,t){return.5*(e+t)},median:function(t,n){return e.mean(t,n)},mode:function(){throw new Error("mode is not yet implemented")},sample:function(t,n){return t/2+n/2+(n/2-t/2)*(2*e._random_fn()-1)},variance:function(e,n){return t.pow(n-e,2)/12}}),e.extend(e.binomial,{pdf:function(n,o,r){return 0===r||1===r?o*r===n?1:0:e.combination(o,n)*t.pow(r,n)*t.pow(1-r,o-n)},cdf:function(o,r,s){var a,i=1e-10;if(o<0)return 0;if(o>=r)return 1;if(s<0||s>1||r<=0)return NaN;var l=s,c=(o=t.floor(o))+1,u=r-o,m=c+u,p=t.exp(e.gammaln(m)-e.gammaln(u)-e.gammaln(c)+c*t.log(l)+u*t.log(1-l));return a=l<(c+1)/(m+2)?p*n(l,c,u,i):1-p*n(1-l,u,c,i),t.round(1/i*(1-a))/(1/i)}}),e.extend(e.negbin,{pdf:function(n,o,r){return n===n>>>0&&(n<0?0:e.combination(n+o-1,o-1)*t.pow(1-r,n)*t.pow(r,o))},cdf:function(t,n,o){var r=0,s=0;if(t<0)return 0;for(;s<=t;s++)r+=e.negbin.pdf(s,n,o);return r}}),e.extend(e.hypgeom,{pdf:function(n,o,r,s){if(n!=n|0)return!1;if(n<0||n<r-(o-s))return 0;if(n>s||n>r)return 0;if(2*r>o)return 2*s>o?e.hypgeom.pdf(o-r-s+n,o,o-r,o-s):e.hypgeom.pdf(s-n,o,o-r,s);if(2*s>o)return e.hypgeom.pdf(r-n,o,r,o-s);if(r<s)return e.hypgeom.pdf(n,o,s,r);for(var a=1,i=0,l=0;l<n;l++){for(;a>1&&i<s;)a*=1-r/(o-i),i++;a*=(s-l)*(r-l)/((l+1)*(o-r-s+l+1))}for(;i<s;i++)a*=1-r/(o-i);return t.min(1,t.max(0,a))},cdf:function(n,o,r,s){if(n<0||n<r-(o-s))return 0;if(n>=s||n>=r)return 1;if(2*r>o)return 2*s>o?e.hypgeom.cdf(o-r-s+n,o,o-r,o-s):1-e.hypgeom.cdf(s-n-1,o,o-r,s);if(2*s>o)return 1-e.hypgeom.cdf(r-n-1,o,r,o-s);if(r<s)return e.hypgeom.cdf(n,o,s,r);for(var a=1,i=1,l=0,c=0;c<n;c++){for(;a>1&&l<s;){var u=1-r/(o-l);i*=u,a*=u,l++}a+=i*=(s-c)*(r-c)/((c+1)*(o-r-s+c+1))}for(;l<s;l++)a*=1-r/(o-l);return t.min(1,t.max(0,a))}}),e.extend(e.poisson,{pdf:function(n,o){return o<0||n%1!=0||n<0?0:t.pow(o,n)*t.exp(-o)/e.factorial(n)},cdf:function(t,n){var o=[],r=0;if(t<0)return 0;for(;r<=t;r++)o.push(e.poisson.pdf(r,n));return e.sum(o)},mean:function(e){return e},variance:function(e){return e},sampleSmall:function(n){var o=1,r=0,s=t.exp(-n);do{r++,o*=e._random_fn()}while(o>s);return r-1},sampleLarge:function(n){var o,r,s,a,i,l,c,u,m,p,d=n;for(a=t.sqrt(d),i=t.log(d),l=.02483*(c=.931+2.53*a)-.059,u=1.1239+1.1328/(c-3.4),m=.9277-3.6224/(c-2);;){if(r=t.random()-.5,s=t.random(),p=.5-t.abs(r),o=t.floor((2*l/p+c)*r+d+.43),p>=.07&&s<=m)return o;if(!(o<0||p<.013&&s>p)&&t.log(s)+t.log(u)-t.log(l/(p*p)+c)<=o*i-d-e.loggam(o+1))return o}},sample:function(e){return e<10?this.sampleSmall(e):this.sampleLarge(e)}}),e.extend(e.triangular,{pdf:function(e,t,n,o){return n<=t||o<t||o>n?NaN:e<t||e>n?0:e<o?2*(e-t)/((n-t)*(o-t)):e===o?2/(n-t):2*(n-e)/((n-t)*(n-o))},cdf:function(e,n,o,r){return o<=n||r<n||r>o?NaN:e<=n?0:e>=o?1:e<=r?t.pow(e-n,2)/((o-n)*(r-n)):1-t.pow(o-e,2)/((o-n)*(o-r))},inv:function(e,n,o,r){return o<=n||r<n||r>o?NaN:e<=(r-n)/(o-n)?n+(o-n)*t.sqrt(e*((r-n)/(o-n))):n+(o-n)*(1-t.sqrt((1-e)*(1-(r-n)/(o-n))))},mean:function(e,t,n){return(e+t+n)/3},median:function(e,n,o){return o<=(e+n)/2?n-t.sqrt((n-e)*(n-o))/t.sqrt(2):o>(e+n)/2?e+t.sqrt((n-e)*(o-e))/t.sqrt(2):void 0},mode:function(e,t,n){return n},sample:function(n,o,r){var s=e._random_fn();return s<(r-n)/(o-n)?n+t.sqrt(s*(o-n)*(r-n)):o-t.sqrt((1-s)*(o-n)*(o-r))},variance:function(e,t,n){return(e*e+t*t+n*n-e*t-e*n-t*n)/18}}),e.extend(e.arcsine,{pdf:function(e,n,o){return o<=n?NaN:e<=n||e>=o?0:2/t.PI*t.pow(t.pow(o-n,2)-t.pow(2*e-n-o,2),-.5)},cdf:function(e,n,o){return e<n?0:e<o?2/t.PI*t.asin(t.sqrt((e-n)/(o-n))):1},inv:function(e,n,o){return n+(.5-.5*t.cos(t.PI*e))*(o-n)},mean:function(e,t){return t<=e?NaN:(e+t)/2},median:function(e,t){return t<=e?NaN:(e+t)/2},mode:function(){throw new Error("mode is not yet implemented")},sample:function(n,o){return(n+o)/2+(o-n)/2*t.sin(2*t.PI*e.uniform.sample(0,1))},variance:function(e,n){return n<=e?NaN:t.pow(n-e,2)/8}}),e.extend(e.laplace,{pdf:function(e,n,o){return o<=0?0:t.exp(-t.abs(e-n)/o)/(2*o)},cdf:function(e,n,o){return o<=0?0:e<n?.5*t.exp((e-n)/o):1-.5*t.exp(-(e-n)/o)},mean:function(e){return e},median:function(e){return e},mode:function(e){return e},variance:function(e,t){return 2*t*t},sample:function(n,o){var r,s=e._random_fn()-.5;return n-o*((r=s)/t.abs(r))*t.log(1-2*t.abs(s))}}),e.extend(e.tukey,{cdf:function(n,r,s){var a=r,i=[.9894009349916499,.9445750230732326,.8656312023878318,.755404408355003,.6178762444026438,.45801677765722737,.2816035507792589,.09501250983763744],l=[.027152459411754096,.062253523938647894,.09515851168249279,.12462897125553388,.14959598881657674,.16915651939500254,.18260341504492358,.1894506104550685];if(n<=0)return 0;if(s<2||a<2)return NaN;if(!Number.isFinite(n))return 1;if(s>25e3)return o(n,1,a);var c,u=.5*s,m=u*t.log(s)-s*t.log(2)-e.gammaln(u),p=u-1,d=.25*s;c=s<=100?1:s<=800?.5:s<=5e3?.25:.125,m+=t.log(c);for(var f=0,g=1;g<=50;g++){for(var h=0,y=(2*g-1)*c,E=1;E<=16;E++){var w,v;8<E?(w=E-8-1,v=m+p*t.log(y+i[w]*c)-(i[w]*c+y)*d):(w=E-1,v=m+p*t.log(y-i[w]*c)+(i[w]*c-y)*d),v>=-30&&(h+=o(8<E?n*t.sqrt(.5*(i[w]*c+y)):n*t.sqrt(.5*(-i[w]*c+y)),1,a)*l[w]*t.exp(v))}if(g*c>=1&&h<=1e-14)break;f+=h}if(h>1e-14)throw new Error("tukey.cdf failed to converge");return f>1&&(f=1),f},inv:function(n,o,r){if(r<2||o<2)return NaN;if(n<0||n>1)return NaN;if(0===n)return 0;if(1===n)return 1/0;var s,a=function(e,n,o){var r=.5-.5*e,s=t.sqrt(t.log(1/(r*r))),a=s+((((-453642210148e-16*s-.204231210125)*s-.342242088547)*s-1)*s+.322232421088)/((((.0038560700634*s+.10353775285)*s+.531103462366)*s+.588581570495)*s+.099348462606);o<120&&(a+=(a*a*a+a)/o/4);var i=.8832-.2368*a;return o<120&&(i+=-1.214/o+1.208*a/o),a*(i*t.log(n-1)+1.4142)}(n,o,r),i=e.tukey.cdf(a,o,r)-n;s=i>0?t.max(0,a-1):a+1;for(var l,c=e.tukey.cdf(s,o,r)-n,u=1;u<50;u++)if(l=s-c*(s-a)/(c-i),i=c,a=s,l<0&&(l=0,c=-n),c=e.tukey.cdf(l,o,r)-n,s=l,t.abs(s-a)<1e-4)return l;throw new Error("tukey.inv failed to converge")}})}(t,Math),function(e,t){var n,o,r=Array.prototype.push,s=e.utils.isArray;function a(t){return s(t)||t instanceof e}e.extend({add:function(t,n){return a(n)?(a(n[0])||(n=[n]),e.map(t,function(e,t,o){return e+n[t][o]})):e.map(t,function(e){return e+n})},subtract:function(t,n){return a(n)?(a(n[0])||(n=[n]),e.map(t,function(e,t,o){return e-n[t][o]||0})):e.map(t,function(e){return e-n})},divide:function(t,n){return a(n)?(a(n[0])||(n=[n]),e.multiply(t,e.inv(n))):e.map(t,function(e){return e/n})},multiply:function(t,n){var o,r,s,i,l,c,u,m;if(void 0===t.length&&void 0===n.length)return t*n;if(l=t.length,c=t[0].length,u=e.zeros(l,s=a(n)?n[0].length:c),m=0,a(n)){for(;m<s;m++)for(o=0;o<l;o++){for(i=0,r=0;r<c;r++)i+=t[o][r]*n[r][m];u[o][m]=i}return 1===l&&1===m?u[0][0]:u}return e.map(t,function(e){return e*n})},outer:function(t,n){return e.multiply(t.map(function(e){return[e]}),[n])},dot:function(t,n){a(t[0])||(t=[t]),a(n[0])||(n=[n]);for(var o,r,s=1===t[0].length&&1!==t.length?e.transpose(t):t,i=1===n[0].length&&1!==n.length?e.transpose(n):n,l=[],c=0,u=s.length,m=s[0].length;c<u;c++){for(l[c]=[],o=0,r=0;r<m;r++)o+=s[c][r]*i[c][r];l[c]=o}return 1===l.length?l[0]:l},pow:function(n,o){return e.map(n,function(e){return t.pow(e,o)})},exp:function(n){return e.map(n,function(e){return t.exp(e)})},log:function(n){return e.map(n,function(e){return t.log(e)})},abs:function(n){return e.map(n,function(e){return t.abs(e)})},norm:function(e,n){var o=0,r=0;for(isNaN(n)&&(n=2),a(e[0])&&(e=e[0]);r<e.length;r++)o+=t.pow(t.abs(e[r]),n);return t.pow(o,1/n)},angle:function(n,o){return t.acos(e.dot(n,o)/(e.norm(n)*e.norm(o)))},aug:function(e,t){var n,o=[];for(n=0;n<e.length;n++)o.push(e[n].slice());for(n=0;n<o.length;n++)r.apply(o[n],t[n]);return o},inv:function(t){for(var n,o=t.length,r=t[0].length,s=e.identity(o,r),a=e.gauss_jordan(t,s),i=[],l=0;l<o;l++)for(i[l]=[],n=r;n<a[0].length;n++)i[l][n-r]=a[l][n];return i},det:function e(t){if(2===t.length)return t[0][0]*t[1][1]-t[0][1]*t[1][0];for(var n=0,o=0;o<t.length;o++){for(var r=[],s=1;s<t.length;s++){r[s-1]=[];for(var a=0;a<t.length;a++)a<o?r[s-1][a]=t[s][a]:a>o&&(r[s-1][a-1]=t[s][a])}var i=o%2?-1:1;n+=e(r)*t[0][o]*i}return n},gauss_elimination:function(n,o){var r,s,a,i,l=0,c=0,u=n.length,m=n[0].length,p=1,d=0,f=[];for(r=(n=e.aug(n,o))[0].length,l=0;l<u;l++){for(s=n[l][l],c=l,i=l+1;i<m;i++)s<t.abs(n[i][l])&&(s=n[i][l],c=i);if(c!=l)for(i=0;i<r;i++)a=n[l][i],n[l][i]=n[c][i],n[c][i]=a;for(c=l+1;c<u;c++)for(p=n[c][l]/n[l][l],i=l;i<r;i++)n[c][i]=n[c][i]-p*n[l][i]}for(l=u-1;l>=0;l--){for(d=0,c=l+1;c<=u-1;c++)d+=f[c]*n[l][c];f[l]=(n[l][r-1]-d)/n[l][l]}return f},gauss_jordan:function(n,o){var r,s,a,i=e.aug(n,o),l=i.length,c=i[0].length,u=0;for(s=0;s<l;s++){var m=s;for(a=s+1;a<l;a++)t.abs(i[a][s])>t.abs(i[m][s])&&(m=a);var p=i[s];for(i[s]=i[m],i[m]=p,a=s+1;a<l;a++)for(u=i[a][s]/i[s][s],r=s;r<c;r++)i[a][r]-=i[s][r]*u}for(s=l-1;s>=0;s--){for(u=i[s][s],a=0;a<s;a++)for(r=c-1;r>s-1;r--)i[a][r]-=i[s][r]*i[a][s]/u;for(i[s][s]/=u,r=l;r<c;r++)i[s][r]/=u}return i},triaUpSolve:function(t,n){var o,r=t[0].length,s=e.zeros(1,r)[0],a=!1;return null!=n[0].length&&(n=n.map(function(e){return e[0]}),a=!0),e.arange(r-1,-1,-1).forEach(function(a){o=e.arange(a+1,r).map(function(e){return s[e]*t[a][e]}),s[a]=(n[a]-e.sum(o))/t[a][a]}),a?s.map(function(e){return[e]}):s},triaLowSolve:function(t,n){var o,r=t[0].length,s=e.zeros(1,r)[0],a=!1;return null!=n[0].length&&(n=n.map(function(e){return e[0]}),a=!0),e.arange(r).forEach(function(r){o=e.arange(r).map(function(e){return t[r][e]*s[e]}),s[r]=(n[r]-e.sum(o))/t[r][r]}),a?s.map(function(e){return[e]}):s},lu:function(t){var n,o=t.length,r=e.identity(o),s=e.zeros(t.length,t[0].length);return e.arange(o).forEach(function(e){s[0][e]=t[0][e]}),e.arange(1,o).forEach(function(a){e.arange(a).forEach(function(o){n=e.arange(o).map(function(e){return r[a][e]*s[e][o]}),r[a][o]=(t[a][o]-e.sum(n))/s[o][o]}),e.arange(a,o).forEach(function(o){n=e.arange(a).map(function(e){return r[a][e]*s[e][o]}),s[a][o]=t[n.length][o]-e.sum(n)})}),[r,s]},cholesky:function(n){var o,r=n.length,s=e.zeros(n.length,n[0].length);return e.arange(r).forEach(function(a){o=e.arange(a).map(function(e){return t.pow(s[a][e],2)}),s[a][a]=t.sqrt(n[a][a]-e.sum(o)),e.arange(a+1,r).forEach(function(t){o=e.arange(a).map(function(e){return s[a][e]*s[t][e]}),s[t][a]=(n[a][t]-e.sum(o))/s[a][a]})}),s},gauss_jacobi:function(n,o,r,s){for(var a,i,l,c,u=0,m=0,p=n.length,d=[],f=[],g=[];u<p;u++)for(d[u]=[],f[u]=[],g[u]=[],m=0;m<p;m++)u>m?(d[u][m]=n[u][m],f[u][m]=g[u][m]=0):u<m?(f[u][m]=n[u][m],d[u][m]=g[u][m]=0):(g[u][m]=n[u][m],d[u][m]=f[u][m]=0);for(l=e.multiply(e.multiply(e.inv(g),e.add(d,f)),-1),i=e.multiply(e.inv(g),o),a=r,c=e.add(e.multiply(l,r),i),u=2;t.abs(e.norm(e.subtract(c,a)))>s;)a=c,c=e.add(e.multiply(l,a),i),u++;return c},gauss_seidel:function(n,o,r,s){for(var a,i,l,c,u,m=0,p=n.length,d=[],f=[],g=[];m<p;m++)for(d[m]=[],f[m]=[],g[m]=[],a=0;a<p;a++)m>a?(d[m][a]=n[m][a],f[m][a]=g[m][a]=0):m<a?(f[m][a]=n[m][a],d[m][a]=g[m][a]=0):(g[m][a]=n[m][a],d[m][a]=f[m][a]=0);for(c=e.multiply(e.multiply(e.inv(e.add(g,d)),f),-1),l=e.multiply(e.inv(e.add(g,d)),o),i=r,u=e.add(e.multiply(c,r),l),m=2;t.abs(e.norm(e.subtract(u,i)))>s;)i=u,u=e.add(e.multiply(c,i),l),m+=1;return u},SOR:function(n,o,r,s,a){for(var i,l,c,u,m,p=0,d=n.length,f=[],g=[],h=[];p<d;p++)for(f[p]=[],g[p]=[],h[p]=[],i=0;i<d;i++)p>i?(f[p][i]=n[p][i],g[p][i]=h[p][i]=0):p<i?(g[p][i]=n[p][i],f[p][i]=h[p][i]=0):(h[p][i]=n[p][i],f[p][i]=g[p][i]=0);for(u=e.multiply(e.inv(e.add(h,e.multiply(f,a))),e.subtract(e.multiply(h,1-a),e.multiply(g,a))),c=e.multiply(e.multiply(e.inv(e.add(h,e.multiply(f,a))),o),a),l=r,m=e.add(e.multiply(u,r),c),p=2;t.abs(e.norm(e.subtract(m,l)))>s;)l=m,m=e.add(e.multiply(u,l),c),p++;return m},householder:function(n){for(var o,r,s,a,i=n.length,l=n[0].length,c=0,u=[],m=[];c<i-1;c++){for(o=0,a=c+1;a<l;a++)o+=n[a][c]*n[a][c];for(o=(n[c+1][c]>0?-1:1)*t.sqrt(o),r=t.sqrt((o*o-n[c+1][c]*o)/2),(u=e.zeros(i,1))[c+1][0]=(n[c+1][c]-o)/(2*r),s=c+2;s<i;s++)u[s][0]=n[s][c]/(2*r);m=e.subtract(e.identity(i,l),e.multiply(e.multiply(u,e.transpose(u)),2)),n=e.multiply(m,e.multiply(n,m))}return n},QR:(n=e.sum,o=e.arange,function(r){var s,a,i,l=r.length,c=r[0].length,u=e.zeros(c,c);for(r=e.copy(r),a=0;a<c;a++){for(u[a][a]=t.sqrt(n(o(l).map(function(e){return r[e][a]*r[e][a]}))),s=0;s<l;s++)r[s][a]=r[s][a]/u[a][a];for(i=a+1;i<c;i++)for(u[a][i]=n(o(l).map(function(e){return r[e][a]*r[e][i]})),s=0;s<l;s++)r[s][i]=r[s][i]-r[s][a]*u[a][i]}return[r,u]}),lstsq:function(t,n){var o=!1;void 0===n[0].length&&(n=n.map(function(e){return[e]}),o=!0);var r=e.QR(t),s=r[0],a=r[1],i=t[0].length,l=e.slice(s,{col:{end:i}}),c=function(t){var n=(t=e.copy(t)).length,o=e.identity(n);return e.arange(n-1,-1,-1).forEach(function(n){e.sliceAssign(o,{row:n},e.divide(e.slice(o,{row:n}),t[n][n])),e.sliceAssign(t,{row:n},e.divide(e.slice(t,{row:n}),t[n][n])),e.arange(n).forEach(function(r){var s=e.multiply(t[r][n],-1),a=e.slice(t,{row:r}),i=e.multiply(e.slice(t,{row:n}),s);e.sliceAssign(t,{row:r},e.add(a,i));var l=e.slice(o,{row:r}),c=e.multiply(e.slice(o,{row:n}),s);e.sliceAssign(o,{row:r},e.add(l,c))})}),o}(e.slice(a,{row:{end:i}})),u=e.transpose(l);void 0===u[0].length&&(u=[u]);var m=e.multiply(e.multiply(c,u),n);return void 0===m.length&&(m=[[m]]),o?m.map(function(e){return e[0]}):m},jacobi:function(n){for(var o,r,s,a,i,l,c,u=1,m=n.length,p=e.identity(m,m),d=[];1===u;){for(i=n[0][1],s=0,a=1,o=0;o<m;o++)for(r=0;r<m;r++)o!=r&&i<t.abs(n[o][r])&&(i=t.abs(n[o][r]),s=o,a=r);for(l=n[s][s]===n[a][a]?n[s][a]>0?t.PI/4:-t.PI/4:t.atan(2*n[s][a]/(n[s][s]-n[a][a]))/2,(c=e.identity(m,m))[s][s]=t.cos(l),c[s][a]=-t.sin(l),c[a][s]=t.sin(l),c[a][a]=t.cos(l),p=e.multiply(p,c),n=e.multiply(e.multiply(e.inv(c),n),c),u=0,o=1;o<m;o++)for(r=1;r<m;r++)o!=r&&t.abs(n[o][r])>.001&&(u=1)}for(o=0;o<m;o++)d.push(n[o][o]);return[p,d]},rungekutta:function(e,t,n,o,r,s){var a,i,l;if(2===s)for(;o<=n;)r+=((a=t*e(o,r))+(i=t*e(o+t,r+a)))/2,o+=t;if(4===s)for(;o<=n;)r+=((a=t*e(o,r))+2*(i=t*e(o+t/2,r+a/2))+2*(l=t*e(o+t/2,r+i/2))+t*e(o+t,r+l))/6,o+=t;return r},romberg:function(e,n,o,r){for(var s,a,i,l,c,u=0,m=(o-n)/2,p=[],d=[],f=[];u<r/2;){for(c=e(n),i=n,l=0;i<=o;i+=m,l++)p[l]=i;for(s=p.length,i=1;i<s-1;i++)c+=(i%2!=0?4:2)*e(p[i]);c=m/3*(c+e(o)),f[u]=c,m/=2,u++}for(a=f.length,s=1;1!==a;){for(i=0;i<a-1;i++)d[i]=(t.pow(4,s)*f[i+1]-f[i])/(t.pow(4,s)-1);a=d.length,f=d,d=[],s++}return f},richardson:function(e,n,o,r){function s(e,t){for(var n,o=0,r=e.length;o<r;o++)e[o]===t&&(n=o);return n}for(var a,i,l,c,u,m=t.abs(o-e[s(e,o)+1]),p=0,d=[],f=[];r>=m;)a=s(e,o+r),i=s(e,o),d[p]=(n[a]-2*n[i]+n[2*i-a])/(r*r),r/=2,p++;for(c=d.length,l=1;1!=c;){for(u=0;u<c-1;u++)f[u]=(t.pow(4,l)*d[u+1]-d[u])/(t.pow(4,l)-1);c=f.length,d=f,f=[],l++}return d},simpson:function(e,t,n,o){for(var r,s=(n-t)/o,a=e(t),i=[],l=t,c=0,u=1;l<=n;l+=s,c++)i[c]=l;for(r=i.length;u<r-1;u++)a+=(u%2!=0?4:2)*e(i[u]);return s/3*(a+e(n))},hermite:function(e,t,n,o){for(var r,s=e.length,a=0,i=0,l=[],c=[],u=[],m=[];i<s;i++){for(l[i]=1,r=0;r<s;r++)i!=r&&(l[i]*=(o-e[r])/(e[i]-e[r]));for(c[i]=0,r=0;r<s;r++)i!=r&&(c[i]+=1/(e[i]-e[r]));u[i]=(1-2*(o-e[i])*c[i])*(l[i]*l[i]),m[i]=(o-e[i])*(l[i]*l[i]),a+=u[i]*t[i]+m[i]*n[i]}return a},lagrange:function(e,t,n){for(var o,r,s=0,a=0,i=e.length;a<i;a++){for(r=t[a],o=0;o<i;o++)a!=o&&(r*=(n-e[o])/(e[a]-e[o]));s+=r}return s},cubic_spline:function(t,n,o){for(var r,s,a=t.length,i=0,l=[],c=[],u=[],m=[],p=[],d=[];i<a-1;i++)m[i]=t[i+1]-t[i];for(u[0]=0,i=1;i<a-1;i++)u[i]=3/m[i]*(n[i+1]-n[i])-3/m[i-1]*(n[i]-n[i-1]);for(i=1;i<a-1;i++)l[i]=[],c[i]=[],l[i][i-1]=m[i-1],l[i][i]=2*(m[i-1]+m[i]),l[i][i+1]=m[i],c[i][0]=u[i];for(s=e.multiply(e.inv(l),c),r=0;r<a-1;r++)p[r]=(n[r+1]-n[r])/m[r]-m[r]*(s[r+1][0]+2*s[r][0])/3,d[r]=(s[r+1][0]-s[r][0])/(3*m[r]);for(r=0;r<a&&!(t[r]>o);r++);return n[r-=1]+(o-t[r])*p[r]+e.sq(o-t[r])*s[r]+(o-t[r])*e.sq(o-t[r])*d[r]},gauss_quadrature:function(){throw new Error("gauss_quadrature not yet implemented")},PCA:function(t){var n,o,r,s,a,i=t.length,l=t[0].length,c=0,u=[],m=[],p=[],d=[],f=[],g=[],h=[];for(c=0;c<i;c++)u[c]=e.sum(t[c])/l;for(c=0;c<l;c++)for(f[c]=[],n=0;n<i;n++)f[c][n]=t[n][c]-u[n];for(f=e.transpose(f),c=0;c<i;c++)for(g[c]=[],n=0;n<i;n++)g[c][n]=e.dot([f[c]],[f[n]])/(l-1);for(a=(r=e.jacobi(g))[0],m=r[1],h=e.transpose(a),c=0;c<m.length;c++)for(n=c;n<m.length;n++)m[c]<m[n]&&(o=m[c],m[c]=m[n],m[n]=o,p=h[c],h[c]=h[n],h[n]=p);for(s=e.transpose(f),c=0;c<i;c++)for(d[c]=[],n=0;n<s.length;n++)d[c][n]=e.dot([h[c]],[s[n]]);return[t,m,h,d]}}),function(t){for(var n=0;n<t.length;n++)(function(t){e.fn[t]=function(n,o){var r=this;return o?(setTimeout(function(){o.call(r,e.fn[t].call(r,n))},15),this):"number"==typeof e[t](this,n)?e[t](this,n):e(e[t](this,n))}})(t[n])}("add divide multiply subtract dot pow exp log abs norm angle".split(" "))}(t,Math),function(e,t){var n=[].slice,o=e.utils.isNumber,r=e.utils.isArray;function s(e,n,o,r){if(e>1||o>1||e<=0||o<=0)throw new Error("Proportions should be greater than 0 and less than 1");var s=(e*n+o*r)/(n+r);return(e-o)/t.sqrt(s*(1-s)*(1/n+1/r))}e.extend({zscore:function(){var t=n.call(arguments);return o(t[1])?(t[0]-t[1])/t[2]:(t[0]-e.mean(t[1]))/e.stdev(t[1],t[2])},ztest:function(){var o,s=n.call(arguments);return r(s[1])?(o=e.zscore(s[0],s[1],s[3]),1===s[2]?e.normal.cdf(-t.abs(o),0,1):2*e.normal.cdf(-t.abs(o),0,1)):s.length>2?(o=e.zscore(s[0],s[1],s[2]),1===s[3]?e.normal.cdf(-t.abs(o),0,1):2*e.normal.cdf(-t.abs(o),0,1)):(o=s[0],1===s[1]?e.normal.cdf(-t.abs(o),0,1):2*e.normal.cdf(-t.abs(o),0,1))}}),e.extend(e.fn,{zscore:function(e,t){return(e-this.mean())/this.stdev(t)},ztest:function(n,o,r){var s=t.abs(this.zscore(n,r));return 1===o?e.normal.cdf(-s,0,1):2*e.normal.cdf(-s,0,1)}}),e.extend({tscore:function(){var o=n.call(arguments);return 4===o.length?(o[0]-o[1])/(o[2]/t.sqrt(o[3])):(o[0]-e.mean(o[1]))/(e.stdev(o[1],!0)/t.sqrt(o[1].length))},ttest:function(){var r,s=n.call(arguments);return 5===s.length?(r=t.abs(e.tscore(s[0],s[1],s[2],s[3])),1===s[4]?e.studentt.cdf(-r,s[3]-1):2*e.studentt.cdf(-r,s[3]-1)):o(s[1])?(r=t.abs(s[0]),1==s[2]?e.studentt.cdf(-r,s[1]-1):2*e.studentt.cdf(-r,s[1]-1)):(r=t.abs(e.tscore(s[0],s[1])),1==s[2]?e.studentt.cdf(-r,s[1].length-1):2*e.studentt.cdf(-r,s[1].length-1))}}),e.extend(e.fn,{tscore:function(e){return(e-this.mean())/(this.stdev(!0)/t.sqrt(this.cols()))},ttest:function(n,o){return 1===o?1-e.studentt.cdf(t.abs(this.tscore(n)),this.cols()-1):2*e.studentt.cdf(-t.abs(this.tscore(n)),this.cols()-1)}}),e.extend({anovafscore:function(){var o,r,s,a,i,l,c,u,m=n.call(arguments);if(1===m.length){for(i=new Array(m[0].length),c=0;c<m[0].length;c++)i[c]=m[0][c];m=i}for(r=new Array,c=0;c<m.length;c++)r=r.concat(m[c]);for(s=e.mean(r),o=0,c=0;c<m.length;c++)o+=m[c].length*t.pow(e.mean(m[c])-s,2);for(o/=m.length-1,l=0,c=0;c<m.length;c++)for(a=e.mean(m[c]),u=0;u<m[c].length;u++)l+=t.pow(m[c][u]-a,2);return o/(l/(r.length-m.length))},anovaftest:function(){var t,r,s,a,i=n.call(arguments);if(o(i[0]))return 1-e.centralF.cdf(i[0],i[1],i[2]);var l=e.anovafscore(i);for(t=i.length-1,s=0,a=0;a<i.length;a++)s+=i[a].length;return r=s-t-1,1-e.centralF.cdf(l,t,r)},ftest:function(t,n,o){return 1-e.centralF.cdf(t,n,o)}}),e.extend(e.fn,{anovafscore:function(){return e.anovafscore(this.toArray())},anovaftes:function(){var t,n=0;for(t=0;t<this.length;t++)n+=this[t].length;return e.ftest(this.anovafscore(),this.length-1,n-this.length)}}),e.extend({qscore:function(){var r,s,a,i,l,c=n.call(arguments);return o(c[0])?(r=c[0],s=c[1],a=c[2],i=c[3],l=c[4]):(r=e.mean(c[0]),s=e.mean(c[1]),a=c[0].length,i=c[1].length,l=c[2]),t.abs(r-s)/(l*t.sqrt((1/a+1/i)/2))},qtest:function(){var t,o=n.call(arguments);3===o.length?(t=o[0],o=o.slice(1)):7===o.length?(t=e.qscore(o[0],o[1],o[2],o[3],o[4]),o=o.slice(5)):(t=e.qscore(o[0],o[1],o[2]),o=o.slice(3));var r=o[0],s=o[1];return 1-e.tukey.cdf(t,s,r-s)},tukeyhsd:function(t){for(var n=e.pooledstdev(t),o=t.map(function(t){return e.mean(t)}),r=t.reduce(function(e,t){return e+t.length},0),s=[],a=0;a<t.length;++a)for(var i=a+1;i<t.length;++i){var l=e.qtest(o[a],o[i],t[a].length,t[i].length,n,r,t.length);s.push([[a,i],l])}return s}}),e.extend({normalci:function(){var o,r=n.call(arguments),s=new Array(2);return o=4===r.length?t.abs(e.normal.inv(r[1]/2,0,1)*r[2]/t.sqrt(r[3])):t.abs(e.normal.inv(r[1]/2,0,1)*e.stdev(r[2])/t.sqrt(r[2].length)),s[0]=r[0]-o,s[1]=r[0]+o,s},tci:function(){var o,r=n.call(arguments),s=new Array(2);return o=4===r.length?t.abs(e.studentt.inv(r[1]/2,r[3]-1)*r[2]/t.sqrt(r[3])):t.abs(e.studentt.inv(r[1]/2,r[2].length-1)*e.stdev(r[2],!0)/t.sqrt(r[2].length)),s[0]=r[0]-o,s[1]=r[0]+o,s},significant:function(e,t){return e<t}}),e.extend(e.fn,{normalci:function(t,n){return e.normalci(t,n,this.toArray())},tci:function(t,n){return e.tci(t,n,this.toArray())}}),e.extend(e.fn,{oneSidedDifferenceOfProportions:function(t,n,o,r){var a=s(t,n,o,r);return e.ztest(a,1)},twoSidedDifferenceOfProportions:function(t,n,o,r){var a=s(t,n,o,r);return e.ztest(a,2)}})}(t,Math),t.models=function(){function e(e,n){var o=e.length,r=n[0].length-1,s=o-r-1,a=t.lstsq(n,e),i=t.multiply(n,a.map(function(e){return[e]})).map(function(e){return e[0]}),l=t.subtract(e,i),c=t.mean(e),u=t.sum(i.map(function(e){return Math.pow(e-c,2)})),m=t.sum(e.map(function(e,t){return Math.pow(e-i[t],2)})),p=u+m;return{exog:n,endog:e,nobs:o,df_model:r,df_resid:s,coef:a,predict:i,resid:l,ybar:c,SST:p,SSE:u,SSR:m,R2:u/p}}function n(n){var o,r,s=(o=n.exog,r=o[0].length,t.arange(r).map(function(n){var s=t.arange(r).filter(function(e){return e!==n});return e(t.col(o,n).map(function(e){return e[0]}),t.col(o,s))})),a=Math.sqrt(n.SSR/n.df_resid),i=s.map(function(e){var t=e.SST,n=e.R2;return a/Math.sqrt(t*(1-n))}),l=n.coef.map(function(e,t){return(e-0)/i[t]}),c=l.map(function(e){var o=t.studentt.cdf(e,n.df_resid);return 2*(o>.5?1-o:o)}),u=t.studentt.inv(.975,n.df_resid),m=n.coef.map(function(e,t){var n=u*i[t];return[e-n,e+n]});return{se:i,t:l,p:c,sigmaHat:a,interval95:m}}return{ols:function(o,r){var s=e(o,r),a=n(s),i=function(e){var n,o,r,s=e.R2/e.df_model/((1-e.R2)/e.df_resid);return{F_statistic:s,pvalue:1-(n=s,o=e.df_model,r=e.df_resid,t.beta.cdf(n/(r/o+n),o/2,r/2))}}(s),l=1-(1-s.R2)*((s.nobs-1)/s.df_resid);return s.t=a,s.f=i,s.adjust_R2=l,s}}}(),t.extend({buildxmatrix:function(){for(var e=new Array(arguments.length),n=0;n<arguments.length;n++){e[n]=[1].concat(arguments[n])}return t(e)},builddxmatrix:function(){for(var e=new Array(arguments[0].length),n=0;n<arguments[0].length;n++){e[n]=[1].concat(arguments[0][n])}return t(e)},buildjxmatrix:function(e){for(var n=new Array(e.length),o=0;o<e.length;o++)n[o]=e[o];return t.builddxmatrix(n)},buildymatrix:function(e){return t(e).transpose()},buildjymatrix:function(e){return e.transpose()},matrixmult:function(e,n){var o,r,s,a,i;if(e.cols()==n.rows()){if(n.rows()>1){for(a=[],o=0;o<e.rows();o++)for(a[o]=[],r=0;r<n.cols();r++){for(i=0,s=0;s<e.cols();s++)i+=e.toArray()[o][s]*n.toArray()[s][r];a[o][r]=i}return t(a)}for(a=[],o=0;o<e.rows();o++)for(a[o]=[],r=0;r<n.cols();r++){for(i=0,s=0;s<e.cols();s++)i+=e.toArray()[o][s]*n.toArray()[r];a[o][r]=i}return t(a)}},regress:function(e,n){var o=t.xtranspxinv(e),r=e.transpose(),s=t.matrixmult(t(o),r);return t.matrixmult(s,n)},regresst:function(e,n,o){var r=t.regress(e,n),s={anova:{}},a=t.jMatYBar(e,r);s.yBar=a;var i=n.mean();s.anova.residuals=t.residuals(n,a),s.anova.ssr=t.ssr(a,i),s.anova.msr=s.anova.ssr/(e[0].length-1),s.anova.sse=t.sse(n,a),s.anova.mse=s.anova.sse/(n.length-(e[0].length-1)-1),s.anova.sst=t.sst(n,i),s.anova.mst=s.anova.sst/(n.length-1),s.anova.r2=1-s.anova.sse/s.anova.sst,s.anova.r2<0&&(s.anova.r2=0),s.anova.fratio=s.anova.msr/s.anova.mse,s.anova.pvalue=t.anovaftest(s.anova.fratio,e[0].length-1,n.length-(e[0].length-1)-1),s.anova.rmse=Math.sqrt(s.anova.mse),s.anova.r2adj=1-s.anova.mse/s.anova.mst,s.anova.r2adj<0&&(s.anova.r2adj=0),s.stats=new Array(e[0].length);for(var l,c,u,m=t.xtranspxinv(e),p=0;p<r.length;p++)l=Math.sqrt(s.anova.mse*Math.abs(m[p][p])),c=Math.abs(r[p]/l),u=t.ttest(c,n.length-e[0].length-1,o),s.stats[p]=[r[p],l,c,u];return s.regress=r,s},xtranspx:function(e){return t.matrixmult(e.transpose(),e)},xtranspxinv:function(e){var n=t.matrixmult(e.transpose(),e);return t.inv(n)},jMatYBar:function(e,n){var o=t.matrixmult(e,n);return new t(o)},residuals:function(e,n){return t.matrixsubtract(e,n)},ssr:function(e,t){for(var n=0,o=0;o<e.length;o++)n+=Math.pow(e[o]-t,2);return n},sse:function(e,t){for(var n=0,o=0;o<e.length;o++)n+=Math.pow(e[o]-t[o],2);return n},sst:function(e,t){for(var n=0,o=0;o<e.length;o++)n+=Math.pow(e[o]-t,2);return n},matrixsubtract:function(e,n){for(var o=new Array(e.length),r=0;r<e.length;r++){o[r]=new Array(e[r].length);for(var s=0;s<e[r].length;s++)o[r][s]=e[r][s]-n[r][s]}return t(o)}}),t.jStat=t,t)},829(e,t,n){"use strict";n.d(t,{pd:()=>y,zV:()=>w,RJ:()=>p,ps:()=>g,B9:()=>v});var o,r=n(328),s=n(389),a=n(82),i=n(572);function l(e,t,n=!1,o=!1){if(e.length<=1||t.length<=1)throw new Error(`StatisticsError: Wrong sample size; expected at least 2, got ${Math.min(e.length,t.length)})`);const r=i.mean(e),s=i.mean(t),a=i.variance(e),l=i.variance(t),c=e.length,u=t.length;let m,p,d;if(n){const e=a/c,t=l/u,n=(r-s)/Math.sqrt(e+t);p=i.normal.pdf(n,0,1),m=1-p,d=2*(p<m?p:m)}else if(o){const e=c+u-2,t=(a*(c-1)+l*(u-1))/e,n=Math.sqrt(c*u/(c+u))*(r-s)/t;m=1-i.studentt.cdf(n,e),p=i.studentt.cdf(n,e),d=2*(p<m?p:m)}else{const e=a/c,t=l/u,n=(r-s)/Math.sqrt(e+t),o=Math.pow(e+t,2)/(Math.pow(e,2)/(c-1)+Math.pow(t,2)/(u-1));p=i.studentt.cdf(n,o),m=1-p,d=2*(p<m?p:m)}return{"p-value":d,"Mean difference":r-s,"p-value more":m,"p-value less":p}}!function(e){e.indexesOf=function(e,t){const n=[];for(let o=0;o<e.length;o++)t(e[o])&&n.push(o);return n},e.genRange=function(e,t,n=!1){const o=t-e+(n?0:1),r=new Int32Array(o);for(let t=0;t<o;++t)r[t]=e+t;return r},e.argSort=function(e,t=!1){const n=t?(e,t)=>t[0]-e[0]:(e,t)=>e[0]-t[0];return e.map((e,t)=>[e,t]).sort(n).map(e=>e[1])}}(o||(o={}));const c={"+":(e,t)=>e+t,"-":(e,t)=>e-t,"*":(e,t)=>e*t,"/":(e,t)=>e/t,min:(e,t)=>e<t?e:t,max:(e,t)=>e>t?e:t};var u=n(641),m=n(252);function p(e,t){return"true"===e.getTag("proteomics.de_complete")||(r.shell.warning(t),!1)}function d(e,t,n){const o=[];for(const r of t){const t=e.columns.byName(r);t&&!t.isNone(n)&&o.push(t.get(n))}return o}function f(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t/e.length}function g(e,t,n,r,s,i=u.M5,m=u.Dx){const p=e.rowCount,g=new Float32Array(p),h=new Float32Array(p),y=new Float32Array(p);g.fill(a.FLOAT_NULL),h.fill(a.FLOAT_NULL),y.fill(a.FLOAT_NULL);const E=[],w=[];for(let o=0;o<p;o++){const r=d(e,t,o),s=d(e,n,o);if(r.length<2||s.length<2)continue;g[o]=f(s)-f(r);const a=l(r,s)["p-value"];h[o]=a,E.push(o),w.push(a)}if(w.length>0){const[,e]=function(e,t=.05,n="n",r=!1){const s=e.length;let a,i,l=0;var u,m;r?(i=new Int32Array(s).fill(0).map((e,t)=>t),a=e):(i=function(e){const t=Array.from(e);return Int32Array.from(o.argSort(t))}(e),u=i,m=e,a=Float32Array.from(m).map((e,t)=>m[u[t]]));let p=function(e){const t=e.length;return Float32Array.from(e).map((e,n)=>(n+1)/t)}(a);if(["n","negcorr"].includes(n))l=function(e){let t=0;for(let n=0;n<e;++n)t+=1/(n+1);return t}(s),p=function(e,t,n="*"){return Float32Array.from(e).map((e,o)=>c[n](e,t))}(p,l,"/");else if(!["i","indep","p","poscorr"].includes(n))throw new Error("only indep and negcorr implemented");const d=new Array(s).fill(!1);let f=-1;for(let e=0;e<s;++e)a[e]<=p[e]*t&&(f=e);if(f>=0)for(let e=0;e<f;++e)d[e]=!0;let g=function(e,t,n="*"){return Float32Array.from(e).map((e,o)=>c[n](e,t[o]))}(a,p,"/");g=function(e){const t=e.length,n=Float32Array.from(e);for(let o=0;o<t;++o)n[o]=e.slice(0,o+1).reduce((e,t,n,o)=>c.min(e,t));return n}(g.reverse()).reverse();for(let e=0;e<s;++e)g[e]>1&&(g[e]=1);if(!r){const e=function(e,t){const n=Float32Array.from(e);for(let o=0;o<t.length;++o)n[t[o]]=e[o];return n}(g,i),t=function(e,t){const n=Array.from(e);for(let o=0;o<t.length;++o)n[t[o]]=e[o];return n}(d,i);return[t,e]}return[d,g]}(new Float32Array(w),m,"i");for(let t=0;t<E.length;t++)y[E[t]]=e[t]}const v=e.columns.addNewFloat("log2FC"),_=e.columns.addNewFloat("p-value"),C=e.columns.addNewFloat("adj.p-value");v.init(e=>g[e]),_.init(e=>h[e]),C.init(e=>y[e]),e.columns.addNewBool("significant").init(e=>{const t=y[e],n=g[e];return t!==a.FLOAT_NULL&&n!==a.FLOAT_NULL&&Math.abs(n)>=i&&t<=m}),v.semType=u.iu.LOG2FC,_.semType=u.iu.P_VALUE,C.semType=u.iu.P_VALUE,e.setTag("proteomics.de_complete","true"),e.fireValuesChanged();const b=E.length;return{tested:b,untestable:e.rowCount-b}}function h(e,t,n){const o=[...t,...n],r=[];for(let t=0;t<o.length;t++){const n=e.columns.byName(o[t]).getRawData(),s=new Float32Array(n.length);s.set(n),r.push(a.Column.fromFloat32Array(`s${t+1}`,s))}return a.DataFrame.fromColumns(r)}function y(e,t){const n=e.rowCount,o=t.rowCount,r=t.columns.byName("log2FC").getRawData(),s=t.columns.byName("p.value").getRawData(),i=t.columns.byName("adj.p.value").getRawData(),l=t.columns.byName("significant"),c=t.col("row"),m=new Int32Array(o);if(c){const e=c.getRawData();for(let t=0;t<o;t++)m[t]=(0|e[t])-1}else for(let e=0;e<o;e++)m[e]=e;const p=new Float32Array(n);p.fill(a.FLOAT_NULL);const d=new Float32Array(n);d.fill(a.FLOAT_NULL);const f=new Float32Array(n);f.fill(a.FLOAT_NULL);const g=new Uint8Array(n);let h=0;for(let e=0;e<o;e++){const t=m[e];if(t<0||t>=n)continue;p[t]=r[e],d[t]=s[e],f[t]=i[e];const o=l.get(e);!0!==o&&1!==o&&"1"!==o&&"TRUE"!==o||(g[t]=1,h++)}const y=a.Column.fromFloat32Array("log2FC",p),E=a.Column.fromFloat32Array("p-value",d),w=a.Column.fromFloat32Array("adj.p-value",f);return e.columns.addNewBool("significant").init(e=>1===g[e]),y.semType=u.iu.LOG2FC,E.semType=u.iu.P_VALUE,w.semType=u.iu.P_VALUE,e.columns.add(y),e.columns.add(E),e.columns.add(w),h}async function E(e,t,n,o,s){const a=h(e,t,n),i=y(e,await r.functions.call("Proteomics:LimmaDE",{exprDf:a,nGroup1:t.length,fcThreshold:o,pThreshold:s}));return e.setTag("proteomics.de_complete","true"),e.fireValuesChanged(),i}function w(e,t){return`${e} vs ${t}`}function v(e,t){const n=(0,m.f)(e);if(!n)return void r.shell.warning("Please annotate experimental groups first (Proteomics | Annotate Experiment)");if("true"===e.getTag("proteomics.de_complete"))return void r.shell.warning("Differential expression already performed");const o=n.group1,i=n.group2,l=s.divText(`Group 1: ${o.name} (${o.columns.length} samples), Group 2: ${i.name} (${i.columns.length} samples)`),c=[`${i.name} vs ${o.name}`,`${o.name} vs ${i.name}`],p=s.input.choice("Comparison",{value:w(o.name,i.name),items:c,nullable:!1}),d=s.div();d.style.cssText="font-style:italic; color:#888; font-size:12px; margin-bottom:8px;";const f=()=>{const e=p.value===c[1],t=e?o.name:i.name,n=e?i.name:o.name;d.textContent=`Positive log2FC = higher in ${t}, Negative log2FC = higher in ${n}`};p.onChanged.subscribe(f),f();const v=s.input.choice("Method",{value:"limma",items:["limma","DEqMS","t-test"],nullable:!1});v.setTooltip("limma: moderated t-test; DEqMS: peptide-count-weighted variance; t-test: client-side Welch's t-test");const _=e.columns.toList().find(e=>"Unique peptides"===e.name||"Peptides"===e.name)??void 0,C=s.input.column("Peptide count column",{table:e,value:_,filter:e=>e.type===a.COLUMN_TYPE.INT||e.type===a.COLUMN_TYPE.FLOAT,nullable:!1});C.setTooltip("Column with peptide/spectra counts per protein");const b=C.root;b.style.display="none",v.onChanged.subscribe(()=>{b.style.display="DEqMS"===v.value?"":"none"});const T=s.input.float("|log2FC| threshold",{value:u.M5});T.setTooltip("Minimum absolute fold change for significance");const P=s.input.float("Adj. p-value threshold",{value:u.Dx});P.setTooltip("Maximum adjusted p-value for significance"),s.dialog("Differential Expression").add(l).add(p).add(d).add(v).add(C).add(T).add(P).onOK(async()=>{const n=T.value??u.M5,s=P.value??u.Dx,l=v.value,m=p.value===c[1],d=m?o.columns:i.columns,f=m?i.columns:o.columns,w=(m?o.name:i.name,m?i.name:o.name,a.TaskBarProgressIndicator.create(`Running ${l} analysis...`));try{if("t-test"===l){const t=g(e,f,d,0,0,n,s);e.setTag("proteomics.de_method","t-test"),r.shell.info(`DE complete (t-test): ${t.tested} proteins tested, ${t.untestable} untestable`)}else if("DEqMS"===l){const t=C.value;if(!t)return void r.shell.error("Please select a peptide count column for DEqMS");try{const o=await async function(e,t,n,o,s,i){const l=h(e,t,n),c=a.DataFrame.create(e.rowCount),u=c.columns.addNewInt("count");for(let t=0;t<e.rowCount;t++)u.set(t,o.isNone(t)?1:Math.round(o.get(t)));const m=y(e,await r.functions.call("Proteomics:DeqmsDE",{exprDf:l,nGroup1:t.length,peptideDf:c,fcThreshold:s,pThreshold:i}));return e.setTag("proteomics.de_complete","true"),e.setTag("proteomics.de_method","deqms"),e.fireValuesChanged(),m}(e,f,d,t,n,s);e.setTag("proteomics.de_method","deqms"),r.shell.info(`DE complete (DEqMS): ${o} significant proteins`)}catch(t){console.warn("DEqMS failed, trying limma:",t),w.update(50,"DEqMS unavailable, trying limma..."),r.shell.warning("DEqMS unavailable, trying limma...");try{const t=await E(e,f,d,n,s);e.setTag("proteomics.de_method","limma"),r.shell.info(`DE complete (limma fallback): ${t} significant proteins`)}catch(t){console.warn("Limma DE also failed, using client-side fallback:",t),w.update(75,"Server-side DE unavailable, using client-side t-test..."),r.shell.warning("R environment unavailable — using client-side t-test");const o=g(e,f,d,0,0,n,s);e.setTag("proteomics.de_method","t-test"),r.shell.info(`DE complete (t-test): ${o.tested} proteins tested, ${o.untestable} untestable`)}}}else try{const t=await E(e,f,d,n,s);e.setTag("proteomics.de_method","limma"),r.shell.info(`DE complete (limma): ${t} significant proteins`)}catch(t){w.update(50,"Limma unavailable, using client-side t-test..."),r.shell.warning("R environment unavailable — using client-side t-test"),console.warn("Limma DE failed, using client-side fallback:",t);const o=g(e,f,d,0,0,n,s);e.setTag("proteomics.de_method","t-test"),r.shell.info(`DE complete (t-test): ${o.tested} proteins tested, ${o.untestable} untestable`)}}finally{w.close()}t&&t()}).show()}},989(e,t,n){"use strict";n.d(t,{J:()=>c,N:()=>u});var o=n(328),r=n(389),s=n(82),a=n(304),i=n(641),l=n(230);function c(e,t,n){const o=(0,a.I)(e);if(!o.log2fc||!o.pValue)throw new Error("No log2FC or adjusted p-value columns found. Run Differential Expression first.");const r=o.geneName??o.proteinId;if(!r)throw new Error("No gene-name or protein-ID column found to export.");const s=new Map;for(let t=0;t<e.rowCount;t++){const e=r.get(t);e&&s.set(t,String(e))}const i=o.log2fc.getRawData(),c=o.pValue.getRawData(),{upGenes:u,downGenes:m,background:p}=(0,l.Bx)(s,i,c,t,n),d=e=>/[",\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e,f=["gene,list"];for(const e of u)f.push(`${d(e)},up`);for(const e of m)f.push(`${d(e)},down`);for(const e of p)f.push(`${d(e)},background`);return{csv:f.join("\n"),counts:{up:u.length,down:m.length,background:p.length}}}function u(e){const t=(0,a.I)(e);if(!t.log2fc||!t.pValue)return void o.shell.warning("No log2FC or p-value columns found. Run Differential Expression first.");const n=r.input.float("|log2FC| threshold",{value:i.M5});n.setTooltip("Minimum absolute fold change for a gene to count as up/down.");const u=r.input.float("Adj. p-value threshold",{value:i.Dx});u.setTooltip("Maximum adjusted p-value for a gene to count as up/down.");const m=r.divText(""),p=()=>{const o=(0,l.bM)(e,n.value??i.M5,u.value??i.Dx,t.log2fc,t.pValue);m.textContent=`${o.significant} of ${o.total.toLocaleString()} proteins significant`};p(),n.onChanged.subscribe(p),u.onChanged.subscribe(p),r.dialog("Export Enrichment Inputs").add(m).add(n).add(u).onOK(()=>{const t=n.value??i.M5,r=u.value??i.Dx,{csv:a,counts:l}=c(e,t,r),m=e.name?`${e.name} — enrichment inputs`:"enrichment inputs";s.Utils.download(`${m}.csv`,a,"text/csv"),o.shell.info(`Exported ${l.up} up, ${l.down} down, ${l.background} background genes.`)}).show()}},230(e,t,n){"use strict";n.d(t,{AB:()=>E,Ae:()=>p.Ae,Bx:()=>v,D9:()=>C,Mz:()=>w,_W:()=>y,bM:()=>_,pG:()=>b,zy:()=>h});var o=n(328),r=n(389),s=n(82),a=n(498),i=n(304),l=n(641),c=n(897),u=n(829),m=n(252),p=n(935);const d="https://biit.cs.ut.ee/gprofiler";async function f(e,t,n=3e4){const r=o.dapi.fetchProxy(e,t),s=new Promise((e,t)=>setTimeout(()=>t(new Error("g:Profiler API request timed out. The service may be temporarily unavailable.")),n)),a=await Promise.race([r,s]);if(!a.ok)throw new Error(`g:Profiler API returned status ${a.status}`);return a}async function g(e,t,n,o,r=l.Dx){const s=await f(`${d}/api/gost/profile/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({organism:n,query:e,sources:o,user_threshold:r,significance_threshold_method:"fdr",domain_scope:"custom",background:t,all_results:!0,ordered:!1,no_evidences:!1,combined:!1,measure_underrepresentation:!1,no_iea:!1,numeric_ns:"",output:"json"})}),a=await s.json();return a.result?Array.isArray(a.result)&&a.result.length>0&&a.result[0]?.result?a.result[0].result:Array.isArray(a.result)?a.result:[]:[]}const h=["localization","cellular component organization","transport","cellular process","biological process","metabolic process"],y=["actin","vesicle","endocytosis","cytoskeleton"];function E(e,t=15){if(0===e.length)return{kept:[],stats:{total:0,kept:0,droppedParents:0,cappedAtN:t}};const n=e.filter(e=>"GO:BP"===e.source),o=e.filter(e=>"GO:BP"!==e.source);let r=0;const s=[];if(n.length>0){const e=[...n].sort((e,t)=>e.p_value-t.p_value);for(const n of e){const e=(n.name??"").toLowerCase();if(h.some(t=>e.includes(t))&&s.some(e=>y.some(t=>(e.name??"").toLowerCase().includes(t))))r++;else if(s.push(n),s.length>=t)break}}const a=[...o].sort((e,t)=>e.p_value-t.p_value).slice(0,t),i=[...s,...a].sort((e,t)=>e.p_value-t.p_value);return{kept:i,stats:{total:e.length,kept:i.length,droppedParents:r,cappedAtN:t}}}function w(e,t,n=l.Dx,o){const r=e.length,a=s.DataFrame.create(r);a.name="Enrichment Results";const i=e.map(e=>{if(!e.intersections)return"";const n=[],o=Math.min(t.length,e.intersections.length);for(let r=0;r<o;r++)e.intersections[r]&&e.intersections[r].length>0&&n.push(t[r]);return n.join(", ")}),c=a.columns.addNewString("Source"),u=a.columns.addNewString("Term ID"),m=a.columns.addNewString("Term Name"),p=a.columns.addNewFloat("FDR"),d=a.columns.addNewInt("Gene Count"),f=a.columns.addNewFloat("Gene Ratio"),g=a.columns.addNewString("Intersection");c.init(t=>e[t].source),u.init(t=>e[t].native),m.init(t=>e[t].name),p.init(t=>e[t].p_value),d.init(t=>e[t].intersection_size),f.init(t=>e[t].precision),g.init(e=>i[e]);const h=p.getRawData();return a.columns.addNewBool("Significant").init(e=>h[e]!==s.FLOAT_NULL&&h[e]<=n),o&&a.columns.addNewString("Direction").init(()=>o),p.setTag("color-coding-type","Linear"),p.setTag("color-coding-linear",'{"0":"#2ecc71","0.05":"#f39c12","1":"#e74c3c"}'),a.setTag("proteomics.enrichment","true"),a}function v(e,t,n,o,r){const a=new Set,i=new Set,l=new Set;for(const[c,u]of e){l.add(u);const e=t[c],m=n[c];e!==s.FLOAT_NULL&&m!==s.FLOAT_NULL&&m<=r&&Math.abs(e)>=o&&(e>0?a.add(u):e<0&&i.add(u))}return{upGenes:[...a],downGenes:[...i],background:[...l]}}function _(e,t,n,o,r){const a=e.rowCount,i=o.getRawData(),l=r.getRawData();let c=0;for(let e=0;e<a;e++){const o=i[e],r=l[e];o!==s.FLOAT_NULL&&r!==s.FLOAT_NULL&&Math.abs(o)>=t&&r<=n&&c++}return{significant:c,total:a}}async function C(e,t,n,o,r,s=!0,c=15){const u=(0,i.I)(e);if(!u.proteinId)throw new Error("No protein ID column found");if(!u.log2fc||!u.pValue)throw new Error("No log2FC or adjusted p-value columns found. Run Differential Expression first.");let m,p=0,h=0,y=0;if(u.geneName){m=new Map;const t=u.geneName;for(let n=0;n<e.rowCount;n++){const e=t.get(n);e&&m.set(n,e)}p=m.size,h=e.rowCount,y=h-p}else{const t=new Map;for(let n=0;n<e.rowCount;n++){const e=u.proteinId.get(n),o=(0,a.S6)(e);o&&(t.has(o)||t.set(o,[]),t.get(o).push(n))}const n=[...t.keys()],r=await async function(e,t="hsapiens"){const n=await f(`${d}/api/convert/convert/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({organism:t,query:e,target:"ENSG",numeric_ns:"",output:"json"})});return(await n.json()).result??[]}(n,o),s=new Map;for(const e of r)e.incoming&&e.name&&"N/A"!==e.name&&!s.has(e.incoming)&&s.set(e.incoming,e.name);m=new Map;for(const[e,n]of t){const t=s.get(e);if(t)for(const e of n)m.set(e,t)}const i=new Array(e.rowCount).fill("");for(const[e,t]of m)i[e]=t;const c=e.columns.addNewString("Gene Symbol (mapped)");c.semType=l.iu.GENE_SYMBOL,c.init(e=>i[e]),p=s.size,h=n.length,y=h-p}const _=u.log2fc.getRawData(),C=u.pValue.getRawData(),{upGenes:b,downGenes:T,background:P}=v(m,_,C,t,n);if(0===b.length&&0===T.length)throw new Error("No significant proteins found with the given thresholds");const S=[];let N=null,A=null;if(b.length>0){let e=await g(b,P,o,r,n);if(s){const t=E(e,c);e=t.kept,N=t.stats}S.push(w(e,b,n,"Up"))}if(T.length>0){let e=await g(T,P,o,r,n);if(s){const t=E(e,c);e=t.kept,A=t.stats}S.push(w(e,T,n,"Down"))}let x=S[0];for(let e=1;e<S.length;e++)x=x.append(S[e]);x.name=e.name?`${e.name} — Enrichment`:"Enrichment Results",x.setTag("proteomics.enrichment","true");const D=x.col("FDR");if(D&&(D.setTag("color-coding-type","Linear"),D.setTag("color-coding-linear",'{"0":"#2ecc71","0.05":"#f39c12","1":"#e74c3c"}')),s){const e=(N?.total??0)+(A?.total??0),t=(N?.kept??0)+(A?.kept??0),n=(N?.droppedParents??0)+(A?.droppedParents??0);t<e&&(x.setTag("proteomics.enrichment_smart_filtered","true"),x.setTag("proteomics.enrichment_smart_filtered_kept",String(t)),x.setTag("proteomics.enrichment_smart_filtered_total",String(e)),x.setTag("proteomics.enrichment_smart_filtered_dropped_parents",String(n)),x.setTag("proteomics.enrichment_smart_filtered_cap",String(c)))}return{enrichmentDf:x,mapped:p,total:h,unmapped:y}}function b(e){if(!(0,u.RJ)(e,"Run Differential Expression first"))return;const t=(0,i.I)(e);if(!t.log2fc||!t.pValue)return void o.shell.warning("No log2FC or p-value columns found");const n=r.input.float("|log2FC| threshold",{value:l.M5});n.setTooltip("Minimum absolute fold change for significance");const a=r.input.float("Adj. p-value threshold",{value:l.Dx});a.setTooltip("Maximum adjusted p-value for significance");const d=(0,p.X3)((0,m.Di)(e)??(0,p.Vr)(e)),f=r.input.choice("Organism",{value:d??"Homo sapiens (Human)",items:p.Ae.map(e=>e.display),nullable:!1}),g=r.input.bool("GO: Biological Process",{value:!0}),h=r.input.bool("GO: Molecular Function",{value:!0}),y=r.input.bool("GO: Cellular Component",{value:!0}),E=r.input.bool("KEGG Pathways",{value:!0}),w=r.input.bool("Reactome Pathways",{value:!0}),v=r.input.bool("WikiPathways",{value:!0}),b=r.input.bool("Apply smart pathway filter",{value:!0});b.setTooltip("Drops generic GO parent terms when more specific child terms are present; caps each source at top-N by FDR. Recommended for cleaner results; uncheck for raw g:Profiler output.");const T=r.input.int("Max terms per source",{value:15,min:1});T.setTooltip("Upper bound on terms kept per enrichment source (top-N by FDR). Applies only when the smart pathway filter is on.");const P=()=>T.enabled=b.value??!0;b.onChanged.subscribe(P),P();const S=r.divText(""),N=()=>{const o=n.value??l.M5,r=a.value??l.Dx,s=_(e,o,r,t.log2fc,t.pValue),i=s.total.toLocaleString();S.textContent=`${s.significant} of ${i} proteins are significant with these thresholds`};N(),n.onChanged.subscribe(N),a.onChanged.subscribe(N),r.dialog("Enrichment Analysis").add(S).add(n).add(a).add(f).add(g).add(h).add(y).add(E).add(w).add(v).add(b).add(T).onOK(async()=>{const t=s.TaskBarProgressIndicator.create("Running enrichment analysis...");try{const t=n.value??l.M5,r=a.value??l.Dx,s=f.value,i=p.Ae.find(e=>e.display===s),u=i?.code??"hsapiens";(0,m.Np)(e,u);const d=[];if(g.value&&d.push("GO:BP"),h.value&&d.push("GO:MF"),y.value&&d.push("GO:CC"),E.value&&d.push("KEGG"),w.value&&d.push("REAC"),v.value&&d.push("WP"),0===d.length)return void o.shell.warning("Please select at least one enrichment source");const _=await C(e,t,r,u,d,b.value??!0,T.value??15),P=_.total>0?(_.mapped/_.total*100).toFixed(1):"0.0";o.shell.info(`${_.mapped}/${_.total} proteins mapped (${P}%). ${_.unmapped} unmapped.`),(0,c.q6)(_.enrichmentDf,e)}catch(e){o.shell.error(`Enrichment analysis failed: ${e.message}`)}finally{t.close()}}).show()}},252(e,t,n){"use strict";n.d(t,{$Y:()=>u,Di:()=>d,Np:()=>p,XX:()=>g,Yf:()=>f,applyAnnotation:()=>h,f:()=>m});var o=n(328),r=n(389),s=n(353),a=n.n(s),i=n(641),l=n(655),c=n(935);function u(e,t){e.setTag("proteomics.groups",JSON.stringify(t))}function m(e){const t=e.getTag("proteomics.groups");if(!t)return null;try{return JSON.parse(t)}catch{return null}}function p(e,t){e.setTag("proteomics.organism",t)}function d(e){return e.getTag("proteomics.organism")||void 0}function f(e,t){const n=function(e){const t=(0,l.getRunMeta)(e);if(t)return t;const n=e.getTag("proteomics.spc_run_meta_seed");if(n)try{return JSON.parse(n)}catch{return}}(e),o=m(e);if(!o)return{group1Name:"Control",group1Cols:[],group2Name:"Treatment",group2Cols:[],instrumentId:n?.instrument_id,acquisitionDatetime:n?.acquisition_datetime};const r=new Set(t),s=t=>t.filter(e=>r.has(e)).map(t=>e.col(t)).filter(e=>null!==e);return{group1Name:o.group1.name||"Control",group1Cols:s(o.group1.columns),group2Name:o.group2.name||"Treatment",group2Cols:s(o.group2.columns),instrumentId:n?.instrument_id,acquisitionDatetime:n?.acquisition_datetime}}function g(e){const t=e.columns.toList().filter(e=>e.semType===i.iu.INTENSITY&&e.name.startsWith("log2(")).map(e=>e.name),n=f(e,t),s=r.input.string("Group 1 Name",{value:n.group1Name}),l=r.input.columns("Group 1",{table:e,available:t,value:n.group1Cols}),u=r.input.string("Group 2 Name",{value:n.group2Name}),m=r.input.columns("Group 2",{table:e,available:t,value:n.group2Cols}),p=r.input.string("Instrument",{value:n.instrumentId??"",tooltipText:"Free-text identifier for the instrument that ran this analysis (e.g. QExactive-01). Used to group runs in the SPC dashboard."}),g=r.input.date("Acquisition datetime",{value:n.acquisitionDatetime?a()(n.acquisitionDatetime):null,tooltipText:"When the samples were acquired on the instrument. Used to order runs on the SPC trend chart — not the file-import time."}),y=r.input.choice("Organism",{value:(0,c.X3)(d(e)??(0,c.Vr)(e))??"Homo sapiens (Human)",items:c.Ae.map(e=>e.display),nullable:!1,tooltipText:"Species for enrichment (g:Profiler) and UniProt subcellular-location lookup. Auto-detected from the data when available."});r.dialog("Annotate Experiment").add(s).add(l).add(u).add(m).add(y).add(p).add(g).onOK(()=>{const t=l.value??[],n=m.value??[];if(0===t.length||0===n.length)return void o.shell.warning("Select at least one column per group");const r={group1:{name:s.value,columns:t.map(e=>e.name)},group2:{name:u.value,columns:n.map(e=>e.name)}},a=(p.value??"").trim(),i=g.value,d=i&&"function"==typeof i.toISOString||i instanceof Date?i.toISOString():"";h(e,{group1:r.group1,group2:r.group2,organism:(0,c.$S)(y.value??void 0),runMeta:a.length>0||d.length>0?{instrument_id:a,acquisition_datetime:d}:void 0}),o.shell.info(`Groups assigned: ${t.length} + ${n.length} samples`)}).show()}function h(e,t){u(e,{group1:t.group1,group2:t.group2}),t.organism&&p(e,t.organism),t.runMeta&&(0,l.setRunMeta)(e,t.runMeta)}},47(e,t,n){"use strict";n.d(t,{Mx:()=>u,Q2:()=>p,U0:()=>c,UN:()=>f,fX:()=>m,p4:()=>d});var o=n(328),r=n(389),s=n(82),a=n(641),i=n(252);function l(e,t){const n=Math.random(),o=Math.random();return e+t*(Math.sqrt(-2*Math.log(n))*Math.cos(2*Math.PI*o))}function c(e,t,n=1.8,o=.3){let r=0;for(const a of t){const t=e.col(a);if(!t)continue;if(t.type!==s.COLUMN_TYPE.FLOAT)continue;const i=t.stats.avg,c=t.stats.stdev;if(isNaN(i)||isNaN(c)||0===c)continue;const u=i-n*c,m=o*c,p=t.getRawData();for(let t=0;t<e.rowCount;t++)p[t]===s.FLOAT_NULL&&(p[t]=l(u,m),r++)}return e.fireValuesChanged(),e.setTag("proteomics.imputed","true"),r}function u(e,t,n=10){const o=t.map(t=>e.col(t)).filter(e=>null!=e&&e.type===s.COLUMN_TYPE.FLOAT);if(0===o.length)return 0;const r=o.map(e=>e.getRawData()),a=e.rowCount,i=o.length,l=[],c=[];for(let e=0;e<a;e++){const t=new Float64Array(i),n=[];for(let r=0;r<i;r++){const s=o[r].isNone(e);n.push(s),t[r]=s?0:o[r].get(e)}l.push(t),c.push(n)}const u=new Float64Array(i);for(let e=0;e<i;e++){let t=0,n=0;for(let o=0;o<a;o++)c[o][e]||(t+=l[o][e],n++);u[e]=n>0?t/n:NaN}const m=[];for(let e=0;e<a;e++)c[e].some(e=>e)&&m.push(e);const p=s.TaskBarProgressIndicator.create("kNN imputation...");let d=0;try{for(let e=0;e<m.length;e++){const t=m[e];if(p.update(Math.round(e/m.length*100),`Row ${e+1}/${m.length}`),!c[t].some(e=>!e)){for(let e=0;e<i;e++)c[t][e]&&isFinite(u[e])&&(r[e][t]=u[e],d++);continue}const o=[];for(let e=0;e<a;e++){if(e===t)continue;let n=0,r=0;for(let o=0;o<i;o++)if(!c[t][o]&&!c[e][o]){const s=l[t][o]-l[e][o];n+=s*s,r++}r>0&&o.push({row:e,dist:Math.sqrt(n/r)})}o.sort((e,t)=>e.dist-t.dist);const s=o.slice(0,n);for(let e=0;e<i;e++){if(!c[t][e])continue;let n=0,o=0;for(const t of s)c[t.row][e]||(n+=l[t.row][e],o++);const a=o>0?n/o:u[e];isFinite(a)&&(r[e][t]=a,d++)}}}finally{p.close()}return e.fireValuesChanged(),e.setTag("proteomics.imputed","true"),d}function m(e,t){let n=0;for(const o of t){const t=e.col(o);if(!t||t.type!==s.COLUMN_TYPE.FLOAT)continue;const r=t.getRawData();for(let t=0;t<e.rowCount;t++)r[t]===s.FLOAT_NULL&&(r[t]=0,n++)}return e.fireValuesChanged(),e.setTag("proteomics.imputed","true"),n}function p(e,t){let n=0;for(const o of t){const t=e.col(o);if(!t||t.type!==s.COLUMN_TYPE.FLOAT)continue;const r=t.stats.avg;if(isNaN(r))continue;const a=t.getRawData();for(let t=0;t<e.rowCount;t++)a[t]===s.FLOAT_NULL&&(a[t]=r,n++)}return e.fireValuesChanged(),e.setTag("proteomics.imputed","true"),n}function d(e,t){let n=0;for(const o of t){const t=e.col(o);if(!t||t.type!==s.COLUMN_TYPE.FLOAT)continue;const r=t.stats.med;if(isNaN(r))continue;const a=t.getRawData();for(let t=0;t<e.rowCount;t++)a[t]===s.FLOAT_NULL&&(a[t]=r,n++)}return e.fireValuesChanged(),e.setTag("proteomics.imputed","true"),n}function f(e){if("true"===e.getTag("proteomics.imputed"))return void o.shell.warning("Missing values already imputed");const t=e.columns.toList().filter(e=>e.semType===a.iu.INTENSITY&&e.name.startsWith("log2(")).map(e=>e.name),n=t.map(t=>e.col(t)),l=r.input.choice("Method",{value:"MinProb",items:["MinProb","kNN","Zero","Mean","Median"],nullable:!1}),f=r.input.columns("Intensity columns",{table:e,available:t,value:n}),g=r.input.float("Downshift",{value:1.8});g.setTooltip("Standard deviations to shift left from mean (Perseus default: 1.8)");const h=r.input.float("Width",{value:.3});h.setTooltip("Fraction of standard deviation for imputation distribution (Perseus default: 0.3)");const y=r.div([g.root,h.root]),E=r.input.int("k (neighbors)",{value:10}),w=r.div([E.root]);w.style.display="none",l.onChanged.subscribe(()=>{const e=l.value;y.style.display="MinProb"===e?"":"none",w.style.display="kNN"===e?"":"none"});const v=r.input.int("Min valid values per group",{value:2}),_=r.divText("");_.style.cssText="font-size:12px; color:#888; margin-bottom:8px;";const C=()=>{const t=v.value??0,n=(0,i.f)(e);if(0===t||!n)return void(_.textContent=`Will keep all ${e.rowCount} proteins`);const o=n.group1.columns.map(t=>e.col(t)).filter(e=>null!=e),r=n.group2.columns.map(t=>e.col(t)).filter(e=>null!=e);let s=0;for(let n=0;n<e.rowCount;n++){let e=0;for(const t of o)t.isNone(n)||e++;let a=0;for(const e of r)e.isNone(n)||a++;(e>=t||a>=t)&&s++}const a=e.rowCount-s;_.textContent=`Will keep ${s}/${e.rowCount} proteins (${a} removed)`};v.onChanged.subscribe(C),C(),r.dialog("Impute Missing Values").add(l).add(f).add(y).add(w).add(v).add(_).onOK(()=>{const t=f.value.map(e=>e.name),n=l.value,r=v.value??0,a=(0,i.f)(e);if(r>0&&a){const t=a.group1.columns.map(t=>e.col(t)).filter(e=>null!=e),n=a.group2.columns.map(t=>e.col(t)).filter(e=>null!=e),i=s.BitSet.create(e.rowCount);for(let o=0;o<e.rowCount;o++){let e=0;for(const n of t)n.isNone(o)||e++;let s=0;for(const e of n)e.isNone(o)||s++;e<r&&s<r&&i.set(o,!0)}const l=i.trueCount;l>0&&(e.rows.removeWhere(e=>i.get(e.idx)),o.shell.info(`Filtered: removed ${l} proteins below threshold`))}let y=0;try{switch(n){case"MinProb":y=c(e,t,g.value,h.value);break;case"kNN":y=u(e,t,E.value);break;case"Zero":y=m(e,t);break;case"Mean":y=p(e,t);break;case"Median":y=d(e,t)}}catch(e){return void o.shell.error(`Imputation failed: ${e?.message??e}. Valid-values filter was already applied; data remains filtered but un-imputed.`)}o.shell.info(`Imputed ${y} missing values across ${t.length} columns (${n})`)}).show()}},871(e,t,n){"use strict";n.d(t,{DA:()=>c,IZ:()=>l,Kb:()=>u,ye:()=>i});var o=n(328),r=n(389),s=n(641),a=n(954);function i(e){return e.columns.toList().filter(e=>e.semType===s.iu.INTENSITY&&!e.name.startsWith("log2(")).map(e=>e.name)}function l(e,t){for(const n of t){const t=e.col(n),o=e.col(`log2(${n})`);if(t&&o)for(let n=0;n<e.rowCount;n++){if(t.isNone(n)||o.isNone(n))continue;const e=Number(t.get(n)),r=Number(o.get(n));if(e>0&&Number.isFinite(r)){if(Math.abs(r-Math.log2(e))<1e-4)return"transform";if(Math.abs(r-e)<1e-4)return"copy"}}}return"unknown"}function c(e,t){const n=i(e);if(0===n.length)return!1;if(l(e,n)===(t?"copy":"transform"))return!1;for(const t of n){const n=`log2(${t})`;e.col(n)&&e.columns.remove(n)}t?(0,a.l3)(e,n):(0,a.Kh)(e,n);for(const t of["proteomics.normalized","proteomics.imputed","proteomics.de_complete","proteomics.de_method"])e.setTag(t,"");return!0}function u(e){const t=i(e);if(0===t.length)return void o.shell.warning("No intensity columns found — nothing to rescale.");const n=l(e,t),s=(0,a.eY)(e,t),u=r.input.bool("Data is already log2-transformed",{value:"copy"===n,tooltipText:"On: intensities are used as-is. Off: a log2 transform is applied. Flip this if fold changes look wildly off — the import heuristic can misread small-magnitude raw intensities as already-log2."}),m=r.divText(`Auto-detection: ${s.message}.`+("unknown"!==n?` Currently applied: ${"copy"===n?"used as-is (no transform)":"log2-transformed"}.`:""));m.style.cssText="font-style:italic;color:#888;margin:4px 0;font-size:12px;max-width:420px;";const p=["proteomics.normalized","proteomics.imputed","proteomics.de_complete"].some(t=>"true"===e.getTag(t)),d=r.divText("Normalize / Impute / Differential Expression have already run. Changing the scale resets those steps — re-run them from Analyze.");d.style.cssText="color:#b26a00;margin:4px 0;font-size:12px;max-width:420px;",d.style.display=p?"":"none",r.dialog("Set Log2 Scale").add(u).add(m).add(d).onOK(()=>{c(e,u.value)?o.shell.info(u.value?"Intensities are now used as-is (no log2 transform). Re-run analysis steps.":"Intensities are now log2-transformed. Re-run analysis steps."):o.shell.info("Scale unchanged.")}).show()}},350(e,t,n){"use strict";n.d(t,{Nx:()=>u,VD:()=>c,aj:()=>l,v5:()=>m});var o=n(328),r=n(389),s=n(82),a=n(641),i=n(715);function l(e,t){for(const n of t){const t=e.col(n);if(!t)continue;if(t.type!==s.COLUMN_TYPE.FLOAT){console.warn(`medianNormalize: skipping non-float column "${n}" (type=${t.type})`);continue}const o=t.stats.med;if(isNaN(o))continue;const r=t.getRawData();for(let e=0;e<r.length;e++)t.isNone(e)||(r[e]-=o)}e.fireValuesChanged(),e.setTag("proteomics.normalized","true")}function c(e,t){if(t.length<2)return;const n=t.map(t=>e.col(t)).filter(e=>null!=e&&e.type===s.COLUMN_TYPE.FLOAT);if(n.length<2)return;const o=e.rowCount,r=[];for(const e of n){const t=e.getRawData(),n=[];for(let t=0;t<o;t++)e.isNone(t)||n.push(t);n.sort((e,n)=>t[e]-t[n]),r.push({indices:n,raw:t})}const a=Math.max(...r.map(e=>e.indices.length));if(0===a)return;const i=new Float64Array(a);for(let e=0;e<a;e++){let t=0,n=0;for(const o of r){if(0===o.indices.length)continue;const r=e/(a-1)*(o.indices.length-1),s=Math.floor(r),i=Math.min(Math.ceil(r),o.indices.length-1),l=r-s;t+=(1-l)*o.raw[o.indices[s]]+l*o.raw[o.indices[i]],n++}i[e]=t/n}for(const e of r){const t=e.indices.length;if(0!==t)for(let n=0;n<t;n++){const o=1===a?0:n/(t-1)*(a-1),r=Math.floor(o),s=Math.min(Math.ceil(o),a-1),l=o-r,c=(1-l)*i[r]+l*i[s];e.raw[e.indices[n]]=c}}e.fireValuesChanged(),e.setTag("proteomics.normalized","true")}async function u(e,t){try{const n=[],r=[];for(const o of t)if(o.startsWith("log2(")&&o.endsWith(")")){const t=o.slice(5,-1);e.col(t)&&(n.push(t),r.push(o))}if(0===n.length)return t.length<2?void o.shell.warning("Cannot normalize — VSN needs raw intensity columns and quantile fallback needs at least 2 columns"):(o.shell.warning("No raw intensity columns found for VSN — using quantile normalization"),void c(e,t));const a=s.DataFrame.create(e.rowCount);for(let t=0;t<n.length;t++){const o=e.col(n[t]).getRawData();a.columns.addNewFloat(`s${t+1}`).init(e=>o[e])}const i=await o.functions.call("Proteomics:VsnNormalize",{exprDf:a});for(let t=0;t<r.length;t++){const n=e.col(r[t]),o=i.col(`s${t+1}`),a=n.getRawData(),l=o.getRawData();for(let t=0;t<e.rowCount;t++)l[t]!==s.FLOAT_NULL&&(a[t]=l[t])}e.fireValuesChanged(),e.setTag("proteomics.normalized","true")}catch(n){if(console.warn("VSN normalization failed, using quantile fallback:",n),t.length<2)return void o.shell.warning("VSN failed and quantile fallback needs at least 2 columns — data left unnormalized");o.shell.warning("R environment unavailable — using quantile normalization"),c(e,t)}}function m(e){if("true"===e.getTag("proteomics.normalized"))return void o.shell.warning("Data already normalized");const t=e.columns.toList().filter(e=>e.semType===a.iu.INTENSITY&&e.name.startsWith("log2(")).map(e=>e.name),n=t.map(t=>e.col(t)),m=r.div([],{style:{background:"#FFF3CD",border:"1px solid #FFEEBA",color:"#856404",padding:"8px",margin:"4px 0",borderRadius:"4px",display:"true"===e.getTag("proteomics.preNormalized")?"":"none"}});m.textContent="This data may be pre-normalized (Spectronaut). Additional normalization may distort results.";const p=r.input.choice("Method",{value:"Median Centering",items:["Median Centering","Quantile","VSN"],nullable:!1}),d=r.input.columns("Intensity columns",{table:e,available:t,value:n}),f=r.div([],{style:{width:"100%",height:"250px",border:"1px solid #ddd",marginTop:"8px"}});function g(){f.innerHTML="";const t=d.value.map(e=>e.name);if(0===t.length)return;const n=e.clone(null,t),o=p.value;"Median Centering"===o?l(n,t):"Quantile"===o&&c(n,t);const r=(0,i.j4)(n,t),a=s.Viewer.boxPlot(r,{valueColumnName:"Intensity",categoryColumnName:"Sample"});a.root.style.width="100%",a.root.style.height="220px",f.appendChild(a.root)}p.onChanged.subscribe(()=>g()),d.onChanged.subscribe(()=>g()),g(),r.dialog("Normalize").add(m).add(p).add(d).add(f).onOK(async()=>{const t=d.value.map(e=>e.name),n=p.value;"Median Centering"===n?l(e,t):"Quantile"===n?c(e,t):"VSN"===n&&await u(e,t),o.shell.info(`Normalized ${t.length} columns (${n})`)}).show()}},883(e,t,n){"use strict";n.d(t,{$G:()=>S,OI:()=>P,loadBaseline:()=>w,loadRuns:()=>E,oF:()=>C,readRunsMeta:()=>h,saveBaseline:()=>v,upsertRun:()=>y});var o=n(328),r=n(82);const s=["run_id","instrument_id","acquisition_datetime","run_label","median_intensity","missing_pct","control_corr","protein_count","status","rules_tripped","source_project_id","source_df_name","computed_at"],a="spc.runs.schema_version";function i(e){return e&&e.root?e.root:"System:AppData/Proteomics/spc"}function l(e){return`${i(e)}/runs.csv`}function c(e){return`${i(e)}/runs-meta.json`}function u(e,t){return`${i(t)}/baseline-${function(e){if(null==e)return"unnamed";let t=String(e).replace(/[^A-Za-z0-9._-]+/g,"-").replace(/-{2,}/g,"-").replace(/^[-.]+|[-.]+$/g,"").slice(0,64).replace(/[-.]+$/g,"");return 0===t.length&&(t="unnamed"),t}(e)}.json`}function m(e){return e.indexOf(",")<0&&e.indexOf('"')<0&&e.indexOf("\n")<0?e:'"'+e.replace(/"/g,'""')+'"'}function p(e){const t=[];let n=0;for(;n<e.length;)if('"'===e[n]){n++;let o="";for(;n<e.length;)if('"'===e[n]){if('"'!==e[n+1]){n++;break}o+='"',n+=2}else o+=e[n],n++;t.push(o),","===e[n]&&n++}else{let o="";for(;n<e.length&&","!==e[n];)o+=e[n],n++;t.push(o),","===e[n]&&n++}return t}function d(e){return[e.run_id,e.instrument_id,e.acquisition_datetime,e.run_label,String(e.median_intensity),String(e.missing_pct),String(e.control_corr),String(e.protein_count),e.status,JSON.stringify(e.rules_tripped),null==e.source_project_id?"":e.source_project_id,e.source_df_name,e.computed_at].map(m).join(",")}function f(e){const t=t=>e[(e=>s.indexOf(e))(t)]??"";let n=[];try{const e=t("rules_tripped");e&&(n=JSON.parse(e))}catch{}const o=t("source_project_id");return{run_id:t("run_id"),instrument_id:t("instrument_id"),acquisition_datetime:t("acquisition_datetime"),run_label:t("run_label"),median_intensity:Number(t("median_intensity")),missing_pct:Number(t("missing_pct")),control_corr:Number(t("control_corr")),protein_count:Number(t("protein_count")),status:t("status"),rules_tripped:n,source_project_id:0===o.length?null:o,source_df_name:t("source_df_name"),computed_at:t("computed_at")}}async function g(e){const t=l(e);if(!await o.dapi.files.exists(t))return[];const n=function(e){const t=[],n=e.split("\n").filter(e=>e.length>0);for(const e of n)t.push(p(e));return t}(await o.dapi.files.readAsText(t));return n.length<=1?[]:n.slice(1).map(f)}async function h(e){const t=c(e);if(!await o.dapi.files.exists(t))return{};try{return JSON.parse(await o.dapi.files.readAsText(t))}catch(e){return console.warn(`[spc-storage] failed to parse ${t}: ${e}`),{}}}async function y(e,t){const n=await g(t),r=n.findIndex(t=>t.instrument_id===e.instrument_id&&t.acquisition_datetime===e.acquisition_datetime);let i;r>=0?(i={...n[r],...e,run_id:n[r].run_id,rules_tripped:e.rules_tripped,source_project_id:e.source_project_id},n[r]=i):(i={run_id:e.run_id??("undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"r-"+Math.random().toString(16).slice(2)+"-"+Date.now().toString(16)),instrument_id:e.instrument_id,acquisition_datetime:e.acquisition_datetime,run_label:e.run_label,median_intensity:e.median_intensity,missing_pct:e.missing_pct,control_corr:e.control_corr,protein_count:e.protein_count,status:e.status,rules_tripped:e.rules_tripped,source_project_id:e.source_project_id,source_df_name:e.source_df_name,computed_at:e.computed_at},n.push(i)),await o.dapi.files.writeAsText(l(t),function(e){const t=[s.map(m).join(",")];for(const n of e)t.push(d(n));return t.join("\n")+"\n"}(n));const u=await async function(e){return(await h(e))[a]??null}(t);return"1"!==u&&await async function(e,t){const n=await h(t);n[a]=e,await async function(e,t){await o.dapi.files.writeAsText(c(t),JSON.stringify(e,null,2))}(n,t)}("1",t),i}async function E(e,t){const n=await g(t),o=e?n.filter(t=>t.instrument_id===e):n;return o.sort((e,t)=>e.acquisition_datetime.localeCompare(t.acquisition_datetime)),o}async function w(e,t){const n=u(e,t);if(!await o.dapi.files.exists(n))return null;try{return JSON.parse(await o.dapi.files.readAsText(n))}catch(e){return console.warn(`[spc-storage] failed to parse baseline at ${n}: ${e}`),null}}async function v(e,t,n){await o.dapi.files.writeAsText(u(e,n),JSON.stringify(t,null,2))}function _(e){const t=e.length;if(0===t)return{mean:NaN,sd:NaN};let n=0;for(const t of e)n+=t;const o=n/t;let r=0;for(const t of e){const e=t-o;r+=e*e}return{mean:o,sd:t>1?Math.sqrt(r/(t-1)):0}}function C(e,t=2){const n=e.slice(),o=[],r=[];if(n.length<3)return{retained_run_ids:n.map(e=>e.run_id),excluded_run_ids:[],iteration_trace:[]};for(let e=1;e<=t;e++){const t=n.map(e=>e.value).filter(e=>Number.isFinite(e)),{mean:s,sd:a}=_(t);if(!Number.isFinite(a)||0===a)break;const i=[];for(let e=n.length-1;e>=0;e--){const t=n[e].value;if(!Number.isFinite(t))continue;const r=(t-s)/a;Math.abs(r)>3&&(i.push(n[e]),o.push(n[e]),n.splice(e,1))}if(0===i.length)break;r.push({iter:e,dropped:i.map(e=>e.run_id)})}return{retained_run_ids:n.map(e=>e.run_id),excluded_run_ids:o.map(e=>e.run_id),iteration_trace:r}}const b=["median_intensity","missing_pct","control_corr","protein_count"];function T(e){const t=e.filter(e=>Number.isFinite(e));if(t.length<2)return{mean:NaN,sd:NaN};const{mean:n,sd:o}=_(t);return{mean:n,sd:o}}function P(e){const t={};for(const n of b)t[n]=T(e.map(e=>e[n]));return t}function S(e){const t=t=>e.map(t),n=[r.Column.fromStrings("run_id",t(e=>e.run_id)),r.Column.fromStrings("instrument_id",t(e=>e.instrument_id)),r.Column.fromList(r.COLUMN_TYPE.DATE_TIME,"acquisition_datetime",t(e=>Date.parse(e.acquisition_datetime))),r.Column.fromStrings("run_label",t(e=>e.run_label)),r.Column.fromFloat32Array("median_intensity",new Float32Array(t(e=>e.median_intensity))),r.Column.fromFloat32Array("missing_pct",new Float32Array(t(e=>e.missing_pct))),r.Column.fromFloat32Array("control_corr",new Float32Array(t(e=>e.control_corr))),r.Column.fromFloat32Array("protein_count",new Float32Array(t(e=>e.protein_count))),r.Column.fromStrings("status",t(e=>e.status)),r.Column.fromStrings("rules_tripped",t(e=>JSON.stringify(e.rules_tripped))),r.Column.fromStrings("source_project_id",t(e=>e.source_project_id??"")),r.Column.fromStrings("source_df_name",t(e=>e.source_df_name)),r.Column.fromStrings("computed_at",t(e=>e.computed_at))];return r.DataFrame.fromColumns(n)}},655(e,t,n){"use strict";n.d(t,{Mj:()=>o,assertSpcEligible:()=>i,classifyStatus:()=>E,computeIterativeBaseline:()=>v,computeSpcMetrics:()=>m,defaultRulesEnabled:()=>p,evaluateNelsonRules:()=>h,getRunMeta:()=>a,kY:()=>d,recoverSpcMetricsFromColumn:()=>C,setRunMeta:()=>s,setSpcStatus:()=>_,uV:()=>y});const o=3.267,r="~spc_metrics_meta";function s(e,t){e.setTag("proteomics.spc_run_meta",JSON.stringify(t))}function a(e){const t=e.getTag("proteomics.spc_run_meta");if(!t)return null;try{return JSON.parse(t)}catch{return null}}function i(e){if("spectronaut-candidates"===e.getTag("proteomics.source"))throw new Error("SPC requires per-sample intensities. Re-import this analysis from the Spectronaut PG report (not the Candidates report) to compute SPC.")}function l(e,t){if(e.isNone(t))return!0;const n=e.get(t);return!("number"!=typeof n||!Number.isNaN(n))}function c(e,t){const n=e.length;if(n<3)return NaN;let o=0,r=0;for(let s=0;s<n;s++)o+=e[s],r+=t[s];const s=o/n,a=r/n;let i=0,l=0,c=0;for(let o=0;o<n;o++){const n=e[o]-s,r=t[o]-a;i+=n*r,l+=n*n,c+=r*r}const u=Math.sqrt(l*c);return 0===u?NaN:i/u}function u(e,t){const n=[];for(const o of t){const t=e.col(o);null!==t&&n.push(t)}return n}function m(e,t,n){const o=u(e,t.group1.columns),r=u(e,t.group2.columns),s=o.concat(r),a=t.group1.columns.length+t.group2.columns.length,i=[],m=e.rowCount;let p=0,d=0,f=0;for(let e=0;e<m;e++){let t=!1;for(const n of s)d++,l(n,e)?p++:(i.push(n.get(e)),t=!0);t&&f++}const g=function(e){if(0===e.length)return NaN;const t=e.slice().sort((e,t)=>e-t),n=t.length,o=Math.floor(n/2);return n%2==0?(t[o-1]+t[o])/2:t[o]}(i),h=0===d?NaN:p/d*100;let y=NaN;if(o.length>=2){let e=0,t=0;for(let n=0;n<o.length;n++)for(let r=n+1;r<o.length;r++){const s=o[n],a=o[r],i=[],u=[];for(let e=0;e<m;e++)l(s,e)||l(a,e)||(i.push(s.get(e)),u.push(a.get(e)));const p=c(i,u);Number.isNaN(p)||(e+=p,t++)}y=0===t?NaN:e/t}return{median_intensity:g,missing_pct:h,control_corr:y,protein_count:f,sample_count:a,computed_at:(new Date).toISOString()}}function p(){return{nelson_1:!0,nelson_2:!1,nelson_3:!1,nelson_4:!1,nelson_5:!0,nelson_6:!1,nelson_7:!1,nelson_8:!1}}function d(){const e={nelson_1:!0,nelson_2:!1,nelson_3:!1,nelson_4:!1,nelson_5:!0,nelson_6:!1,nelson_7:!1,nelson_8:!1};return{median_intensity:{...e},missing_pct:{...e},control_corr:{...e},protein_count:{...e}}}const f={nelson_1:function(e){const t=e.z.length-1;return Math.abs(e.z[t])>3},nelson_2:function(e){if(e.series.length<9)return!1;const t=e.series.slice(-9),n=t.every(t=>t>e.mean),o=t.every(t=>t<e.mean);return n||o},nelson_3:function(e){if(e.series.length<6)return!1;const t=e.series.slice(-6);let n=!0,o=!0;for(let e=1;e<6;e++)t[e]>t[e-1]||(n=!1),t[e]<t[e-1]||(o=!1);return n||o},nelson_4:function(e){if(e.series.length<14)return!1;const t=e.series.slice(-14).map(t=>t>e.mean?1:t<e.mean?-1:0);for(let e=1;e<t.length;e++){if(0===t[e]||0===t[e-1])return!1;if(t[e]===t[e-1])return!1}return!0},nelson_5:function(e){if(e.z.length<3){const t=e.z;if(t.length<2)return!1;const n=t.filter(e=>e>2).length,o=t.filter(e=>e<-2).length;return n>=2||o>=2}const t=e.z.slice(-3),n=t.filter(e=>e>2).length,o=t.filter(e=>e<-2).length;return n>=2||o>=2},nelson_6:function(e){if(e.z.length<5)return!1;const t=e.z.slice(-5),n=t.filter(e=>e>1).length,o=t.filter(e=>e<-1).length;return n>=4||o>=4},nelson_7:function(e){return!(e.z.length<15)&&e.z.slice(-15).every(e=>Math.abs(e)<1)},nelson_8:function(e){return!(e.z.length<8)&&e.z.slice(-8).every(e=>Math.abs(e)>1)}},g=["nelson_1","nelson_2","nelson_3","nelson_4","nelson_5","nelson_6","nelson_7","nelson_8"];function h(e,t,n,o,r){if(0===e.length||!Number.isFinite(n)||0===n)return{status:"pass",rulesTripped:[]};const s=e.map(e=>(e-t)/n),a={series:e,z:s,mean:t,sd:n},i=[];for(const e of g)o[e]&&f[e](a)&&i.push(r?`${e}@${r}`:e);return{status:E(i),rulesTripped:i}}function y(e,t,n,o){const r=[],s=["median_intensity","missing_pct","control_corr","protein_count"];for(const a of s){const s=e[a];if(!Number.isFinite(s))continue;const i=h(t[a].concat([s]),n[a].mean,n[a].sd,o[a],a);for(const e of i.rulesTripped)r.push(e)}return{status:E(r),rulesTripped:r}}function E(e){if(0===e.length)return"pass";for(const t of e)if(t.startsWith("nelson_1@")||"nelson_1"===t)return"out_of_control";return"flagged"}function w(e){const t=e.length;if(0===t)return{mean:NaN,sd:NaN};let n=0;for(const t of e)n+=t;const o=n/t;let r=0;for(const t of e){const e=t-o;r+=e*e}return{mean:o,sd:t>1?Math.sqrt(r/(t-1)):0}}function v(e,t){const n=new Set;for(let t=0;t<e.length;t++)n.add(t);const o=[];let r=NaN,s=NaN;if(!t)return({mean:r,sd:s}=w(e)),{mean:r,sd:s,includedCount:e.length,excludedIndices:[],iterationTrace:o};for(let t=1;t<=2;t++){const a=w(Array.from(n).map(t=>e[t]));if(r=a.mean,s=a.sd,!Number.isFinite(s)||0===s)break;const i=[];for(const t of n){const n=(e[t]-r)/s;Math.abs(n)>3&&i.push(t)}if(0===i.length)break;for(const e of i)n.delete(e);o.push({iter:t,dropped:i});const l=Array.from(n).map(t=>e[t]);({mean:r,sd:s}=w(l))}const a=[];for(let t=0;t<e.length;t++)n.has(t)||a.push(t);return{mean:r,sd:s,includedCount:n.size,excludedIndices:a,iterationTrace:o}}function _(e,t,n){e.setTag("proteomics.spc_metrics",JSON.stringify(t)),e.setTag("proteomics.spc_status",n.status),e.setTag("proteomics.spc_rules_tripped",JSON.stringify(n.rulesTripped));const o=function(e,t){return e.columns.contains(t)&&e.columns.remove(t),e.columns.addNewString(t)}(e,r),s=JSON.stringify({metrics:t,status:n.status,rulesTripped:n.rulesTripped});0!==e.rowCount&&o.set(0,s)}function C(e){if(!e.columns.contains(r))return null;const t=e.col(r);if(!t||0===e.rowCount)return null;const n=t.get(0);if("string"!=typeof n||0===n.length)return null;try{const e=JSON.parse(n);return e&&e.metrics?e.metrics:null}catch{return null}}},623(e,t,n){"use strict";n.d(t,{JO:()=>u,Jn:()=>s,Kf:()=>w,Pd:()=>h,ZF:()=>l,er:()=>m,n0:()=>y,y:()=>c});var o=n(328);const r={Nucleus:["nucleus","nuclear","nucleoplasm","chromatin","nucleolus","nuclear envelope","nuclear membrane","nuclear pore","nuclear speck","cajal body","nuclear body"],Cytoplasm:["cytoplasm","cytosol","cytoplasmic","cytoskeleton","microtubule","actin","intermediate filament","sarcomere","myofibril","z disc","z disk","spindle","centriole","centrosome","cilium","flagellum","stress fiber"],Mitochondria:["mitochondria","mitochondrial","mitochondrion","mitochondrial matrix","mitochondrial membrane","mitochondrial inner membrane","mitochondrial outer membrane","mitochondrial intermembrane space"],ER:["endoplasmic reticulum","sarcoplasmic reticulum","rough endoplasmic reticulum","smooth endoplasmic reticulum","er-golgi intermediate compartment","ergic"],Golgi:["golgi","trans-golgi","golgi apparatus","golgi membrane","cis-golgi","trans-golgi network","tgn"],"Plasma Membrane":["plasma membrane","cell membrane","cell surface","tight junction","gap junction","adherens junction","desmosome","focal adhesion","cell junction","synapse","postsynaptic","presynaptic","neuromuscular junction"],Lysosome:["lysosome","lysosomal","vacuole","lysosomal membrane","autophagosome","phagosome"],Peroxisome:["peroxisome","peroxisomal","glyoxysome"],Ribosome:["ribosome","ribosomal","ribosomal protein","polysome"],Extracellular:["extracellular","secreted","extracellular space","extracellular matrix","basement membrane","basal lamina","collagen","ecm"],Vesicles:["vesicle","endosome","transport vesicle","secretory vesicle","early endosome","late endosome","recycling endosome","clathrin-coated vesicle","coated vesicle"]},s={Nucleus:4278190080|parseInt("FF6B6B",16),Cytoplasm:4278190080|parseInt("ECDC44",16),Mitochondria:4278190080|parseInt("45B7D1",16),ER:4278190080|parseInt("96CEB4",16),Golgi:4278190080|parseInt("FAAFFE",16),"Plasma Membrane":4278190080|parseInt("DDA0DD",16),Lysosome:4278190080|parseInt("F39C12",16),Peroxisome:4278190080|parseInt("E17055",16),Ribosome:4278190080|parseInt("A29BFE",16),Extracellular:4278190080|parseInt("FD79A8",16),Vesicles:4278190080|parseInt("FDCB6E",16),Unknown:4278190080|parseInt("CCCCCC",16)};function a(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i(e){if(!e)return null;const t=e.toLowerCase();let n=null,o=1/0;for(const e of Object.keys(r))for(const s of r[e]){const r=new RegExp("\\b"+a(s)+"\\b","i").exec(t);r&&r.index<o&&(o=r.index,n=e)}return n}function l(e,t){const n=t??"";let o=i(e??"");return o||(o=i(n),o||"Unknown")}function c(e){const t=new Map,n=new Map,o=new Map,r=e.trim().split("\n");for(let e=1;e<r.length;e++){const s=r[e];if(!s)continue;const a=s.split("\t"),i=(a[0]??"").trim();if(!i)continue;const c=a[1]??"",u=a[2]??"",m="reviewed"===(a[3]??"").toLowerCase(),p=(a[4]??"").trim(),d=l(c,u);t.has(i)?m&&"Unknown"!==d?(t.set(i,d),o.set(i,!0)):"Unknown"===t.get(i)&&"Unknown"!==d&&(t.set(i,d),o.set(i,m)):(t.set(i,d),o.set(i,m)),!p||n.has(i)&&!m||n.set(i,p)}return{locByAcc:t,geneByAcc:n,reviewedByAcc:o}}const u={hsapiens:9606,mmusculus:10090,rnorvegicus:10116,scerevisiae:4932,ecoli:562,drerio:7955,dmelanogaster:7227,athaliana:3702,celegans:6239},m="proteomics-subcell-loc",p="13-04-1",d="__schema_v",f=new Set([...Object.keys(r),"Unknown"]);function g(e,t){const n=[];for(let o=0;o<e.length;o+=t)n.push(e.slice(o,o+t));return n}async function h(e,t,n){const o=new Array(e.length);let r=0;const s=Math.min(Math.max(1,t),e.length||1),a=[];for(let t=0;t<s;t++)a.push((async()=>{for(;;){const t=r++;if(t>=e.length)return;o[t]=await n(e[t],t)}})());return await Promise.all(a),o}async function y(e,t,n){const r=[...new Set(e.filter(e=>e&&e.length>0))],s=await async function(){try{const e=await o.dapi.userDataStorage.get(m)??{};return e[d]!==p?{[d]:p}:e}catch{return{[d]:p}}}(),a=new Map,i=[];for(const e of r){const t=s[e];void 0!==t&&f.has(t)?a.set(e,t):i.push(e)}const y=new Map,E={},w=function(e){const t=e?u[e]:void 0;return t?` AND (taxonomy_id:${t})`:""}(t),v=async()=>{if(0!==Object.keys(E).length)try{await o.dapi.userDataStorage.put(m,{...s,...E,[d]:p})}catch(e){console.warn(`Subcellular-location cache write failed: ${e?.message??e}`)}},_=setInterval(()=>{v().catch(()=>{})},5e3);try{const e=g(i,100),t=e.length;let s=0;await h(e,6,async e=>{const r=e.map(e=>`accession:${e}`).join(" OR "),i=`https://rest.uniprot.org/uniprotkb/stream?query=(${encodeURIComponent(r)})&fields=accession,cc_subcellular_location,go_c,reviewed,gene_primary&format=tsv`;try{const e=await o.dapi.fetchProxy(i);if(!e.ok)return void console.warn(`UniProt stream returned status ${e.status}; continuing`);const{locByAcc:t,geneByAcc:n}=c(await e.text());for(const[e,n]of t)a.set(e,n),E[e]=n;for(const[e,t]of n)y.set(e,t)}catch(e){console.warn(`UniProt stream batch failed: ${e?.message??e}; continuing`)}s++,n?.(s,t,"fetch-acc")});const u=new Map;for(const e of i){const t=a.get(e)??"Unknown",n=y.get(e);"Unknown"===t&&n&&(u.has(n)||u.set(n,[]),u.get(n).push(e))}const m=g([...u.keys()],20),p=m.length;let d=0;await h(m,6,async e=>{const t=e.map(e=>`gene_exact:${e}`).join(" OR "),r=`https://rest.uniprot.org/uniprotkb/stream?query=(${encodeURIComponent(t)}) AND (reviewed:true)${encodeURIComponent(w)}&fields=accession,gene_primary,cc_subcellular_location,go_c&format=tsv`;try{const e=await o.dapi.fetchProxy(r);if(!e.ok)return void console.warn(`UniProt gene fallback returned status ${e.status}; continuing`);const t=(await e.text()).trim().split("\n");for(let e=1;e<t.length;e++){const n=t[e].split("\t"),o=(n[1]??"").trim(),r=l(n[2]??"",n[3]??"");if(o&&"Unknown"!==r)for(const e of u.get(o)??[])a.set(e,r),E[e]=r}}catch(e){console.warn(`UniProt gene fallback batch failed: ${e?.message??e}; continuing`)}d++,n?.(d,p,"fetch-gene")});for(const e of r)a.has(e)||a.set(e,"Unknown"),void 0===E[e]&&(E[e]=a.get(e))}finally{clearInterval(_),await v()}const C=new Map;for(const e of r)C.set(e,a.get(e)??"Unknown");return C}const E=new Map;async function w(e){if(E.has(e))return E.get(e)??null;const t=`https://rest.uniprot.org/uniprotkb/${encodeURIComponent(e)}.json?fields=accession,protein_name,gene_names,organism_name,cc_function,go`;try{const n=await o.dapi.fetchProxy(t);if(!n.ok)return console.warn(`UniProt fetch for ${e} returned status ${n.status}`),E.set(e,null),null;const r=await n.json();return E.set(e,r),r}catch(t){return console.warn(`UniProt fetch for ${e} failed:`,t?.message??t),null}}},110(e,t,n){"use strict";n.d(t,{_package:()=>J,dockComparisonFilterIfMultiContrast:()=>oe,openCandidatesAnalysisView:()=>re,sniffIsPrecursor:()=>ee});var o=n(328),r=n(389),s=n(82),a=n(713),i=n(312),l=n(53),c=n(86),u=n(119),m=n(641),p=n(304);const d=["primary protein id","pg.proteingroups","protein id","uniprot","accession"];function f(e,t=0){if(0===e.rowCount||t<0||t>=e.rowCount)return;const n=(0,p.k)(e,m.iu.PROTEIN_ID,d);n&&(e.currentCell=e.cell(t,n.name),o.shell.windows.showContextPanel=!0,async function(){const e=["Proteomics","UniProt"];for(let t=0;t<12;t++){await new Promise(e=>setTimeout(e,250));try{const t=document.querySelector('[d4-title="semantic meta.Proteomics-ProteinId"]');if(!t)continue;let n=!0;for(const o of e){const e=Array.from(t.querySelectorAll(".d4-accordion-pane-header")).find(e=>e.textContent?.trim()===o);e?e.classList.contains("expanded")||(e.click(),n=!1):n=!1}if(n)return}catch{}}}())}var g=n(954),h=n(117);function y(){s.Utils.openFile({accept:".csv,.tsv,.txt",open:e=>{const t=new FileReader;t.onload=()=>{try{const n=t.result,a=(0,g.T6)(n);!function(e,t){const n=(0,g.q2)(e),a=(0,g.YL)(e),i=(0,g.WI)(e),l=r.input.column("Protein ID",{table:e,filter:e=>e.type===s.COLUMN_TYPE.STRING,value:n??void 0}),c=r.input.column("Gene Name (optional)",{table:e,filter:e=>e.type===s.COLUMN_TYPE.STRING,value:a??void 0,nullable:!0}),u=e.columns.toList().filter(e=>e.type===s.COLUMN_TYPE.FLOAT||e.type===s.COLUMN_TYPE.INT||e.type===s.COLUMN_TYPE.BIG_INT).map(e=>e.name),p=r.input.columns("Intensity Columns",{table:e,available:u,value:i.map(t=>e.col(t)).filter(e=>null!=e)}),d=(0,g.eY)(e,i),y=r.input.bool("Log2 Transform",{value:!d.isLog2}),E=r.divText(d.message);E.style.cssText="font-style:italic;color:#888;margin-bottom:8px;font-size:12px;";const w=document.createElement("div");function v(){const t=[],n=l.value;n&&t.push(n.name);const o=c.value;o&&t.push(o.name);const a=(p.value??[]).map(e=>e.name);if(t.push(...a),0!==t.length)try{const n=s.BitSet.create(e.rowCount,e=>e<5),o=e.clone(n,t),a=s.Viewer.grid(o);w.innerHTML="";const i=r.divText(`Preview: ${t.length} columns, 5 rows`);i.style.cssText="font-size:11px;color:#888;padding:2px 4px;",a.root.style.cssText="width:100%;height:180px;",w.appendChild(i),w.appendChild(a.root)}catch{w.innerHTML='<div style="padding:8px;color:#888">Unable to generate preview</div>'}else w.innerHTML='<div style="padding:8px;color:#888">Select columns to preview</div>'}w.style.cssText="border:1px solid #ddd;margin-top:8px;width:100%;",l.onChanged.subscribe(()=>v()),c.onChanged.subscribe(()=>v()),p.onChanged.subscribe(()=>{(function(){const t=(p.value??[]).map(e=>e.name);if(0===t.length)return void(E.textContent="Select intensity columns");const n=(0,g.eY)(e,t);E.textContent=n.message,y.value=!n.isLog2})(),v()}),v(),r.dialog("Import Generic Matrix").add(l).add(c).add(p).add(y).add(r.div([E])).add(w).onOK(async()=>{const n=l.value;if(!n)return void o.shell.warning("Please select a Protein ID column");const r=(p.value??[]).map(e=>e.name);if(0===r.length)return void o.shell.warning("Please select at least one intensity column");n.semType=m.iu.PROTEIN_ID;const s=c.value;s&&(s.semType=m.iu.GENE_SYMBOL),y.value?(0,g.Kh)(e,r):(0,g.l3)(e,r),(0,g.wK)(e,n.name,"Primary Protein ID",m.iu.PROTEIN_ID),s&&(0,g.wK)(e,s.name,"Primary Gene Name",m.iu.GENE_SYMBOL),e.setTag("proteomics.source","generic"),await(0,h.rv)(e),e.name=t.replace(/\.[^.]+$/,""),o.shell.addTableView(e),o.shell.info(`Imported ${e.rowCount} proteins from ${t}`),f(e)}).show()}(s.DataFrame.fromCsv(n,{delimiter:a}),e.name)}catch(e){o.shell.error("Failed to parse file: "+e.message)}},t.readAsText(e)}})}var E=n(252),w=n(935),v=n(655),_=n(883),C=n(350),b=n(871),T=n(989),P=n(47),S=n(829),N=n(70),A=n(623);async function x(e,t){const n=t?.topN??50,o=t?.labelCol??"Gene Name";if("true"!==e.getTag("proteomics.de_complete"))throw new Error("Differential expression must be run first");const r=(0,E.f)(e);if(!r)throw new Error("Experimental groups must be annotated first");const a=e.col("adj.p-value");if(!a)throw new Error("adj.p-value column not found");const i=[];for(let t=0;t<e.rowCount;t++)a.isNone(t)||i.push({idx:t,pVal:a.get(t)});i.sort((e,t)=>e.pVal-t.pVal);const l=new Set;for(let e=0;e<Math.min(n,i.length);e++)l.add(i[e].idx);const c=s.BitSet.create(e.rowCount);for(const e of l)c.set(e,!0);const u=e.clone(c),d=[...r.group1.columns,...r.group2.columns],f=[];for(const t of d){const n=`_zscore_${t}`;f.push(n);const o=e.col(t);if(!o)continue;const r=o.getRawData();let a=0,i=0,l=0;for(let t=0;t<e.rowCount;t++){const e=r[t];e!==s.FLOAT_NULL&&(a+=e,i+=e*e,l++)}const c=l>0?a/l:0,m=l>1?(i-a*a/l)/(l-1):0,p=Math.sqrt(m),d=u.col(t);if(!d)continue;const g=d.getRawData();u.columns.addNewFloat(n).init(e=>{return g[e]===s.FLOAT_NULL?s.FLOAT_NULL:(t=g[e],(n=p)>0?(t-c)/n:0);var t,n})}const g=u.plot.grid();for(let e=0;e<g.columns.length;e++){const t=g.columns.byIndex(e);t&&(t.visible=!1)}const h=(0,p.k)(u,m.iu.GENE_SYMBOL,[o.toLowerCase(),"gene symbol"])??(0,p.k)(u,m.iu.PROTEIN_ID,["protein id","majority protein id","accession"]);if(h){const e=g.columns.byName(h.name);e&&(e.visible=!0)}const y=r.group1.columns.map(e=>`_zscore_${e}`),w=r.group2.columns.map(e=>`_zscore_${e}`);for(const e of[...y,...w]){const t=g.columns.byName(e);t&&(t.visible=!0)}let v=!1;const _=s.TaskBarProgressIndicator.create("Calculating distance matrix...");try{const e=s.Func.find({package:"Dendrogram",name:"hierarchicalClustering"})[0];if(!e)throw new Error("Dendrogram package not installed (hierarchicalClustering not found)");if(4!==e.inputs.length)throw new Error(`Dendrogram.hierarchicalClustering signature changed (expected 4 inputs, got ${e.inputs.length})`);await e.apply({df:g,colNameList:f,distance:"euclidean",linkage:"complete"}),v=!0}catch(e){console.warn(`Dendrogram clustering unavailable, falling back to significance-based row ordering: ${e?.message??e}`)}finally{_.close()}if(!v){const e=u.col("adj.p-value")?"adj.p-value":u.col("adj.p.value")?"adj.p.value":null;e&&g.sort([e])}return g.props.isHeatmap=!0,g.props.isGrid=!1,t?.title&&g.setOptions({title:t.title}),g}const D=["#2196F3","#FF5722"];function L(e,t,n=64){const o=e.length;if(o<3)return null;let r=0,s=0;for(let n=0;n<o;n++)r+=e[n],s+=t[n];r/=o,s/=o;let a=0,i=0,l=0;for(let n=0;n<o;n++){const o=e[n]-r,c=t[n]-s;a+=o*o,i+=o*c,l+=c*c}a/=o-1,i/=o-1,l/=o-1;const c=a+l,u=a*l-i*i,m=Math.sqrt(Math.max(c*c/4-u,0)),p=c/2+m,d=c/2-m;if(p<=0||d<=0)return null;let f;f=Math.abs(i)>1e-12?Math.atan2(p-a,i):a>=l?0:Math.PI/2;const g=Math.sqrt(5.991*p),h=Math.sqrt(5.991*d),y=[],E=Math.cos(f),w=Math.sin(f);for(let e=0;e<n;e++){const t=2*Math.PI*e/n,o=g*Math.cos(t),a=h*Math.sin(t),i=r+E*o-w*a,l=s+w*o+E*a;y.push([i,l])}return y}function F(e,t,n,o){const{pcaDf:r,varianceExplained:a}=function(e,t,n,o=2){const r=t.length,a=e.rowCount,i=[],l=new Array(a).fill(0),c=new Array(a).fill(0);for(const n of t){const t=e.col(n);if(t)for(let e=0;e<a;e++)t.isNone(e)||(l[e]+=t.get(e),c[e]++)}for(let e=0;e<a;e++)l[e]=c[e]>0?l[e]/c[e]:0;for(const n of t){const t=e.col(n),o=new Array(a);for(let e=0;e<a;e++)!t||t.isNone(e)?o[e]=l[e]:o[e]=t.get(e);i.push(o)}const u=new Array(a).fill(0);for(let e=0;e<a;e++){for(let t=0;t<r;t++)u[e]+=i[t][e];u[e]/=r}for(let e=0;e<r;e++)for(let t=0;t<a;t++)i[e][t]-=u[t];const m=function(e,t,n){const o=[];for(let r=0;r<n;r++){const n=new Array(t);for(let o=0;o<t;o++)n[o]=e[o][r];o.push(n)}return o}(i,r,a),p=function(e,t,n,o,r){const s=[];for(let a=0;a<n;a++){const n=new Array(r).fill(0);for(let s=0;s<o;s++){const o=e[a][s];for(let e=0;e<r;e++)n[e]+=o*t[s][e]}s.push(n)}return s}(i,m,r,a,r),d=a>1?a-1:1;for(let e=0;e<r;e++)for(let t=0;t<r;t++)p[e][t]/=d;const{eigenvalues:f,eigenvectors:g}=function(e,t){const n=e.map(e=>[...e]),o=[];for(let e=0;e<t;e++){const n=new Array(t).fill(0);n[e]=1,o.push(n)}let r=!1;for(let e=0;e<100;e++){let e=0,s=0,a=1;for(let o=0;o<t;o++)for(let r=o+1;r<t;r++)Math.abs(n[o][r])>e&&(e=Math.abs(n[o][r]),s=o,a=r);if(e<1e-10){r=!0;break}const i=(n[a][a]-n[s][s])/(2*n[s][a]),l=Math.sign(i)/(Math.abs(i)+Math.sqrt(i*i+1)),c=1/Math.sqrt(l*l+1),u=l*c,m=n[s][s],p=n[a][a],d=n[s][a];n[s][s]=c*c*m-2*u*c*d+u*u*p,n[a][a]=u*u*m+2*u*c*d+c*c*p,n[s][a]=0,n[a][s]=0;for(let e=0;e<t;e++)if(e!==s&&e!==a){const t=n[e][s],o=n[e][a];n[e][s]=c*t-u*o,n[s][e]=n[e][s],n[e][a]=u*t+c*o,n[a][e]=n[e][a]}for(let e=0;e<t;e++){const t=o[e][s],n=o[e][a];o[e][s]=c*t-u*n,o[e][a]=u*t+c*n}}r||console.warn(`PCA Jacobi did not converge in 100 iterations (n=${t}); results may be approximate`);const s=new Array(t);for(let e=0;e<t;e++)s[e]=n[e][e];const a=Array.from({length:t},(e,t)=>t);a.sort((e,t)=>s[t]-s[e]);const i=a.map(e=>s[e]),l=[];for(let e=0;e<t;e++){const n=new Array(t);for(let r=0;r<t;r++)n[r]=o[e][a[r]];l.push(n)}return{eigenvalues:i,eigenvectors:l}}(p,r),h=[];for(let e=0;e<r;e++){const t=[];for(let n=0;n<Math.min(o,r);n++){const o=f[n]>0?Math.sqrt(f[n]):0;t.push(g[e][n]*o)}h.push(t)}const y=f.reduce((e,t)=>e+Math.max(t,0),0),E=[];for(let e=0;e<Math.min(o,r);e++){const t=y>0?Math.max(f[e],0)/y*100:0;E.push(Math.round(10*t)/10)}const w=E.length>0&&isFinite(E[0])?E[0]:0,v=r>=2?`PC1 (${w}%)`:"PC1",_=E.length>=2&&isFinite(E[1])?E[1]:0,C=o>=2&&E.length>=2&&r>=2?`PC2 (${_}%)`:"PC2",b=[s.Column.fromStrings("SampleName",t),s.Column.fromFloat32Array(v,new Float32Array(h.map(e=>e[0])))];if(o>=2){const e=s.Column.fromFloat32Array(C,new Float32Array(h.map(e=>e.length>1?e[1]:0)));b.push(e)}const T=t.map(e=>n.group1.columns.includes(e)?n.group1.name:n.group2.columns.includes(e)?n.group2.name:"Unknown"),P=s.Column.fromStrings("Group",T);b.push(P);const S=s.DataFrame.fromColumns(b);return S.name="PCA",{pcaDf:S,varianceExplained:E}}(e,t,n),i=r.columns.toList().find(e=>e.name.startsWith("PC1"))?.name,l=r.columns.toList().find(e=>e.name.startsWith("PC2"))?.name;if(!i||!l)throw new Error("PCA did not produce PC1/PC2 columns — too few samples?");const c=r.plot.scatter({x:i,y:l,color:"Group"});c.props.labelColumnNames=["SampleName"],c.props.displayLabels="Always";try{const e=r.col(i),t=r.col(l),o=r.col("Group"),s=[n.group1.name,n.group2.name];for(let n=0;n<s.length;n++){const a=s[n],u=[],m=[];for(let n=0;n<r.rowCount;n++)o.get(n)===a&&(u.push(e.get(n)),m.push(t.get(n)));const p=L(u,m);if(p){const e=D[n%D.length],t={type:"area",area:p,fillColor:e,opacity:.15,outlineColor:e,outlineWidth:1,x:i,y:l};c.meta.annotationRegions?.add(t)}}}catch(e){console.warn("PCA: could not add confidence ellipses:",e?.message??e)}return o&&c.setOptions({title:o}),{viewer:c,pcaDf:r}}var I=n(715);const M=["M","A","MA_trend","CV_group1","meanInt_group1","CV_group2","meanInt_group2"];function O(e){const t=s.TaskBarProgressIndicator.create("Creating QC dashboard...");try{const t=(0,E.f)(e);if(!t)return void o.shell.warning("Annotate experimental groups first (Proteomics | Annotate Experiment)");for(const t of M)e.columns.contains(t)&&e.columns.remove(t);const n=(0,I.Hc)(e);if(0===n.length)return void o.shell.warning("No log2 intensity columns found");(0,I.iQ)(e,t),(0,I.Pq)(e),(0,I.JZ)(e,t.group1.columns,"CV_group1","meanInt_group1"),(0,I.JZ)(e,t.group2.columns,"CV_group2","meanInt_group2");const r=o.shell.tv;if(!r)return void o.shell.warning("No table view open");const a={xColumnName:"A",yColumnName:"M",title:"MA Plot",markerDefaultSize:2};if("true"===e.getTag("proteomics.de_complete"))try{const t=(0,N.EO)(e,m.M5,m.Dx);a.colorColumnName=t}catch(e){}const i=r.addViewer(s.VIEWER.SCATTER_PLOT,a),l="${M} = 0";e.meta.formulaLines.items=e.meta.formulaLines.items.filter(e=>e.formula!==l),e.meta.formulaLines.addLine({formula:l,color:"#888888",width:1,visible:!0});const c=r.addViewer(s.VIEWER.SCATTER_PLOT,{xColumnName:"A",yColumnName:"MA_trend",title:"MA Trend",markerDefaultSize:1}),u=r.addViewer(s.VIEWER.SCATTER_PLOT,{xColumnName:"meanInt_group1",yColumnName:"CV_group1",title:"CV Plot",markerDefaultSize:2}),p=r.addViewer(s.VIEWER.CORR_PLOT,{xColumnNames:n,yColumnNames:n,title:"Sample Correlation"}),d=(0,I.ho)(e,n),f=s.Viewer.grid(d);f.props.allowColSelection=!1;const g=(0,I.rA)(e,n,t),h=s.Viewer.barChart(g,{splitColumnName:"Sample",valueColumnName:"MissingPct",stackColumnName:"Group"}),y=(0,I.j4)(e,n),w=s.Viewer.boxPlot(y,{valueColumnName:"Intensity",categoryColumnName:"Sample"}),v=r.dockManager,_=v.dock(i,s.DOCK_TYPE.RIGHT,null,"MA Plot",.75);v.dock(c,s.DOCK_TYPE.FILL,_,"MA Trend"),v.dock(u,s.DOCK_TYPE.FILL,_,"CV Plot");const C=v.dock(p,s.DOCK_TYPE.DOWN,_,"Sample Correlation",.5);v.dock(w,s.DOCK_TYPE.FILL,C,"Intensity Distributions"),v.dock(h,s.DOCK_TYPE.FILL,C,"Missing % per Sample"),v.dock(f,s.DOCK_TYPE.FILL,C,"Missing Values");const b=e=>{try{const t=v.findNode(e.root);t?.parent&&t.parent.container.setActiveChild(t.container)}catch{}};b(i),b(p)}finally{t.close()}}var R=n(589),G=n(644),k=n(498),$=n(771);function B(e){if(null==e)return"unknown date";try{if(e instanceof Date)return Number.isNaN(e.getTime())?"unknown date":e.toISOString().slice(0,10);const t=new Date(e);return Number.isNaN(t.getTime())?"unknown date":t.toISOString().slice(0,10)}catch{return"unknown date"}}function U(e,t){const n=r.divText(e);n.style.fontWeight="600",n.style.fontSize="12px",n.style.color="#666";const o=r.divText(t);o.style.marginBottom="8px";const s=r.div([n,o]);return s.style.marginBottom="6px",s}var j=n(807),V=n(637);var q=n(649),Y=n(230),z=n(897);const H=["Import","Annotate Experiment...","Analyze","Visualize","Share"];var Q=function(e,t,n,o){var r,s=arguments.length,a=s<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,o);else for(var i=e.length-1;i>=0;i--)(r=e[i])&&(a=(s<3?r(a):s>3?r(t,n,a):r(t,n))||a);return s>3&&a&&Object.defineProperty(t,n,a),a},W=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},K=function(e,t){return function(n,o){t(n,o,e)}};const J=new s.Package;function Z(e,t){return"spectronaut-candidates"!==e.getTag("proteomics.source")||(o.shell.warning(`${t} needs per-sample intensities, but this table is a Spectronaut Candidates report (one row per protein per comparison — pre-computed DE only). Import the matching Spectronaut Report (Proteomics | Import | Spectronaut Report) to enable per-sample analyses, or stick to Volcano / Enrichment / UniProt panel on this one.`),!1)}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","treeBrowser","polyfill"].forEach(e=>{o.decorators[e]||(o.decorators[e]=function(e){return function(e,t,n){}})});const X=["EG.ModifiedPeptide","FG.Charge","PEP.StrippedSequence"];async function ee(e){const t=e.stream().pipeThrough(new TextDecoderStream("utf-8")).getReader();try{let e="";const n=1048576;for(;e.indexOf("\n")<0&&e.length<n;){const{value:n,done:o}=await t.read();if(o)break;e+=n}const o=e.indexOf("\n");let r=o>=0?e.slice(0,o):e;return r.endsWith("\r")&&(r=r.slice(0,-1)),X.some(e=>r.includes(e))}finally{await t.cancel()}}let te=[];function ne(e){if((0,E.Di)(e))return;const t=(0,w.Vr)(e);t&&(0,E.Np)(e,t)}function oe(e,t){const n=c.g.reduce((e,n)=>e??t.col(n),null);if(!n)return!1;const o=new Set;for(let e=0;e<t.rowCount;e++){const t=n.get(e);"string"==typeof t&&t.length>0&&o.add(t)}if(o.size<=1)return!1;const r=(0,p.k)(t,m.iu.DISPLAY_NAME,["display name"]),i=(0,p.k)(t,m.iu.SOURCE_ID,["source id"]),l=(0,p.k)(t,m.iu.PROTEIN_ID,["primary protein id","protein id","uniprot","accession"]),u=[n.name];r&&u.push(r.name),i&&u.push(i.name),!r&&l&&u.push(l.name);const d=s.Viewer.filters(t,{columnNames:u,showBoolCombinedFilter:!1,showHeader:!0,showSearchBox:!0});e.dockManager.dock(d,s.DOCK_TYPE.RIGHT,null,"Filters",.3);for(const e of te)e.unsubscribe();te=[];const f=s.BitSet.create(t.rowCount);f.copyFrom(t.filter);let g=!1;return te.push(t.onFilterChanged.pipe((0,a.debounceTime)(100)).subscribe(()=>{if(g)return;const n=[];for(let e=0;e<t.rowCount;e++)t.filter.get(e)&&n.push(e);if(n.length===t.rowCount)return void f.copyFrom(t.filter);g=!0;try{t.filter.copyFrom(f)}finally{g=!1}t.selection.setAll(!1,!1);for(const e of n)t.selection.set(e,!0,!1);t.selection.fireChanged();const o=(()=>{for(const t of e.viewers)if(t.type===s.VIEWER.SCATTER_PLOT&&"negLog10P"===t.props.yColumnName)return t;return null})();o&&(0,N.XC)(t,o,(0,N.m2)(t),n)})),!0}function re(e){const t=o.shell.addTableView(e);o.shell.info(`Imported ${e.rowCount} candidates from Spectronaut`);try{t.addViewer((0,N.gO)(e))}catch(e){o.shell.warning(`Imported, but could not auto-open the volcano: ${e?.message??e}. Open it via Proteomics | Visualize | Volcano Plot.`)}return oe(t,e),f(e),t}class se{static async initProteomics(){}static async buildProteomicsTopMenu(){const e={importSpectronautCandidates:()=>se.importSpectronautCandidates(),importSpectronaut:()=>se.importSpectronaut(),importMaxQuant:()=>se.importMaxQuant(),importFragPipe:()=>se.importFragPipe(),importGenericMatrix:()=>se.importGenericMatrix(),annotateExperiment:()=>se.annotateExperiment(),setLog2Scale:()=>se.setLog2Scale(),normalize:()=>se.normalizeProteomics(),impute:()=>se.imputeMissingValues(),differentialExpression:()=>se.differentialExpression(),enrichmentAnalysis:()=>se.enrichmentAnalysis(),exportEnrichmentInputs:()=>se.exportEnrichmentInputs(),computeSpcStatus:()=>se.computeSpcStatus(),showVolcanoPlot:()=>se.showVolcanoPlot(),showHeatmap:()=>se.showHeatmap(),showPcaPlot:()=>se.showPcaPlot(),showGroupMeanCorrelation:()=>se.showGroupMeanCorrelation(),showQcDashboard:()=>se.showQcDashboard(),showSpcDashboard:()=>se.showSpcDashboard(),enrichmentCharts:()=>se.enrichmentCharts(),showAllVisualizations:()=>se.showAllVisualizations(),shareAnalysisForReview:()=>se.shareAnalysisForReview()},t=new WeakSet,n=n=>{n?.type!==s.VIEW_TYPE.TABLE_VIEW||t.has(n)||setTimeout(()=>{if(!t.has(n))try{(function(e,t){if(!(n=e.dataFrame)||!n.getTag("proteomics.source"))return!1;var n;const o=e.ribbonMenu.group("Proteomics");for(const e of H)try{o.remove(e)}catch{}const r={isEnabled:()=>function(e){return e&&"spectronaut-candidates"===e.getTag("proteomics.source")?"Not applicable to a Spectronaut Candidates file — it already carries computed differential expression and has no per-sample intensities. Use Volcano Plot, Enrichment Analysis or the UniProt panel, or import the matching Spectronaut Report for sample-level analyses.":null}(e.dataFrame)},s=o.group("Import");s.item("Spectronaut Candidates...",t.importSpectronautCandidates),s.item("Spectronaut Report...",t.importSpectronaut),s.item("MaxQuant...",t.importMaxQuant),s.item("FragPipe...",t.importFragPipe),s.item("Generic Matrix...",t.importGenericMatrix),o.item("Annotate Experiment...",t.annotateExperiment,null,r);const a=o.group("Analyze");a.item("Set Log2 Scale...",t.setLog2Scale,null,r),a.item("Normalize...",t.normalize,null,r),a.item("Impute Missing Values...",t.impute,null,r),a.item("Differential Expression...",t.differentialExpression,null,r),a.item("Enrichment Analysis...",t.enrichmentAnalysis),a.item("Export Enrichment Inputs...",t.exportEnrichmentInputs),a.item("Compute SPC Status",t.computeSpcStatus,null,r);const i=o.group("Visualize");return i.item("Volcano Plot...",t.showVolcanoPlot),i.item("Heatmap...",t.showHeatmap,null,r),i.item("PCA...",t.showPcaPlot,null,r),i.item("Group-Mean Correlation...",t.showGroupMeanCorrelation,null,r),i.item("QC Dashboard...",t.showQcDashboard,null,r),i.item("SPC Dashboard...",t.showSpcDashboard),i.item("Enrichment Charts...",t.enrichmentCharts),i.item("Show All Visualizations...",t.showAllVisualizations,null,r),o.group("Share").item("Share Analysis for Review...",t.shareAnalysisForReview),!0})(n,e)&&t.add(n)}catch{}},50)};try{for(const e of o.shell.views)n(e)}catch{}o.events.onViewAdded.subscribe(n),o.events.onCurrentViewChanged.subscribe(()=>n(o.shell.v))}static async importSpectronautCandidates(){s.Utils.openFile({accept:".tsv,.txt,.csv",open:async e=>{try{const t=await e.text(),n=await(0,c.R)(t);n.name=e.name.replace(/\.[^.]+$/,""),ne(n),re(n)}catch(e){o.shell.error(`Failed to import Spectronaut Candidates file: ${e?.message??e}`)}}})}static async importSpectronaut(){s.Utils.openFile({accept:".tsv,.txt,.csv",open:async e=>{try{const t=await ee(e)?await(0,l.A)(e):await(0,l.parseSpectronautText)(await e.text());t.name=e.name.replace(/\.[^.]+$/,""),ne(t),o.shell.addTableView(t),o.shell.info(`Imported ${t.rowCount} protein groups from Spectronaut`),f(t)}catch(e){o.shell.error(`Failed to import Spectronaut file: ${e?.message??e}`),o.shell.warning("If this is a very large precursor-level Spectronaut report that fails to stream in-browser, pre-aggregate it to the importable protein-group shape with the bundled duckdb fallback: tools/spectronaut-aggregate.sh <input.tsv>, then re-import the resulting file. See files/demo/README.md for usage.")}}})}static async importMaxQuant(){s.Utils.openFile({accept:".txt,.tsv",open:async e=>{try{const t=await e.text(),n=await(0,i.E)(t);n.name=e.name.replace(/\.[^.]+$/,""),ne(n),o.shell.addTableView(n),o.shell.info(`Imported ${n.rowCount} protein groups`),f(n)}catch(e){o.shell.error(`Failed to import MaxQuant file: ${e?.message??e}`)}}})}static async importFragPipe(){s.Utils.openFile({accept:".tsv,.txt",open:async e=>{try{const t=await e.text(),n=await(0,u.p)(t);n.name=e.name.replace(/\.[^.]+$/,""),ne(n),o.shell.addTableView(n),o.shell.info(`Imported ${n.rowCount} protein groups from FragPipe`),f(n)}catch(e){o.shell.error(`Failed to import FragPipe file: ${e?.message??e}`)}}})}static async importGenericMatrix(){y()}static async annotateExperiment(){const e=o.shell.tv?.dataFrame;e?Z(e,"Annotate Experiment")&&(0,E.XX)(e):o.shell.warning("No table open")}static async setLog2Scale(){const e=o.shell.tv?.dataFrame;e?Z(e,"Set Log2 Scale")&&(0,b.Kb)(e):o.shell.warning("No table open")}static async normalizeProteomics(){const e=o.shell.tv?.dataFrame;e?Z(e,"Normalize")&&(0,C.v5)(e):o.shell.warning("No table open")}static async imputeMissingValues(){const e=o.shell.tv?.dataFrame;e?Z(e,"Impute Missing Values")&&(0,P.UN)(e):o.shell.warning("No table open")}static async differentialExpression(){const e=o.shell.tv,t=e?.dataFrame;e&&t?Z(t,"Differential Expression")&&(0,S.B9)(t,()=>{const n=(0,N.gO)(t);e.addViewer(n)}):o.shell.warning("No table open")}static async computeSpcStatus(){const e=o.shell.tv,t=e?.dataFrame;if(!e||!t)return void o.shell.warning("Open an analyzed file first, then run Compute SPC Status.");if("spectronaut-candidates"===t.getTag("proteomics.source"))return void o.shell.warning("SPC requires per-sample intensities. Re-import this analysis from the Spectronaut PG report (not the Candidates report) to compute SPC.");const n=(0,v.getRunMeta)(t);if(!n||!n.instrument_id||!n.acquisition_datetime)return void o.shell.warning("Open Annotate Experiment to set instrument + acquisition datetime.");const r=(0,E.f)(t);if(!r)return void o.shell.warning("Annotate experimental groups first (Proteomics → Annotate Experiment) — SPC needs Group 1 to compute control-replicate correlation.");r.group1.columns.length<2&&o.shell.info("Group 1 has fewer than 2 samples — control-replicate correlation can't be computed. The other three metrics will still be recorded.");const a=s.TaskBarProgressIndicator.create("Computing SPC status...");try{const e=(0,v.computeSpcMetrics)(t,r,n),s=await(0,_.loadBaseline)(n.instrument_id),a=await(0,_.loadRuns)(n.instrument_id),i=a.find(e=>e.acquisition_datetime===n.acquisition_datetime),l=i?.status??null;let c;if(null===s)c={status:"pass",rulesTripped:[]},o.shell.info(`No baseline locked for ${n.instrument_id} yet — recorded as pass. Define a baseline once at least 4 runs have been computed.`);else{const t={median_intensity:a.map(e=>e.median_intensity),missing_pct:a.map(e=>e.missing_pct),control_corr:a.map(e=>e.control_corr),protein_count:a.map(e=>e.protein_count)};c=(0,v.uV)(e,t,s.metrics,s.rules_enabled??(0,v.kY)())}(0,v.setSpcStatus)(t,e,c);const u={instrument_id:n.instrument_id,acquisition_datetime:n.acquisition_datetime,run_label:t.name,median_intensity:e.median_intensity,missing_pct:e.missing_pct,control_corr:e.control_corr,protein_count:e.protein_count,status:c.status,rules_tripped:c.rulesTripped,source_project_id:null,source_df_name:t.name,computed_at:e.computed_at};await(0,_.upsertRun)(u),null!==l?o.shell.info(`Updated SPC for ${t.name} (previous status: ${l}).`):"pass"===c.status?o.shell.info(`SPC computed: ${t.name} — status: pass.`):"flagged"===c.status?o.shell.info(`SPC computed: ${t.name} — flagged on ${c.rulesTripped.length} rule(s): ${c.rulesTripped.join(", ")}.`):o.shell.info(`SPC computed: ${t.name} — OUT OF CONTROL on ${c.rulesTripped.length} rule(s): ${c.rulesTripped.join(", ")}.`)}finally{a.close()}}static async showVolcanoPlot(){const e=o.shell.tv,t=e?.dataFrame;e&&t?(0,S.RJ)(t,"Run Differential Expression first (Proteomics | Analyze | Differential Expression)")&&await se.volcanoOptions():o.shell.warning("No table open")}static async volcanoOptions(e){const t=o.shell.tv,n=t?.dataFrame;if(!t||!n)return void o.shell.warning("No table open");if(!(0,S.RJ)(n,"Run Differential Expression first (Proteomics | Analyze | Differential Expression)"))return;let a=e;if(!a)for(const e of t.viewers)if(e.type===s.VIEWER.SCATTER_PLOT&&"negLog10P"===e.props.yColumnName){a=e;break}const i=a?(0,N.ur)(n,a):{metric:"adj.p-value",colorDim:"significance"},l=null!=n.col("p-value"),c=l?i.metric:"adj.p-value",u=r.input.choice("Significance metric",{value:c,items:l?["adj.p-value","p-value"]:["adj.p-value"],nullable:!1});u.setTooltip(l?"Y axis, classification and threshold line all switch together":"p-value column not present — only adj.p-value is available");const p=r.input.choice("Color by",{value:i.colorDim,items:["significance","location"],nullable:!1});p.setTooltip("significance = Enriched in g1 / Enriched in g2 / Not significant; location = UniProt subcellular location");const d=r.input.int("Label top N points",{value:(0,N.m2)(n),min:0});d.setTooltip("How many of the most significant proteins get name labels. 0 = none. Labels no longer touch your row selection.");const f=(0,N.GE)(n),g=r.input.float("X-axis max (|log2FC|)",{value:f.xMax??void 0,min:0,nullable:!0});g.setTooltip("Pin the X axis to ±this |log2FC|. Leave empty to auto-scale. Set the same value on two volcanoes to compare them side-by-side.");const h=r.input.float("Y-axis max (−log10 p)",{value:f.yMax??void 0,min:0,nullable:!0});h.setTooltip("Pin the Y axis to 0…this −log10(p). Leave empty to auto-scale. Set the same value on two volcanoes to compare them side-by-side."),r.dialog("Volcano Options").add(u).add(p).add(d).add(g).add(h).onOK(async()=>{const e=u.value??"adj.p-value",r="location"===p.value?"location":"significance";if((0,N.S6)(n,g.value??null,h.value??null),a||(a=(0,N.gO)(n,{topNLabels:0}),t.addViewer(a)),"location"===r&&!n.col(N.fQ)){const e=await o.dapi.userDataStorage.get(A.er).catch(()=>null);0===(e?Object.keys(e).filter(e=>"__schema_v"!==e).length:0)?o.shell.info("Fetching subcellular locations from UniProt — may take a minute or two on first use without cache; subsequent toggles use the cache."):o.shell.info("Resolving subcellular locations from cache.")}const i="location"===r?"Classifying subcellular locations…":"Updating volcano…",l=s.TaskBarProgressIndicator.create(i),c="location"===r;c&&(0,N.DI)(a,i);const f=(e,t,n)=>{const o="fetch-acc"===n?"Fetching subcellular locations":"fetch-gene"===n?"Resolving by gene name":"init-column"===n||"location"===r?"Classifying subcellular locations":"Updating volcano",s=t>0?Math.round(e/t*100):0;if(l.update(s,`${o}: ${e}/${t}`),c){const n=t>1?`${e}/${t} (${s}%)`:"";(0,N.Bb)(a,o,n)}};try{await(0,N.nj)(n,a,e,r,m.M5,m.Dx,f),(0,N.XC)(n,a,d.value??(0,N.m2)(n))}catch(e){o.shell.error(`Volcano update failed: ${e?.message??e}`)}finally{l.close(),c&&a&&(0,N.kX)(a)}}).show()}static async showHeatmap(){const e=o.shell.tv,t=e?.dataFrame;if(!e||!t)return void o.shell.warning("No table open");if(!Z(t,"Heatmap"))return;if(!(0,S.RJ)(t,"Run Differential Expression first (Proteomics | Analyze | Differential Expression)"))return;const n=r.input.int("Top N proteins",{value:50,min:1});n.setTooltip("How many of the most significant proteins (by adj. p-value) to show."),r.dialog("Heatmap Options").add(n).onOK(async()=>{const o=n.value??50,r=s.TaskBarProgressIndicator.create("Creating heatmap...");try{const n=await x(t,{topN:o,title:`Heatmap: Top ${o} DE Proteins`});e.addViewer(n)}finally{r.close()}}).show()}static async showPcaPlot(){const e=o.shell.tv,t=e?.dataFrame;if(!e||!t)return void o.shell.warning("No table open");if(!Z(t,"PCA"))return;const n=(0,E.f)(t);if(!n)return void o.shell.warning("Annotate experimental groups first (Proteomics | Annotate Experiment)");const r=[...n.group1.columns,...n.group2.columns],{viewer:s,pcaDf:a}=F(t,r,n,"PCA: All Groups");a.name=`PCA: ${t.name}`,o.shell.addTableView(a).addViewer(s)}static async showGroupMeanCorrelation(){const e=o.shell.tv,t=e?.dataFrame;if(!e||!t)return void o.shell.warning("No table open");if(!(0,S.RJ)(t,"Run Differential Expression first (Proteomics | Analyze | Differential Expression)"))return;if(!(0,E.f)(t))return void o.shell.warning("Annotate experimental groups first (Proteomics | Annotate Experiment)");const n=(0,G.Z7)(t);e.addViewer(n)}static async showQcDashboard(){const e=o.shell.tv,t=e?.dataFrame;e&&t?Z(t,"QC Dashboard")&&O(t):o.shell.warning("No table open")}static async showSpcDashboard(){await(0,R.r9)()}static async showAllVisualizations(){const e=o.shell.tv,t=e?.dataFrame;if(!e||!t)return void o.shell.warning("No table open");if(!Z(t,"Show All Visualizations"))return;if(!(0,S.RJ)(t,"Run Differential Expression first"))return;const n=(0,E.f)(t),r=(0,N.gO)(t);e.addViewer(r);const a=s.TaskBarProgressIndicator.create("Creating heatmap...");try{const n=await x(t,{title:"Heatmap: Top 50 DE Proteins"});e.addViewer(n)}finally{a.close()}if(n){const e=[...n.group1.columns,...n.group2.columns],{viewer:r,pcaDf:s}=F(t,e,n,"PCA: All Groups");s.name=`PCA: ${t.name}`,o.shell.addTableView(s).addViewer(r)}}static async enrichmentAnalysis(){const e=o.shell.tv?.dataFrame;e?(0,Y.pG)(e):o.shell.warning("No table open")}static async exportEnrichmentInputs(){const e=o.shell.tv?.dataFrame;e?(0,S.RJ)(e,"Run Differential Expression first (Proteomics | Analyze | Differential Expression)")&&(0,T.N)(e):o.shell.warning("No table open")}static async enrichmentCharts(){const e=o.shell.tv,t=e?.dataFrame;if(!t)return void o.shell.warning("No table open");if("true"!==t.getTag("proteomics.enrichment"))return void o.shell.warning("Run Enrichment Analysis first (Proteomics | Enrichment Analysis)");const n=o.shell.tables.filter(e=>"true"===e.getTag("proteomics.de_complete"));if(0===n.length)return o.shell.warning("No protein table with DE results found. Enrichment charts will open without volcano linking."),void(0,z.q6)(t,t);n.length>1&&o.shell.warning(`Multiple protein tables with DE results found; linking enrichment to "${n[0].name}"`),(0,z.q6)(t,n[0])}static async proteomicsDemo(){await async function(){const e=s.TaskBarProgressIndicator.create("Loading proteomics demo…");try{e.update(5,"Importing HYE benchmark (Spectronaut DIA)…");const t=await J.files.readAsText("demo/spectronaut-hye-demo.tsv"),n=await(0,l.parseSpectronautText)(t);n.name="HYE benchmark";const r=o.shell.addTableView(n),a=(0,E.f)(n);if(!a)return void o.shell.warning("Demo: expected two auto-annotated conditions — opened the table without running differential expression.");const i=[...a.group1.columns,...a.group2.columns];e.update(40,"Imputing missing values (KNN)…"),(0,P.Mx)(n,i),n.setTag("proteomics.imputed","true"),e.update(60,"Differential expression (t-test)…"),(0,S.ps)(n,a.group1.columns,a.group2.columns,a.group1.name,a.group2.name),n.setTag("proteomics.de_method","t-test"),e.update(78,"Building volcano and heatmap…");const c=(0,N.gO)(n);r.dockManager.dock(c,s.DOCK_TYPE.RIGHT,null,"Volcano",.5);const u=await x(n,{title:"Heatmap: Top 50 DE Proteins"});r.dockManager.dock(u,s.DOCK_TYPE.DOWN,null,"Heatmap",.45),e.update(90,"Building QC dashboard tab…"),o.shell.addTableView(n).name="HYE benchmark — QC",O(n),o.shell.v=r,f(n,function(e){const t=e.col("adj.p-value"),n=e.col("significant");if(!t)return 0;let o=-1,r=1/0;for(let s=0;s<e.rowCount;s++){if(n&&!n.get(s))continue;if(t.isNone(s))continue;const e=t.get(s);e<r&&(r=e,o=s)}return o<0?0:o}(n)),e.update(100,"Done"),o.shell.info("Proteomics demo: HYE benchmark analyzed end to end (import → impute → differential expression). Yeast and E. coli proteins shift abundance between the two conditions, so the volcano separates the genuinely differential proteins from the constant human background. QC charts are on the second tab; the top hit is selected for its UniProt panel.")}finally{e.close()}}()}static async proteomicsEnrichmentDemo(){await async function(){const e=s.TaskBarProgressIndicator.create("Loading enrichment demo…");try{e.update(10,"Loading human DE result…");const t=await J.files.readAsText("demo/enrichment-demo.csv"),n=s.DataFrame.fromCsv(t);n.name="Treatment vs Control (human)";const r=(e,t)=>{const o=n.col(e);o&&(o.semType=t)};r("Protein ID",m.iu.PROTEIN_ID),r("Gene",m.iu.GENE_SYMBOL),r("log2FC",m.iu.LOG2FC),r("p-value",m.iu.P_VALUE),r("adj.p-value",m.iu.P_VALUE),n.setTag("proteomics.source","generic"),n.setTag("proteomics.de_method","precomputed"),n.setTag("proteomics.de_complete","true"),(0,E.$Y)(n,{group1:{name:"Treatment",columns:[]},group2:{name:"Control",columns:[]}});const a=o.shell.addTableView(n),i=(0,N.gO)(n);a.dockManager.dock(i,s.DOCK_TYPE.RIGHT,null,"Volcano",.5),f(n,0),e.update(45,"Running g:Profiler enrichment (GO / KEGG / Reactome)…");try{const{enrichmentDf:t,mapped:r,total:s}=await(0,Y.D9)(n,m.M5,m.Dx,"hsapiens",["GO:BP","GO:MF","GO:CC","KEGG","REAC","WP"],!0);e.update(90,"Opening enrichment charts…"),(0,z.q6)(t,n).name=`${n.name} — Enrichment`,o.shell.v=a,o.shell.info(`Enrichment demo: ${t.rowCount} over-represented terms across ${r}/${s} genes. Up-regulated proteins are enriched for cell-cycle / mitosis; down-regulated for oxidative phosphorylation. Select a term row to highlight its proteins on the volcano.`)}catch(e){o.shell.warning(`Enrichment demo: g:Profiler enrichment could not run (${e?.message??e}). The DE table and volcano are open — retry via Proteomics | Enrichment Analysis once the service is reachable.`)}e.update(100,"Done")}finally{e.close()}}()}static uniprotPanelWidget(e){return(0,k.ku)(e)}static async shareAnalysisForReview(){const e=o.shell.tv;let t=e?.dataFrame;if(t){if("true"!==t.getTag("proteomics.de_complete")){const e=o.shell.tables.filter(e=>"true"===e.getTag("proteomics.de_complete"));if(0===e.length)return void(0,S.RJ)(t,"Run Differential Expression first (Proteomics | Analyze | Differential Expression)");e.length>1&&o.shell.warning(`Multiple analyzed tables open; sharing "${e[0].name}".`),t=e[0]}await async function(e){if("true"!==e.getTag($.$y))return void o.shell.warning("Run Differential Expression first.");const t=await o.dapi.groups.list(),n=s.Group.defaultGroupsIds?.["All users"],a=(t??[]).filter(e=>!(null==e||e.hidden||e.personal||n&&e.id===n));if(0===a.length)return void o.shell.warning("No teams available to share with. Ask an admin to create a reviewer team.");const i=new Map;for(const e of a){const t=e.friendlyName??e.name??"";t&&!i.has(t)&&i.set(t,e)}const l=Array.from(i.keys()),c=r.input.string("Target",{value:""});c.setTooltip("Free text — your team's name for this target (e.g., MYH7-DMD, muscle-atrophy panel)");const u=r.input.choice("Share with team",{value:l[0],items:l,nullable:!1}),m=r.input.textArea?r.input.textArea("Note for reviewers",{value:""}):r.input.string("Note for reviewers",{value:""}),p=r.input.bool("Verify published dashboard",{value:(0,V.Cb)()});p.setTooltip("Re-open the shared dashboard after publishing to confirm it survives a reload. On = safer (recommended for client deliverables); off = faster share.");const d=r.div();d.style.cssText="background:#fff3cd; padding:8px; border-radius:4px; margin-bottom:8px; display:none;";const f=r.div();f.style.cssText="background:#f0f0f0; padding:8px; border-radius:4px; margin:8px 0; font-family: monospace; font-size:11px;";let g=null;const h=async()=>{const e=(c.value??"").trim(),t=u.value,n=t?i.get(t)??null:null,o=e?(0,$.fz)(e):"<no-target>",s=(new Date).toISOString().slice(0,10);if(e&&n)try{g=await(0,$.T7)(e,n)}catch{g=null}else g=null;const a=(e=>{if(!e)return 0;const t=/-v(\d+)-/.exec(e);if(!t)return 0;const n=parseInt(t[1],10);return Number.isFinite(n)?n:0})(g?g.name:null),l=a>0?a+1:1;g?(d.textContent=`⚠ This will share as v${l} and supersede "${g.name}". The previous version stays available for reference.`,d.style.display="block"):d.style.display="none";const m=`${(0,V.sK)()}-${o}-v${l}-${s}`,p=n?n.friendlyName??n.name??"<unnamed team>":"<pick a team>",h=g?`Will supersede "${g.name}" (v${l})`:"New share";f.innerHTML="",f.appendChild(r.divText(`Project: ${m}`)),f.appendChild(r.divText(`Will be visible to: ${p}`)),f.appendChild(r.divText(`Status: ${h}`)),f.appendChild(r.divText(`Date: ${s}`))};c.onChanged.subscribe(()=>{h()}),u.onChanged.subscribe(()=>{h()}),await h(),r.dialog("Share Analysis for Review").add(c).add(u).add(m).add(p).add(d).add(f).onOK(async()=>{const t=(c.value??"").trim();if(!t)return void o.shell.warning("Target is required.");const n=u.value?i.get(u.value):null;if(!n)return void o.shell.warning("Pick a team to share with.");const r={target:t,reviewerGroup:n,note:m.value??"",priorVersion:g,verify:p.value??!0};try{const t=await(0,j.M)(e,r),s=n.friendlyName??n.name??"(unnamed team)";o.shell.info(`Shared as ${t.name} with team ${s}.`)}catch(e){o.shell.error(`Share failed: ${e?.message??String(e)}`)}}).show()}(t)}else o.shell.warning("No table open")}static publishedAnalysisPanelWidget(e){return function(e){const t=(0,k.xh)(e);if(null==t)return new s.Widget(r.div());if(!(0,$.HF)(t))return new s.Widget(r.div());const n=(0,$.M4)(t);if(null==n)return new s.Widget(r.divText("Shared analysis metadata unavailable. Ask the sharer to re-share."));const a=r.div();if(a.style.padding="8px 4px",null!=n.supersededBy&&""!==n.supersededBy){const e=r.link("Newer version available — open it",async()=>{try{const e=await o.dapi.projects.find(n.supersededBy);await e.open()}catch(e){o.shell.warning(`Could not open the newer version: ${e?.message??e}`)}}),t=r.div([e]);t.style.padding="8px",t.style.marginBottom="10px",t.style.backgroundColor="#fff8dc",t.style.borderRadius="4px",a.appendChild(t)}a.appendChild(r.h2("Shared analysis details"));const i=(0,E.f)(t),l=null!=i?`${i.group2.name} vs ${i.group1.name}`:"unavailable",c=Number.isFinite(n.fcThreshold)?Math.pow(2,n.fcThreshold):NaN,u=Number.isFinite(n.fcThreshold)?`log2(${n.fcThreshold}) (${Number.isFinite(c)?c.toFixed(2):"NaN"}-fold)`:"(unknown)",m=Number.isFinite(n.pThreshold)?`${n.pThreshold} (FDR-adjusted)`:"(unknown)";a.appendChild(U("Target",n.target||"(unknown)")),a.appendChild(U("Shared",B(n.publishedAt))),a.appendChild(U("Shared by",n.publishedBy||"(unknown)")),a.appendChild(U("Method",function(e){switch(e){case"limma":return"limma — moderated t-test";case"deqms":return"DEqMS — peptide-count-aware moderated t-test";case"t-test":return"Welch t-test";case"spectronaut":return"Spectronaut Candidates (pre-computed DE)";default:return e||"(unknown method)"}}(n.deMethod))),a.appendChild(U("Comparison",l)),a.appendChild(U("Fold-change cutoff",u)),a.appendChild(U("p-value cutoff",m));const p=function(e,t){if(null!=t.publishedByEmail&&""!==t.publishedByEmail)return t.publishedByEmail;try{const t=e.col($.MD.PUBLISHED_BY_EMAIL);if(null!=t){const e=t.get(0);if(null!=e&&""!==e)return String(e)}}catch{}try{const t=e.getTag($.L6.PUBLISHED_BY_EMAIL);if(t)return t}catch{}return null}(t,n);if(null!=p){const e=t.name||"shared analysis",o=(0,$.Kj)({sharerEmail:p,sharerName:n.publishedBy||"colleague",projectName:e,publishedDateStr:B(n.publishedAt)}),s=r.link("Request re-run with different parameters",o);s.href=o;const i=r.div([s]);i.style.marginTop="12px",a.appendChild(i)}return new s.Widget(a)}(e)}static async recoverPublishedProjectsOnStartup(){const e=o.events.onProjectOpened??o.events.onCurrentProjectChanged??null;if(e&&"function"==typeof e.subscribe)e.subscribe(()=>{(async()=>{await new Promise(e=>setTimeout(e,200));const e=o.shell.tables;if(Array.isArray(e))for(const t of e)if((0,$.HF)(t))try{await(0,q.I)(t)}catch(e){o.shell.warning(`Could not auto-recover shared analysis on open: ${e?.message??e}`)}})()});else{const e=o.events.onViewAdded;e&&"function"==typeof e.subscribe&&e.subscribe(e=>{if(e instanceof s.TableView){const t=e.dataFrame;t&&(0,$.HF)(t)&&(0,q.I)(t).catch(e=>{o.shell.warning(`Could not auto-recover shared analysis on open: ${e?.message??e}`)})}})}}}Q([o.decorators.init({tags:["init"]}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"initProteomics",null),Q([o.decorators.func({tags:["autostart"],meta:{autostartImmediate:"true"}}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"buildProteomicsTopMenu",null),Q([o.decorators.func({"top-menu":"Proteomics | Import | Spectronaut Candidates..."}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"importSpectronautCandidates",null),Q([o.decorators.func({"top-menu":"Proteomics | Import | Spectronaut Report..."}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"importSpectronaut",null),Q([o.decorators.func({"top-menu":"Proteomics | Import | MaxQuant..."}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"importMaxQuant",null),Q([o.decorators.func({"top-menu":"Proteomics | Import | FragPipe..."}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"importFragPipe",null),Q([o.decorators.func({"top-menu":"Proteomics | Import | Generic Matrix..."}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"importGenericMatrix",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"annotateExperiment",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"setLog2Scale",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"normalizeProteomics",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"imputeMissingValues",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"differentialExpression",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"computeSpcStatus",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"showVolcanoPlot",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"showHeatmap",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"showPcaPlot",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"showGroupMeanCorrelation",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"showQcDashboard",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"showSpcDashboard",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"showAllVisualizations",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"enrichmentAnalysis",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"exportEnrichmentInputs",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"enrichmentCharts",null),Q([o.decorators.func({name:"Proteomics Demo",description:"End-to-end proteomics differential-expression analysis on the HYE benchmark: import → impute → differential expression → volcano + heatmap, with a QC dashboard tab and the top hit pre-selected for its UniProt panel",meta:{demoPath:"Proteomics | Differential Expression",isDemoDashboard:"true"}}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"proteomicsDemo",null),Q([o.decorators.func({name:"Proteomics Enrichment Demo",description:"Pathway enrichment (g:Profiler GO / KEGG / Reactome / WikiPathways) on a human differential-expression result — cell-cycle up, oxidative-phosphorylation down — with the enrichment charts cross-linked to the volcano",meta:{demoPath:"Proteomics | Enrichment Analysis",isDemoDashboard:"true"}}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"proteomicsEnrichmentDemo",null),Q([o.decorators.panel({name:"Proteomics | UniProt",description:"UniProt protein details",meta:{role:"widgets"}}),K(0,o.decorators.param({options:{semType:"Proteomics-ProteinId"}})),W("design:type",Function),W("design:paramtypes",[String]),W("design:returntype",s.Widget)],se,"uniprotPanelWidget",null),Q([o.decorators.func(),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"shareAnalysisForReview",null),Q([o.decorators.panel({name:"Proteomics | Shared Analysis",description:"Audit context for a shared analysis snapshot",meta:{role:"widgets"}}),K(0,o.decorators.param({options:{semType:"Proteomics-ProteinId"}})),W("design:type",Function),W("design:paramtypes",[String]),W("design:returntype",s.Widget)],se,"publishedAnalysisPanelWidget",null),Q([o.decorators.func({tags:["autostart"],meta:{autostartImmediate:"true"}}),W("design:type",Function),W("design:paramtypes",[]),W("design:returntype",Promise)],se,"recoverPublishedProjectsOnStartup",null)},498(e,t,n){"use strict";n.d(t,{A$:()=>d,S6:()=>u,ku:()=>f,nT:()=>p,xh:()=>m});var o=n(328),r=n(389),s=n(82),a=n(623),i=n(252),l=n(304),c=n(641);function u(e){if(!e||!e.trim())return null;const t=e.split(";")[0].trim();if(!t)return null;const n=t.match(/^(?:sp|tr)\|([A-Za-z0-9_-]+)\|/);if(n)return n[1];const o=t.match(/^([A-Za-z0-9]+?)ups\|/i);if(o)return o[1];if(t.includes("|"))return t.split("|")[0].trim();const r=t.match(/^([A-Za-z0-9_-]+)$/);return r?r[1].replace(/ups$/i,""):null}function m(e){if(!e)return null;const t=[];for(const n of o.shell.tables){if(!(0,i.f)(n))continue;const o=(0,l.k)(n,c.iu.PROTEIN_ID,["primary protein id","protein id","uniprot","accession"]);if(o)for(let r=0;r<n.rowCount;r++){const s=o.get(r);if(s&&u(s)===e){t.push(n);break}}}if(0===t.length)return null;const n=o.shell.tv?.dataFrame??null;return n&&t.includes(n)?n:t[0]}function p(e,t){const n=(0,i.f)(e);if(!n)return null;const o=(0,l.k)(e,c.iu.PROTEIN_ID,["primary protein id","protein id","uniprot","accession"]);if(!o)return null;let a=-1;for(let n=0;n<e.rowCount;n++){const e=o.get(n);if(e&&u(e)===t){a=n;break}}if(a<0)return null;const m=[n.group1,n.group2].map(t=>{const n=t.columns.map(t=>e.col(t)).filter(e=>null!=e).map(e=>e.isNone(a)?NaN:e.get(a)).filter(e=>"number"==typeof e&&!isNaN(e)&&e!==s.FLOAT_NULL),o=n.length;if(0===o)return{name:t.name,mean:NaN,sd:NaN,n:0};const r=n.reduce((e,t)=>e+t,0)/o,i=o>1?n.reduce((e,t)=>e+(t-r)**2,0)/(o-1):0;return{name:t.name,mean:r,sd:Math.sqrt(i),n:o}});if(m.every(e=>0===e.n))return r.divText("No per-group quantities available for this protein");const p=Math.max(...m.map(e=>isNaN(e.mean)?0:e.mean+(isNaN(e.sd)?0:e.sd))),d=p>0?p:1,f=e=>96-e/d*72,g=e=>"#"+(16777215&e).toString(16).padStart(6,"0").toUpperCase(),h=[g(c.PL.enrichedG1),g(c.PL.enrichedG2)],y="http://www.w3.org/2000/svg",E=document.createElementNS(y,"svg");E.setAttribute("width",String(200)),E.setAttribute("height",String(120)),m.forEach((e,t)=>{const n=24+40*t;if(0===e.n)return;const o=f(e.mean),r=document.createElementNS(y,"rect");if(r.setAttribute("x",String(n)),r.setAttribute("y",String(o)),r.setAttribute("width",String(24)),r.setAttribute("height",String(Math.max(0,96-o))),r.setAttribute("fill",h[t]??g(c.PL.notSig)),E.appendChild(r),e.n>1&&!isNaN(e.sd)){const t=n+12,o=f(e.mean+e.sd),r=f(e.mean-e.sd),s=document.createElementNS(y,"line");s.setAttribute("x1",String(t)),s.setAttribute("x2",String(t)),s.setAttribute("y1",String(o)),s.setAttribute("y2",String(r)),s.setAttribute("stroke","#333"),s.setAttribute("stroke-width","1"),E.appendChild(s)}const s=document.createElementNS(y,"text");s.setAttribute("x",String(n+12)),s.setAttribute("y",String(116)),s.setAttribute("text-anchor","middle"),s.setAttribute("font-size","10"),s.textContent=`${e.name} (n=${e.n})`,E.appendChild(s)});const w=r.divV([E]);return m.forEach(e=>{if(e.n>0){const t=r.divText(`${e.name}: mean=${e.mean.toFixed(2)} SD=${e.sd.toFixed(2)}`);t.style.fontSize="0.85em",w.appendChild(t)}}),w}function d(e,t){const n=document.createElement("div"),o=r.link(`UniProt: ${t}`,`https://www.uniprot.org/uniprot/${t}`,"Open full UniProt entry");o.style.fontWeight="bold",o.style.display="block",o.style.marginBottom="8px",n.appendChild(o);const s=function(e){return e.proteinDescription?.recommendedName?.fullName?.value??e.proteinDescription?.submissionNames?.[0]?.fullName?.value??"Unknown"}(e),a=e.genes?.[0]?.geneName?.value??"Unknown",i=e.organism?.scientificName??"Unknown",l=e.comments?.find(e=>"FUNCTION"===e.commentType);let c=l?.texts?.[0]?.value??"";c.length>200&&(c=c.substring(0,200)+"...");const u={Protein:s,Gene:a,Organism:i};c&&(u.Function=c),n.appendChild(r.tableFromMap(u));const d=function(e){const t=[],n=[],o=[];for(const r of e.uniProtKBCrossReferences??[]){if("GO"!==r.database)continue;const e=r.properties?.find(e=>"GoTerm"===e.key)?.value??"";e.startsWith("F:")?t.push(e.substring(2)):e.startsWith("P:")?n.push(e.substring(2)):e.startsWith("C:")&&o.push(e.substring(2))}return{mf:t,bp:n,cc:o}}(e),f=[{label:"Molecular Function",terms:d.mf},{label:"Biological Process",terms:d.bp},{label:"Cellular Component",terms:d.cc}];if(f.some(e=>e.terms.length>0)){const e=r.divText("GO Terms");e.style.fontWeight="bold",e.style.marginTop="8px",e.style.marginBottom="4px",n.appendChild(e);for(const e of f){if(0===e.terms.length)continue;const t=r.divText(e.label);t.style.fontWeight="bold",t.style.fontSize="0.9em",t.style.marginTop="4px",n.appendChild(t);const o=e.terms.slice(0,5).join(", "),s=r.divText(o);s.style.fontSize="0.85em",s.style.marginLeft="8px",n.appendChild(s)}}const g=m(t);if(g){const e=r.divText("Per-Group Quantities");e.style.fontWeight="bold",e.style.marginTop="8px",e.style.marginBottom="4px",n.appendChild(e);const o=p(g,t);n.appendChild(o??r.divText("No per-group quantities available for this protein"))}return n}function f(e){const t=u(e);return t?new s.Widget(r.wait(async()=>{const e=await async function(e){return await(0,a.Kf)(e)}(t);return e?d(e,t):r.divText(`Unable to fetch UniProt data for ${t}`)})):new s.Widget(r.divText("No valid UniProt accession found"))}},119(e,t,n){"use strict";n.d(t,{p:()=>f});var o=n(82),r=n(641),s=n(954),a=n(117);const i=[" MaxLFQ Intensity"," Intensity"," Razor Intensity"],l=["Protein ID","Protein"],c=["Gene","Gene Names","Gene Symbol"],u=["contam_","rev_","CON__","REV__"];function m(e,t){for(const n of t){const t=e.col(n);if(t)return t}return null}function p(e){const t=e.toLowerCase();for(const e of i)if(t.endsWith(e.toLowerCase())&&t.length>e.length)return e.toLowerCase();return null}function d(e,t,n,o){const r=m(e,t);r&&(0,s.wK)(e,r.name,n,o)}async function f(e){const t=function(e){const t=e.indexOf("\n"),n=(t>=0?e.substring(0,t):e).replace(/\r$/,"").split("\t"),o=[];for(const e of n)p(e)&&o.push({name:e,type:"double"});return o}(e),n=o.DataFrame.fromCsv(e,{delimiter:"\t",columnImportOptions:t});n.filter.init(e=>!0),function(e){const t=["Protein ID","Protein"],n=[];for(const o of t){const t=e.col(o);t&&n.push(t)}if(0!==n.length)for(let t=0;t<e.rowCount;t++)for(const o of n){const n=o.get(t);if("string"!=typeof n)continue;let r=!1;for(const e of u)if(n.startsWith(e)){r=!0;break}if(r){e.filter.set(t,!1,!1);break}}}(n),n.filter.fireChanged();const i=n.clone(n.filter),f=function(e){const t=new Map;for(const n of e.columns.names()){const r=e.col(n);if(!r)continue;if(r.type!==o.COLUMN_TYPE.FLOAT&&r.type!==o.COLUMN_TYPE.INT&&r.type!==o.COLUMN_TYPE.BIG_INT)continue;const s=n.toLowerCase();let a=null,i=null;s.endsWith(" maxlfq intensity")?(a=n.substring(0,n.length-17),i="maxLfq"):s.endsWith(" razor intensity")?(a=n.substring(0,n.length-16),i="razor"):s.endsWith(" intensity")&&(a=n.substring(0,n.length-10),i="intensity"),a&&i&&(t.has(a)||t.set(a,{}),t.get(a)[i]=n)}const n=[];for(const e of t.values())e.maxLfq?n.push(e.maxLfq):e.intensity?n.push(e.intensity):e.razor&&n.push(e.razor);return n}(i);return function(e,t){const n=m(e,l);n&&(n.semType=r.iu.PROTEIN_ID);const o=m(e,c);o&&(o.semType=r.iu.GENE_SYMBOL);for(const n of t){const t=e.col(n);t&&(t.semType=r.iu.INTENSITY)}}(i,f),d(i,l,"Primary Protein ID",r.iu.PROTEIN_ID),d(i,c,"Primary Gene Name",r.iu.GENE_SYMBOL),(0,s.Kh)(i,f),i.setTag("proteomics.source","fragpipe"),await(0,a.rv)(i),i}},312(e,t,n){"use strict";n.d(t,{E:()=>h});var o=n(82),r=n(641),s=n(954),a=n(117);const i=["lfq intensity","ibaq","reporter intensity","intensity"],l=["Potential contaminant","Potential.contaminant"],c=["Reverse"],u=["Only identified by site","Only.identified.by.site"],m=["Protein IDs","Majority protein IDs"],p=["Gene names","Gene name"];function d(e,t){for(const n of t){const t=e.col(n);if(t)return t}return null}function f(e,t){const n=d(e,t);if(n)for(let t=0;t<e.rowCount;t++)"+"===n.get(t)&&e.filter.set(t,!1,!1)}function g(e,t,n,o){const r=d(e,t);r&&(0,s.wK)(e,r.name,n,o)}async function h(e){const t=function(e){const t=e.indexOf("\n"),n=(t>=0?e.substring(0,t):e).replace(/\r$/,"").split("\t"),o=[];for(const e of n){const t=e.toLowerCase();for(const n of i)if(t.startsWith(n)){o.push({name:e,type:"double"});break}}return o}(e),n=o.DataFrame.fromCsv(e,{delimiter:"\t",columnImportOptions:t});n.filter.init(e=>!0),f(n,l),f(n,c),f(n,u),function(e){const t=[];for(const n of m){const o=e.col(n);o&&t.push(o)}if(0!==t.length)for(let n=0;n<e.rowCount;n++)for(const o of t){const t=o.get(n);if("string"==typeof t&&(t.startsWith("CON__")||t.startsWith("REV__"))){e.filter.set(n,!1,!1);break}}}(n),n.filter.fireChanged();const h=n.clone(n.filter);return function(e){const t=d(e,m);t&&(t.semType=r.iu.PROTEIN_ID);const n=d(e,p);n&&(n.semType=r.iu.GENE_SYMBOL)}(h),g(h,m,"Primary Protein ID",r.iu.PROTEIN_ID),g(h,p,"Primary Gene Name",r.iu.GENE_SYMBOL),function(e){const t=[];for(const n of e.columns.names()){const r=e.col(n);if(!r)continue;if(r.type!==o.COLUMN_TYPE.FLOAT&&r.type!==o.COLUMN_TYPE.INT)continue;const s=n.toLowerCase();for(const e of i)if(s.startsWith(e)){t.push(n);break}}(0,s.Kh)(e,t)}(h),h.setTag("proteomics.source","maxquant"),await(0,a.rv)(h),h}},954(e,t,n){"use strict";n.d(t,{Kh:()=>s,T6:()=>c,WI:()=>p,YL:()=>m,eY:()=>l,l3:()=>a,q2:()=>u,wK:()=>i});var o=n(82),r=n(641);function s(e,t){let n=0;for(const s of t){const t=e.col(s);if(!t)continue;t.semType=r.iu.INTENSITY;const a=`log2(${s})`,i=e.columns.addNewFloat(a);i.init(e=>{if(t.isNone(e))return o.FLOAT_NULL;const r=Number(t.get(e));return isNaN(r)?(n++,o.FLOAT_NULL):r>0?Math.log2(r):o.FLOAT_NULL}),i.semType=r.iu.INTENSITY}n>0&&console.warn(`log2TransformColumns: ${n} non-numeric value(s) dropped to null`)}function a(e,t){for(const n of t){const t=e.col(n);if(!t)continue;t.semType=r.iu.INTENSITY;const s=`log2(${n})`,a=e.columns.addNewFloat(s);a.init(e=>t.isNone(e)?o.FLOAT_NULL:Number(t.get(e))),a.semType=r.iu.INTENSITY}}function i(e,t,n,o){const r=e.col(t);if(!r)return;let s=!1;for(let t=0;t<e.rowCount&&!s;t++){const e=r.get(t);"string"==typeof e&&e.includes(";")&&(s=!0)}if(!s)return;const a=e.columns.addNewString(n);a.init(e=>{const t=r.get(e);if("string"!=typeof t||0===t.length)return null;const n=t.indexOf(";");return n>=0?t.substring(0,n):t}),a.semType=o}function l(e,t){let n=0,r=0,s=0;for(const a of t){const t=e.col(a);if(t&&(t.type===o.COLUMN_TYPE.FLOAT||t.type===o.COLUMN_TYPE.INT||t.type===o.COLUMN_TYPE.BIG_INT)){for(let o=0;o<e.rowCount&&s<200;o++){if(t.isNone(o))continue;const e=Number(t.get(o));e>=0&&e<=30?(n++,s++):e>=1e3&&(r++,s++)}if(s>=200)break}}return 0===s?{isLog2:!1,message:"No intensity values found"}:r/s>.5?{isLog2:!1,message:"Data appears to be raw intensities"}:n/s>.8?{isLog2:!0,message:"Data appears to be already log2-transformed"}:{isLog2:!1,message:"Could not determine data scale"}}function c(e){const t=e.indexOf("\n"),n=t>=0?e.substring(0,t):e;return(n.match(/\t/g)||[]).length>(n.match(/,/g)||[]).length?"\t":","}function u(e){const t=["protein","accession","uniprot"];for(const n of e.columns.toList()){if(n.type!==o.COLUMN_TYPE.STRING)continue;const e=n.name.toLowerCase();for(const o of t)if(e.includes(o))return n}return null}function m(e){const t=["gene","symbol","gene_name","genename"];for(const n of e.columns.toList()){if(n.type!==o.COLUMN_TYPE.STRING)continue;const e=n.name.toLowerCase();for(const o of t)if(e.includes(o))return n}return null}function p(e){const t=["intensity","lfq","ibaq","tmt","reporter","abundance"],n=[];for(const r of e.columns.toList()){if(r.type!==o.COLUMN_TYPE.FLOAT&&r.type!==o.COLUMN_TYPE.INT&&r.type!==o.COLUMN_TYPE.BIG_INT)continue;const e=r.name.toLowerCase();for(const o of t)if(e.includes(o)){n.push(r.name);break}}return n}},86(e,t,n){"use strict";n.d(t,{R:()=>_,g:()=>d});var o=n(82),r=n(641),s=n(954),a=n(117),i=n(252);const l=["PG.ProteinGroups","ProteinGroups","Protein Groups"],c=["PG.Genes","Genes","Gene Names"],u=["AVG Log2 Ratio","Log2 Ratio","AVG Log2 Fold Change"],m=["Qvalue","Q-Value","Q.Value","AdjustedPValue","Adjusted P-Value"],p=["Pvalue","PValue","P-Value","P.Value"],d=["Comparison (group1/group2)","Comparison"],f=["AVG Group Quantity Numerator"],g=["AVG Group Quantity Denominator"],h=["Condition Numerator"],y=["Condition Denominator"],E=["contam_","rev_","CON__","REV__"];function w(e,t){for(const n of t){const t=e.col(n);if(t)return t}return null}function v(e,t,n){if(t.name===n)return;const o=e.col(n);o&&o!==t||(t.name=n)}async function _(e){const t=(0,s.T6)(e),n=o.DataFrame.fromCsv(e,{delimiter:t}),_=w(n,l);if(!_)throw new Error(`Spectronaut Candidates: missing protein-group column (expected one of ${l.join(", ")})`);if(!w(n,u))throw new Error(`Spectronaut Candidates: missing log2 ratio column (expected one of ${u.join(", ")})`);if(!w(n,m))throw new Error(`Spectronaut Candidates: missing q-value column (expected one of ${m.join(", ")})`);n.filter.init(e=>!0),function(e,t){const n=e.col(t);if(n)for(let t=0;t<e.rowCount;t++){const o=n.get(t);if("string"==typeof o)for(const n of E)if(o.startsWith(n)){e.filter.set(t,!1,!1);break}}}(n,_.name),n.filter.fireChanged();const b=n.clone(n.filter),T=w(b,l),P=w(b,u),S=w(b,m),N=w(b,c),A=w(b,p);v(b,P,"log2FC"),v(b,S,"adj.p-value"),A&&v(b,A,"p-value"),T.semType=r.iu.PROTEIN_ID,N&&(N.semType=r.iu.GENE_SYMBOL),b.col("log2FC").semType=r.iu.LOG2FC,b.col("adj.p-value").semType=r.iu.P_VALUE,b.col("p-value")&&(b.col("p-value").semType=r.iu.P_VALUE),(0,s.wK)(b,T.name,"Primary Protein ID",r.iu.PROTEIN_ID),N&&(0,s.wK)(b,N.name,"Primary Gene Name",r.iu.GENE_SYMBOL),function(e){const t=w(e,d);if(!t)return;const n=e.rowCount;let r=null,s="",a="";for(let e=0;e<n;e++){const n=t.get(e);if("string"==typeof n&&n.includes(" / ")){const e=n.split(" / ");if(2===e.length&&e[0]&&e[1]){r=n,s=e[0],a=e[1];break}}}if(null===r)return;const i=`${a} / ${s}`,l=new Uint8Array(n);let c=!1;for(let e=0;e<n;e++)t.get(e)===i&&(l[e]=1,c=!0);if(!c)return;const u=e.col("log2FC"),m=u.getRawData(),p=new Array(n);for(let e=0;e<n;e++){const t=m[e];p[e]=t===o.FLOAT_NULL?o.FLOAT_NULL:l[e]?-t:t}u.init(e=>p[e]);const E=w(e,f),v=w(e,g);if(E&&v){const e=E.getRawData(),t=v.getRawData(),o=new Array(n),r=new Array(n);for(let s=0;s<n;s++){const n=e[s],a=t[s];o[s]=l[s]?a:n,r[s]=l[s]?n:a}E.init(e=>o[e]),v.init(e=>r[e])}const _=new Array(n);for(let e=0;e<n;e++)_[e]=l[e]?r:t.get(e);t.init(e=>_[e]);const C=w(e,h),b=w(e,y);if(C&&b){const e=new Array(n),t=new Array(n);for(let o=0;o<n;o++)e[o]=l[o]?s:C.get(o),t[o]=l[o]?a:b.get(o);C.init(t=>e[t]),b.init(e=>t[e])}}(b);const x=b.columns.addNewBool("significant"),D=b.col("log2FC").getRawData(),L=b.col("adj.p-value").getRawData();x.init(e=>{const t=D[e],n=L[e];return t!==o.FLOAT_NULL&&n!==o.FLOAT_NULL&&Math.abs(t)>=r.M5&&n<=r.Dx}),b.setTag("proteomics.source","spectronaut-candidates"),b.setTag("proteomics.de_complete","true"),b.setTag("proteomics.de_method","spectronaut");let F=C(w(b,h)),I=C(w(b,y));if(!F||!I){const e=C(w(b,d));if(e&&e.includes("/")){const[t,n]=e.split("/").map(e=>e.trim());F=F??(t||null),I=I??(n||null)}}return F&&I&&(0,i.$Y)(b,{group1:{name:F,columns:[]},group2:{name:I,columns:[]}}),await(0,a.rv)(b),b}function C(e){if(!e)return null;for(let t=0;t<e.length;t++){const n=e.get(t);if(null!=n&&String(n).trim().length>0)return String(n).trim()}return null}},53(e,t,n){"use strict";n.d(t,{A:()=>f,parseSpectronautText:()=>g});var o=n(328),r=n(82),s=n(641),a=n(954),i=n(252),l=n(117);const c=["R.Condition","R.Replicate","PG.ProteinGroups"],u=["PG.IBAQ","PG.Quantity"];function m(e){if(!e||0===e.trim().length)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}async function p(e){const t=function(e){const t=Array.from(e.proteinMap.keys()),n=t.length,o=r.Column.fromStrings("PG.ProteinGroups",t);o.semType=s.iu.PROTEIN_ID;const a=[o];if(e.organisms.size>0){const n=t.map(t=>e.organisms.get(t)??""),o=r.Column.fromStrings("PG.Organisms",n);a.push(o)}for(const o of e.sampleKeys){const i=new Float32Array(n);for(let s=0;s<n;s++){const n=e.proteinMap.get(t[s]);i[s]=n.has(o)?n.get(o):r.FLOAT_NULL}const l=r.Column.fromFloat32Array(o,i);l.semType=s.iu.INTENSITY,e.sampleFileNames.has(o)&&l.setTag("spectronaut.fileName",e.sampleFileNames.get(o)),a.push(l)}return r.DataFrame.fromColumns(a)}(e);(0,a.wK)(t,"PG.ProteinGroups","Primary Protein ID",s.iu.PROTEIN_ID);const n=e.sampleKeys;return(0,a.eY)(t,n).isLog2?(0,a.l3)(t,n):(0,a.Kh)(t,n),t.setTag("proteomics.preNormalized","true"),t.setTag("proteomics.source","spectronaut"),function(e,t){const n=new Map;for(const e of t){const t=e.lastIndexOf("_"),o=e.substring(0,t);n.has(o)||n.set(o,[]),n.get(o).push(`log2(${e})`)}const o=Array.from(n.keys());2===o.length&&(0,i.$Y)(e,{group1:{name:o[0],columns:n.get(o[0])},group2:{name:o[1],columns:n.get(o[1])}})}(t,e.sampleKeys),await(0,l.rv)(t),t}function d(e){if(null==e)return null;const t=e.trim();if(""===t||"NaN"===t||"NA"===t)return null;const n=Number(t);return Number.isFinite(n)?n:null}async function f(e,t=.01){const n=r.TaskBarProgressIndicator.create("Streaming Spectronaut report...");try{const r=e.stream().pipeThrough(new TextDecoderStream("utf-8")).getReader(),s=new Map;let a="",i=!1,l=new Map,f=-1,g=-1,y=-1,E=-1,w=-1,v=-1,_=-1,C=-1,b=-1,T=0,P=null,S=null,N=null,A=0,x=0,D=0,L=0,F=performance.now();const I=Math.max(1,e.size),M=e=>{if(e.length<T)return"malformed";const n=e[f];if(!n)return"filtered";if(n.startsWith("CON__")||n.startsWith("REV__"))return"filtered";const o=E>=0?d(e[E]):null;if(null!==o&&o>t)return"filtered";const r=d(e[w]);if(null===r&&null===o)return"filtered";const a=e[g]??"",i=e[y]??"",l=n+""+a+""+i;let c=s.get(l);if(void 0===c&&(c={protein:n,condition:a,replicate:i,maxQuantity:-1/0,minQvalue:1/0,fileName:null,organism:null},s.set(l,c)),null!==r&&r>c.maxQuantity&&(c.maxQuantity=r),null!==o&&o<c.minQvalue&&(c.minQvalue=o),null===c.fileName&&v>=0){const t=e[v];t&&(c.fileName=t)}if(null===c.organism&&_>=0){const t=e[_];t&&(c.organism=t)}if(C>=0){const t=e[C];if(t){const e=m(t);null!==e&&(null===P||e<P)&&(P=e,S=new Date(e).toISOString())}}if(b>=0&&null===N){const t=e[b];t&&t.trim().length>0&&(N=t)}return"kept"},O=e=>{const t=e.split("\t");l=new Map;for(let e=0;e<t.length;e++)l.set(t[e],e);for(const e of c)if(!l.has(e))throw new Error(`Missing required Spectronaut column: ${e}`);const n=u.find(e=>l.has(e));if(!n)throw new Error(`Missing protein-group quantity column (expected one of ${u.join(", ")})`);f=l.get("PG.ProteinGroups"),g=l.get("R.Condition"),y=l.get("R.Replicate"),w=l.get(n),E=l.has("EG.Qvalue")?l.get("EG.Qvalue"):-1,v=l.has("R.FileName")?l.get("R.FileName"):-1,_=l.has("PG.Organisms")?l.get("PG.Organisms"):-1,C=l.has("R.RunDate")?l.get("R.RunDate"):-1,b=l.has("R.InstrumentMethod")?l.get("R.InstrumentMethod"):-1,T=Math.max(f,g,y,w,E,v,_,C,b)+1,i=!0};for(;;){const{value:e,done:t}=await r.read();if(t)break;let o;for(A+=e.length,a+=e;(o=a.indexOf("\n"))>=0;){let e=a.slice(0,o);if(a=a.slice(o+1),e.endsWith("\r")&&(e=e.slice(0,-1)),i){if(0!==e.length)switch(M(e.split("\t"))){case"kept":x++;break;case"malformed":D++;break;case"filtered":L++}}else{if(0===e.length)continue;O(e)}}if(performance.now()-F>=16){const e=Math.min(99,A/I*100),t=D>0?`${x} rows (${D} malformed skipped)`:`${x} rows`;n.update(e,t),await new Promise(e=>setTimeout(e,0)),F=performance.now()}}if(a.length>0){let e=a;if(e.endsWith("\r")&&(e=e.slice(0,-1)),e.length>0)if(i)switch(M(e.split("\t"))){case"kept":x++;break;case"malformed":D++;break;case"filtered":L++}else O(e)}if(!i)throw new Error("Missing required Spectronaut column: R.Condition");D>0&&o.shell.info(`Spectronaut import: skipped ${D} malformed line(s)`);const R=function(e){const t=new Map,n=new Set,o=new Map,r=new Map;for(const s of e.values()){if(!Number.isFinite(s.maxQuantity))continue;const e=`${s.condition}_${s.replicate}`;n.add(e),t.has(s.protein)||t.set(s.protein,new Map),t.get(s.protein).set(e,s.maxQuantity),null===s.fileName||o.has(e)||o.set(e,s.fileName),null===s.organism||r.has(s.protein)||r.set(s.protein,s.organism)}return{proteinMap:t,sampleKeys:Array.from(n).sort(),sampleFileNames:o,organisms:r}}(s);R.earliestRunDate=S,R.firstInstrumentMethod=N;const G=await p(R);return h(G,R),G}finally{n.close()}}async function g(e,t=.01){const n=r.DataFrame.fromCsv(e,{delimiter:"\t"});for(const e of c)if(!n.col(e))throw new Error(`Missing required Spectronaut column: ${e}`);const o=u.find(e=>null!==n.col(e));if(!o)throw new Error(`Missing protein-group quantity column (expected one of ${u.join(", ")})`);const s=function(e,t,n){const o=e.col("R.Condition"),r=e.col("R.Replicate"),s=e.col("PG.ProteinGroups"),a=e.col(t),i=e.col("EG.Qvalue"),l=e.col("R.FileName"),c=e.col("PG.Organisms"),u=e.col("R.RunDate"),p=e.col("R.InstrumentMethod"),d=new Map,f=new Set,g=new Map,h=new Map;let y=null,E=null,w=null;for(let t=0;t<e.rowCount;t++){if(i)if(i.isNone(t));else{const e=i.get(t),o=Number(e);if(!isNaN(o)&&o>n)continue}const e=s.get(t);if(!e)continue;if(e.startsWith("CON__")||e.startsWith("REV__"))continue;const v=`${String(o.get(t))}_${String(r.get(t))}`;if(f.add(v),d.has(e)||d.set(e,new Map),d.get(e).has(v)||a.isNone(t)||d.get(e).set(v,Number(a.get(t))),!l||g.has(v)||l.isNone(t)||g.set(v,l.get(t)),!c||h.has(e)||c.isNone(t)||h.set(e,c.get(t)),u&&!u.isNone(t)){const e=m(String(u.get(t)));null!==e&&(null===y||e<y)&&(y=e,E=new Date(e).toISOString())}if(p&&null===w&&!p.isNone(t)){const e=String(p.get(t));e.trim().length>0&&(w=e)}}return{proteinMap:d,sampleKeys:Array.from(f).sort(),sampleFileNames:g,organisms:h,earliestRunDate:E,firstInstrumentMethod:w}}(n,o,t),a=await p(s);return h(a,s),a}function h(e,t){const n=null!=t.earliestRunDate,o=null!=t.firstInstrumentMethod;(n||o)&&e.setTag("proteomics.spc_run_meta_seed",JSON.stringify({instrument_id:t.firstInstrumentMethod??"",acquisition_datetime:t.earliestRunDate??""}))}},691(e,t,n){"use strict";n.d(t,{F:()=>u,Y:()=>c});var o=n(328),r=n(82),s=n(749),a=n(641),i=n(304),l=n(771);const c="FORMULA_LINE_MISSING:";async function u(e,t){const n=e.id;o.shell.closeAll(),await(0,s.cb)(100);const u=await o.dapi.projects.find(n);await u.open(),await(0,s.bk)(()=>!!o.shell.tv&&!!o.shell.tv.dataFrame,"assertPublishedShape: TableView never materialized after project.open()",5e3);const m=o.shell.tv.dataFrame;if(m.name!==t.expectedName)throw new Error(`assertPublishedShape: df.name: got "${m.name}", expected "${t.expectedName}"`);if(u.name!==t.expectedProjectName)throw new Error(`assertPublishedShape: project.name: got "${u.name}", expected "${t.expectedProjectName}"`);for(const e of t.expectedAllowlist)if(!m.col(e))throw new Error(`assertPublishedShape: allowlist column missing on reopen: "${e}"`);const p=m.columns.toList().map(e=>e.name).filter(e=>!e.startsWith("_meta_")&&!e.startsWith("~"));if(p.length!==t.expectedAllowlist.length){const e=p.filter(e=>!t.expectedAllowlist.includes(e)),n=t.expectedAllowlist.filter(e=>!p.includes(e));throw new Error(`assertPublishedShape: visible column count: got ${p.length}, expected ${t.expectedAllowlist.length}. Unexpected: [${e.join(", ")}]. Missing: [${n.join(", ")}].`)}const d=(0,i.k)(m,a.iu.PROTEIN_ID,["protein id","majority protein id","accession"]);if(null==d)throw new Error("assertPublishedShape: protein-id column not found via findColumn");if(d.semType!==a.iu.PROTEIN_ID)throw new Error(`assertPublishedShape: protein-id semType: got "${d.semType??"null"}", expected "${a.iu.PROTEIN_ID}". Detectors may not have re-fired on reopen — re-assign in trim-dataframe.ts Step E.`);const f=(0,l.M4)(m);if(null==f)throw new Error("assertPublishedShape: getPublishedMetadata returned null — published flag not set or all critical fields unreadable");const g=t.expectedMeta,h=(e,t)=>!(Math.abs(e-t)>1e-9);if(f.target!==g.target)throw new Error(`assertPublishedShape: meta.target: got "${f.target}", expected "${g.target}"`);if(f.deMethod!==g.deMethod)throw new Error(`assertPublishedShape: meta.deMethod: got "${f.deMethod}", expected "${g.deMethod}"`);if(!h(f.fcThreshold,g.fcThreshold))throw new Error(`assertPublishedShape: meta.fcThreshold: got ${f.fcThreshold}, expected ${g.fcThreshold}`);if(!h(f.pThreshold,g.pThreshold))throw new Error(`assertPublishedShape: meta.pThreshold: got ${f.pThreshold}, expected ${g.pThreshold}`);if(f.version!==g.version)throw new Error(`assertPublishedShape: meta.version: got ${f.version}, expected ${g.version}`);if(f.publishId!==g.publishId)throw new Error(`assertPublishedShape: meta.publishId: got "${f.publishId}", expected "${g.publishId}"`);if(f.includesEnrichment!==g.includesEnrichment)throw new Error(`assertPublishedShape: meta.includesEnrichment: got ${f.includesEnrichment}, expected ${g.includesEnrichment}`);if(f.publishedBy!==g.publishedBy)throw new Error(`assertPublishedShape: meta.publishedBy: got "${f.publishedBy}", expected "${g.publishedBy}"`);for(const e of Object.keys(l.MD)){const t=l.MD[e];if(!m.col(t))throw new Error(`assertPublishedShape: metadata column missing: "${t}"`)}let y=null;if(t.expectVolcano)try{await(0,s.bk)(()=>{const e=o.shell.tv;if(!e)return!1;for(const t of e.viewers)if(t.type===r.VIEWER.SCATTER_PLOT)return y=t,!0;return!1},"assertPublishedShape: volcano scatter plot not present on reopen — consider post-open recomputeVolcano in publish-project.ts",5e3)}catch(e){throw new Error(`assertPublishedShape: volcano viewer assertion failed: ${e?.message??e}`)}if(t.expectVolcano&&t.expectFormulaLines&&null!=y){const e=String(g.fcThreshold),t=String(g.pThreshold),n=String(-Math.log10(g.pThreshold)),o=[];try{const e=m.meta?.formulaLines?.items??[];Array.isArray(e)&&o.push(...e)}catch{}try{const e=y.getOptions?.(),t=e?.look?.formulaLines,n="string"==typeof t?JSON.parse(t):t;Array.isArray(n)&&o.push(...n)}catch{}try{const e=y?.props?.formulaLines,t="string"==typeof e?JSON.parse(e):e;Array.isArray(t)&&o.push(...t)}catch{}const r=o.map(e=>"string"==typeof e?.formula?e.formula:"").filter(e=>e.length>0),s=r.some(t=>t.includes(e)||t.includes(`-${e}`)),a=r.some(e=>e.includes(n)||e.includes(t));if(!s||!a)throw new Error(`${c} volcano reopened without formula lines for FC=${g.fcThreshold} and/or p=${g.pThreshold}. The look/filter config was stripped by the serializer (Phase 13 e527d07ba1 evidence). Plan 04 step 8 catch should invoke the post-open recovery hook from tags ${l.L6.PUBLISHED_FC_THRESHOLD} / ${l.L6.PUBLISHED_P_THRESHOLD} and re-run this assertion once.`)}if(t.expectEnrichment){const e=o.shell.tables;if(!Array.isArray(e)||e.length<2)throw new Error(`assertPublishedShape: expectEnrichment=true but grok.shell.tables has ${e?.length??0} DataFrames (need ≥ 2)`);if(!e.find(e=>{try{const t=e.col(l.MD.PUBLISHED_INCLUDES_ENRICHMENT);return null!=t&&"true"===String(t.get(0))}catch{return!1}}))throw new Error("assertPublishedShape: protein DF (with _meta_published_includes_enrichment=true) not found among reopened tables");if(!e.find(e=>"true"===e.getTag("proteomics.enrichment")))throw new Error("assertPublishedShape: enrichment DF (proteomics.enrichment=true tag) not found among reopened tables")}const E=u.options??{};if(null!=g.supersedes){const e=E[l.L6.SUPERSEDES];if(e!==g.supersedes)throw new Error(`assertPublishedShape: project.options['${l.L6.SUPERSEDES}']: got "${e??"null"}", expected "${g.supersedes}"`)}if(null!=g.supersededBy){const e=E[l.L6.SUPERSEDED_BY];if(e!==g.supersededBy)throw new Error(`assertPublishedShape: project.options['${l.L6.SUPERSEDED_BY}']: got "${e??"null"}", expected "${g.supersededBy}"`)}}},649(e,t,n){"use strict";n.d(t,{I:()=>c});var o=n(328),r=n(82),s=n(771),a=n(807),i=n(897);const l="proteomics.enrichment_wired";async function c(e){if(!(0,s.HF)(e))return;const t=function(e){try{const t=o.shell.tableViews;if(Array.isArray(t)){const n=t.find(t=>t?.dataFrame===e);if(n)return n}}catch{}try{const t=o.shell.tv;if(t&&t.dataFrame===e)return t}catch{}return null}(e);if(t){const n=Array.from(t.viewers).find(e=>e.type===r.VIEWER.SCATTER_PLOT);if(n){const t=e.getTag(s.L6.PUBLISHED_FC_THRESHOLD),o=e.getTag(s.L6.PUBLISHED_P_THRESHOLD);if(t&&o){const r=parseFloat(t),s=parseFloat(o);if(Number.isFinite(r)&&Number.isFinite(s)&&!function(e,t){try{const t=e.meta?.formulaLines?.items??[];if(Array.isArray(t)&&t.length>0)return!0}catch{}try{const e=t.getOptions?.(),n=e?.look?.formulaLines;if("string"==typeof n&&""!==n&&"[]"!==n)return!0;if(Array.isArray(n)&&n.length>0)return!0}catch{}return!1}(e,n))try{(0,a.u)(n,r,s)}catch{}}}}const n=function(e){try{const t=o.shell.tables;return Array.isArray(t)?t.find(t=>t!==e&&"true"===t?.getTag?.("proteomics.enrichment")&&"true"===t?.getTag?.(s.L6.PUBLISHED))??null:null}catch{return null}}(e);if(n&&"true"!==n.getTag(l))try{(0,i.aB)(n,e),n.setTag(l,"true")}catch{}}},807(e,t,n){"use strict";n.d(t,{u:()=>f,M:()=>g});var o=n(328),r=n(82),s=n(749),a=n(771),i=n(641),l=n(304);function c(e,t){let n,o;switch(e.columns.contains(t.name)&&e.columns.remove(t.name),t.type){case"datetime":n=e.columns.addNewDateTime(t.name);break;case"float":n=e.columns.addNewFloat(t.name);break;case"int":n=e.columns.addNewInt(t.name);break;default:n=e.columns.addNewString(t.name)}if(null==t.value){if(!t.emptyForNull)return;o="string"===t.type?"":0}else o=t.value instanceof Date?t.value:"boolean"==typeof t.value?t.value?"true":"false":"string"===t.type?String(t.value):t.value;n.init(()=>o),n.setTag(".hidden","true")}var u=n(691),m=n(70),p=n(897),d=n(637);function f(e,t,n){const o=e.dataFrame;if(!o)return;let r=null;try{const t=e.getOptions?.();r=t?.look?.yColumnName??null}catch{}if(!r)try{r=e.props?.yColumnName??null}catch{}if(!r)return;const s=`\${${r}}`,a="${log2FC}",i=-Math.log10(n),l=o.meta,c=l?.formulaLines;if(c){try{const e=Array.isArray(c.items)?c.items:[];c.items=e.filter(e=>{const t=e?.formula??"";return!("string"==typeof t&&(t.startsWith(s)||t.startsWith(a)))})}catch{}try{c.addLine({formula:`${s} = ${i}`,color:"#888888",width:1,visible:!0}),c.addLine({formula:`${a} = ${t}`,color:"#888888",width:1,visible:!0}),c.addLine({formula:`${a} = ${-t}`,color:"#888888",width:1,visible:!0})}catch{}try{e.props.showViewerFormulaLines=!0}catch{}}}async function g(e,t){const n=r.TaskBarProgressIndicator.create("Publishing snapshot...");try{n.description="Preparing metadata...";const g=o.shell.user?.friendlyName??"",h=o.shell.user?.email??null,y=e.getTag("proteomics.de_method")??"t-test";let E=i.M5,w=i.Dx;try{const e=t;"number"==typeof e.fcThreshold&&Number.isFinite(e.fcThreshold)&&(E=e.fcThreshold),"number"==typeof e.pThreshold&&Number.isFinite(e.pThreshold)&&(w=e.pThreshold)}catch{}const v=(0,a.fz)(t.target),_=function(e){if(!e)return 0;const t=/-v(\d+)-/.exec(e);if(!t)return 0;const n=parseInt(t[1],10);return Number.isFinite(n)?n:0}(t.priorVersion?.name),C=_>0?_+1:1,b=function(){try{const e=globalThis?.crypto;if(e&&"function"==typeof e.randomUUID)return e.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}(),T=new Date,P=T.toISOString().slice(0,10),S=(()=>{const e=o.shell.tables;return Array.isArray(e)?e.find(e=>"true"===e.getTag("proteomics.enrichment"))??null:null})(),N={target:t.target,publishedAt:T,publishedBy:g,publishedByEmail:h,deMethod:y,fcThreshold:E,pThreshold:w,version:C,publishId:b,includesEnrichment:!!S,supersedes:t.priorVersion?.id??null,supersededBy:null};n.description="Trimming snapshot...";const A=function(e,t){const n=(0,l.I)(e),o=n.proteinId,r=n.geneName,s=n.log2fc,u=(0,l.k)(e,"",["adj.p-value","adj.p","fdr","q-value"]),m=e.columns.toList().find(e=>{const t=e.name.toLowerCase();return("p-value"===t||"pvalue"===t)&&e.name!==(u?.name??"")})??null,p=(0,l.k)(e,"",["significant","sig"]),d=(0,l.k)(e,"",["direction","regulation","up_down"]),f=[["Protein ID",o],["log2FC",s],["p-value",m],["adj.p-value",u],["significant",p]];for(const[e,t]of f)if(null==t)throw new Error(`Cannot publish: missing required column [${e}]. Run Differential Expression to completion before publishing.`);const g=Array.from(new Set([o.name,r?.name,s.name,m.name,u.name,p.name,d?.name].filter(e=>"string"==typeof e&&e.length>0))),h=e.clone(null,g),y=["proteomics.source","proteomics.de_method","proteomics.groups","proteomics.de_complete"];for(const t of y){const n=e.getTag(t);null!=n&&""!==n&&h.setTag(t,n)}(0,a.W7)(h,t);const E=t.publishedAt instanceof Date?t.publishedAt.toISOString().slice(0,10):new Date(String(t.publishedAt)).toISOString().slice(0,10);h.name=`${e.name||"analysis"}_published_${E}`;const w=[[o,i.iu.PROTEIN_ID],[r,i.iu.GENE_SYMBOL],[s,i.iu.LOG2FC],[m,i.iu.P_VALUE]];for(const[e,t]of w){if(null==e)continue;const n=h.col(e.name);null!=n&&(n.semType=t)}const v=t.includesEnrichment?"true":"false",_=[{name:a.MD.PUBLISHED,value:"true",type:"string"},{name:a.MD.PUBLISHED_AT,value:t.publishedAt,type:"datetime"},{name:a.MD.PUBLISHED_BY,value:t.publishedBy,type:"string"},{name:a.MD.PUBLISHED_BY_EMAIL,value:t.publishedByEmail??"",type:"string",emptyForNull:!0},{name:a.MD.PUBLISHED_TARGET,value:t.target,type:"string"},{name:a.MD.PUBLISHED_DE_METHOD,value:t.deMethod,type:"string"},{name:a.MD.PUBLISHED_FC_THRESHOLD,value:String(t.fcThreshold),type:"string"},{name:a.MD.PUBLISHED_P_THRESHOLD,value:String(t.pThreshold),type:"string"},{name:a.MD.PUBLISHED_VERSION,value:String(t.version),type:"string"},{name:a.MD.PUBLISHED_ID,value:t.publishId,type:"string"},{name:a.MD.PUBLISHED_INCLUDES_ENRICHMENT,value:v,type:"string"},{name:a.MD.SUPERSEDES,value:t.supersedes??"",type:"string",emptyForNull:!0},{name:a.MD.SUPERSEDED_BY,value:t.supersededBy??"",type:"string",emptyForNull:!0}];for(const e of _)c(h,e);return h}(e,N),x=A.name;let D=null;S&&(n.description="Trimming enrichment...",D=function(e,t){const n=(0,l.k)(e,"",["term name","term","pathway"]),o=(0,l.k)(e,"",["source"]),r=(0,l.k)(e,"",["fdr","adj.p-value","adj.p","q-value","p-value","pvalue"]),s=(0,l.k)(e,"",["intersection","genes"]),i=(0,l.k)(e,"",["direction","regulation"]),u=(0,l.k)(e,"",["gene ratio"]),m=(0,l.k)(e,"",["gene count"]),p=[["Term Name",n],["Source",o],["significance (FDR / adj.p-value)",r],["Intersection",s]];for(const[e,t]of p)if(null==t)throw new Error(`Cannot publish enrichment: missing required column [${e}]. Re-run enrichment before publishing.`);const d=[n.name,o.name,r.name,s.name,i?.name,u?.name,m?.name].filter(e=>"string"==typeof e&&e.length>0),f=e.clone(null,d);f.setTag("proteomics.enrichment","true");const g=t.publishedAt instanceof Date?t.publishedAt.toISOString().slice(0,10):new Date(String(t.publishedAt)).toISOString().slice(0,10);return f.name=`enrichment_published_${g}`,c(f,{name:a.MD.PUBLISHED_ID,value:t.publishId,type:"string"}),c(f,{name:a.MD.PUBLISHED_INCLUDES_ENRICHMENT,value:"true",type:"string"}),f.setTag(a.L6.PUBLISHED,"true"),f.setTag(a.L6.PUBLISHED_ID,t.publishId),f.setTag(a.L6.PUBLISHED_INCLUDES_ENRICHMENT,"true"),f}(S,N)),n.description="Ensuring umbrella Space...";const L=t.umbrellaName??(0,d.ck)(),F=o.dapi;let I=null;try{I=await F.spaces.createRootSpace(L)}catch(e){const t=String(e?.message??e??"");if(!/already exists|exists/i.test(t))throw e;try{I=(await F.spaces.list()??[]).find(e=>e?.name===L||e?.friendlyName===L)??null}catch{}if(!I)throw new Error(`Umbrella Space '${L}' exists on the server but could not be resolved by name from spaces.list() (msg: ${t}). Ask an admin to inspect the conflicting Space.`)}const M=F.spaces.id(I.id);n.description="Ensuring per-target Space...";const O=`${(0,d.sK)()}-${v}`;let R=null;const G=async()=>{try{return(await M.children.filter("Project",!1).list()??[]).find(e=>e?.friendlyName===O||e?.name===O)??null}catch{return null}};try{await M.subspaceExists(O)&&(R=await G())}catch{}if(!R)try{R=await M.addSubspace(O)}catch(e){const t=String(e?.message??e??"");if(!/already exists|exists/i.test(t))throw e;if(R=await G(),!R)throw new Error(`Per-target child Space '${O}' exists but could not be resolved via umbrella children.list() (msg: ${t}).`)}const k=F.spaces.id(R.id);n.description="Saving Project...";const $=r.Project.create(),B=`${(0,d.sK)()}-${v}-v${C}-${P}`;$.name=B,$.friendlyName=`${(0,d.sK)().replace(/-/g," ")} ${t.target} v${C} ${P}`;try{$.options[a.L6.PUBLISHED_ID]=b}catch{}if(null!=t.priorVersion)try{$.options[a.L6.SUPERSEDES]=t.priorVersion.id}catch{}$.addChild(A.getTableInfo()),D&&$.addChild(D.getTableInfo()),n.description="Re-rendering volcano on trimmed snapshot...";const U=o.shell.addTableView(A);await(0,s.cb)(100);const j=(0,m.gO)(A,{fcThreshold:E,pThreshold:w});U.addViewer(j),f(j,E,w),await(0,s.cb)(100);const V=U.getInfo();$.addChild(V);let q=null;if(D){n.description="Re-rendering enrichment charts...";const e=o.shell.addTableView(D);await(0,s.cb)(100),(0,p.YS)(e,D),await(0,s.cb)(100),q=e.getInfo(),$.addChild(q),o.shell.v=U}await o.dapi.tables.uploadDataFrame(A),await o.dapi.tables.save(A.getTableInfo()),D&&(await o.dapi.tables.uploadDataFrame(D),await o.dapi.tables.save(D.getTableInfo())),await o.dapi.views.save(V),q&&await o.dapi.views.save(q),await o.dapi.projects.save($);try{await k.addEntity($.id)}catch(e){o.shell.warning(`Could not move Project into child Space "${O}": ${e?.message??e}. Continuing — reviewer view grant is applied directly to the Project.`)}n.description="Granting reviewer view-only access...";try{await o.dapi.permissions.grant($,t.reviewerGroup,!1)}catch(e){try{await o.dapi.projects.delete($)}catch(e){o.shell.error(`Manual cleanup required: project id ${$.id} could not be deleted: ${e?.message??e}`)}throw new Error(`Reviewer group view grant failed: ${e?.message??e}`)}n.description="Verifying view-only access...";const Y=t.reviewerGroup?.id,z=e=>null!=e&&("string"==typeof e?e===Y:null!=e?.id&&e.id===Y),H=await o.dapi.permissions.get($);let Q=null,W=null;try{R&&(Q=await o.dapi.permissions.get(R))}catch{}try{I&&(W=await o.dapi.permissions.get(I))}catch{}const K=e=>{for(const t of[H,Q,W]){const n=t?.[e];if(Array.isArray(n)&&n.some(z))return!0}return!1},J=K("view"),Z=K("edit"),X=K("share"),ee=K("delete");if(!J||Z||X||ee){try{await o.dapi.projects.delete($)}catch(e){o.shell.error(`Manual cleanup required: project id ${$.id} could not be deleted: ${e?.message??e}`)}throw new Error("Reviewer group already has elevated access via Space inheritance — publish aborted; ask an admin to scope the umbrella Space's permissions")}if(t.verify??(0,d.Cb)()){n.description="Verifying round-trip survival...";const e={expectedName:x,expectedProjectName:B,expectedAllowlist:A.columns.toList().map(e=>e.name).filter(e=>!e.startsWith("_meta_")&&!e.startsWith("~")),expectedMeta:{...N},expectVolcano:!0,expectEnrichment:!!D,expectFormulaLines:!0};let t=!1;for(;;)try{await(0,u.F)($,e);break}catch(e){const n=String(e?.message??e??"");if(!t&&n.startsWith(u.Y)){t=!0;const e=o.shell.tv,n=e?Array.from(e.viewers).find(e=>e.type===r.VIEWER.SCATTER_PLOT):null;if(n&&e){const t=e.dataFrame,r=parseFloat(t.getTag(a.L6.PUBLISHED_FC_THRESHOLD)??String(E)),i=parseFloat(t.getTag(a.L6.PUBLISHED_P_THRESHOLD)??String(w));f(n,Number.isFinite(r)?r:E,Number.isFinite(i)?i:w);try{await o.dapi.views.save(e.getInfo())}catch{}await(0,s.cb)(100);continue}}try{await o.dapi.projects.delete($)}catch(e){o.shell.error(`Manual cleanup required: project id ${$.id} could not be deleted: ${e?.message??e}`)}throw new Error(`Round-trip shape verification failed: ${e?.message??e}`)}}if(null!=t.priorVersion){n.description="Updating supersede chain...";const e=t.priorVersion.id;try{const t=await o.dapi.projects.find(e);t.options[a.L6.SUPERSEDED_BY]=$.id,await o.dapi.projects.save(t)}catch(e){o.shell.warning(`Supersede pointer on prior version's options failed: ${e?.message??e} (DataFrame-tag dual-write path below provides fallback).`)}try{o.shell.closeAll(),await(0,s.cb)(100);const t=await o.dapi.projects.find(e);await t.open(),await(0,s.bk)(()=>!!o.shell.tv&&!!o.shell.tv.dataFrame,"supersede stamp: prior project DF did not materialize",5e3);const n=o.shell.tv.dataFrame;n.setTag(a.L6.SUPERSEDED_BY,$.id);const r=n.col(a.MD.SUPERSEDED_BY);if(r)try{r.set(0,$.id)}catch{}await o.dapi.tables.uploadDataFrame(n),await o.dapi.tables.save(n.getTableInfo())}catch(e){o.shell.warning(`Supersede tag could not be stamped on prior version DF: ${e?.message??e} (Project.options pointer was still written — Plan 06 panel falls back to that path)`)}try{$.options[a.L6.SUPERSEDES]=e}catch{}try{await o.dapi.projects.save($)}catch(e){o.shell.warning(`Could not write supersedes pointer on new project options: ${e?.message??e}`)}}n.description="Restoring your analysis...";try{if(o.shell.closeAll(),await(0,s.cb)(100),S)try{(0,p.q6)(S,e)}catch{}const t=o.shell.addTableView(e);try{t.addViewer((0,m.gO)(e))}catch{}}catch{}return n.description="Done.",$}finally{n.close()}}},637(e,t,n){"use strict";n.d(t,{Cb:()=>i,ck:()=>s,sK:()=>a});var o=n(110);function r(e,t){try{const t=o._package?.settings?.[e];if("string"==typeof t&&t.trim().length>0)return t.trim()}catch{}return t}function s(){return r("reviewSpaceName","Proteomics-Reviews")}function a(){return r("reviewNamePrefix","Proteomics-Review")}function i(){try{const e=o._package?.settings?.verifyPublishedDashboard;if(!1===e||"false"===e)return!1;if(!0===e||"true"===e)return!0}catch{}return!0}},771(e,t,n){"use strict";n.d(t,{$y:()=>s,HF:()=>l,Kj:()=>d,L6:()=>a,M4:()=>c,MD:()=>i,T7:()=>p,W7:()=>u,fz:()=>m});var o=n(328),r=n(637);const s="proteomics.de_complete",a={PUBLISHED:"proteomics.published",PUBLISHED_AT:"proteomics.published_at",PUBLISHED_BY:"proteomics.published_by",PUBLISHED_BY_EMAIL:"proteomics.published_by_email",PUBLISHED_TARGET:"proteomics.published_target",PUBLISHED_DE_METHOD:"proteomics.published_de_method",PUBLISHED_FC_THRESHOLD:"proteomics.published_fc_threshold",PUBLISHED_P_THRESHOLD:"proteomics.published_p_threshold",PUBLISHED_VERSION:"proteomics.published_version",PUBLISHED_ID:"proteomics.published_id",PUBLISHED_INCLUDES_ENRICHMENT:"proteomics.published_includes_enrichment",SUPERSEDED_BY:"proteomics.superseded_by",SUPERSEDES:"proteomics.supersedes"},i={PUBLISHED:"_meta_published",PUBLISHED_AT:"_meta_published_at",PUBLISHED_BY:"_meta_published_by",PUBLISHED_BY_EMAIL:"_meta_published_by_email",PUBLISHED_TARGET:"_meta_published_target",PUBLISHED_DE_METHOD:"_meta_published_de_method",PUBLISHED_FC_THRESHOLD:"_meta_published_fc_threshold",PUBLISHED_P_THRESHOLD:"_meta_published_p_threshold",PUBLISHED_VERSION:"_meta_published_version",PUBLISHED_ID:"_meta_published_id",PUBLISHED_INCLUDES_ENRICHMENT:"_meta_published_includes_enrichment",SUPERSEDED_BY:"_meta_superseded_by",SUPERSEDES:"_meta_supersedes"};function l(e){return"true"===e.getTag(a.PUBLISHED)}function c(e){if(!l(e))return null;const t=(t,n)=>{try{const n=e.col(i[t]);if(null!=n){const e=n.get(0);if(null!=e&&""!==e)return String(e)}}catch{}try{return e.getTag(a[n])??null}catch{return null}},n=(e,n)=>{const o=t(e,n);if(null==o)return NaN;const r=parseFloat(o);return Number.isFinite(r)?r:NaN},o=t("PUBLISHED_TARGET","PUBLISHED_TARGET"),r=t("PUBLISHED_ID","PUBLISHED_ID");if(null==o||null==r)return null;const s=(()=>{try{const t=e.col(i.PUBLISHED_AT);if(null!=t){const e=t.get(0);if(e instanceof Date)return e;if("string"==typeof e&&e)return new Date(e);if("number"==typeof e)return new Date(e)}}catch{}try{const t=e.getTag(a.PUBLISHED_AT);if(t)return new Date(t)}catch{}return null})(),c=t("PUBLISHED_VERSION","PUBLISHED_VERSION"),u=null!=c?parseInt(c,10):NaN;return{target:o,publishedAt:s??new Date(NaN),publishedBy:t("PUBLISHED_BY","PUBLISHED_BY")??"",publishedByEmail:t("PUBLISHED_BY_EMAIL","PUBLISHED_BY_EMAIL"),deMethod:t("PUBLISHED_DE_METHOD","PUBLISHED_DE_METHOD")??"",fcThreshold:n("PUBLISHED_FC_THRESHOLD","PUBLISHED_FC_THRESHOLD"),pThreshold:n("PUBLISHED_P_THRESHOLD","PUBLISHED_P_THRESHOLD"),version:Number.isFinite(u)?u:1,publishId:r,includesEnrichment:"true"===t("PUBLISHED_INCLUDES_ENRICHMENT","PUBLISHED_INCLUDES_ENRICHMENT"),supersedes:t("SUPERSEDES","SUPERSEDES"),supersededBy:t("SUPERSEDED_BY","SUPERSEDED_BY")}}function u(e,t){e.setTag(a.PUBLISHED,"true"),e.setTag(a.PUBLISHED_AT,t.publishedAt instanceof Date?t.publishedAt.toISOString():String(t.publishedAt)),e.setTag(a.PUBLISHED_BY,t.publishedBy),null!=t.publishedByEmail&&e.setTag(a.PUBLISHED_BY_EMAIL,t.publishedByEmail),e.setTag(a.PUBLISHED_TARGET,t.target),e.setTag(a.PUBLISHED_DE_METHOD,t.deMethod),e.setTag(a.PUBLISHED_FC_THRESHOLD,String(t.fcThreshold)),e.setTag(a.PUBLISHED_P_THRESHOLD,String(t.pThreshold)),e.setTag(a.PUBLISHED_VERSION,String(t.version)),e.setTag(a.PUBLISHED_ID,t.publishId),e.setTag(a.PUBLISHED_INCLUDES_ENRICHMENT,t.includesEnrichment?"true":"false"),null!=t.supersedes&&e.setTag(a.SUPERSEDES,t.supersedes),null!=t.supersededBy&&e.setTag(a.SUPERSEDED_BY,t.supersededBy)}function m(e){if(null==e)return"unnamed";let t=String(e).replace(/[^A-Za-z0-9._-]+/g,"-").replace(/-{2,}/g,"-").replace(/^[-.]+|[-.]+$/g,"").slice(0,64).replace(/[-.]+$/g,"");return 0===t.length&&(t="unnamed"),t}async function p(e,t){const n=m(e),s=`${(0,r.sK)()}-${n}-v`,a=/-v(\d+)-/,i=e=>{let t=null,n=-1;for(const o of e){const e=o?.name??"",r=a.exec(e);if(!r)continue;const s=parseInt(r[1],10);Number.isFinite(s)&&s>n&&(n=s,t=o)}return t};try{const e=`${s}%`,t=await o.dapi.projects.filter(`name like "${e}"`).list();if(Array.isArray(t)&&t.length>0)return i(t)}catch{}try{const e=await o.dapi.projects.list(),t=(Array.isArray(e)?e:[]).filter(e=>(e?.name??"").startsWith(s));if(t.length>0)return i(t)}catch{}return null}function d(e){const t=`Re-run request: ${e.projectName}`,n=`Hi ${e.sharerName}, could you re-run with [different parameters]? Looking at ${e.projectName} (shared ${e.publishedDateStr}).`;return`mailto:${e.sharerEmail?encodeURIComponent(e.sharerEmail):""}?subject=${encodeURIComponent(t)}&body=${encodeURIComponent(n)}`}},304(e,t,n){"use strict";n.d(t,{I:()=>s,k:()=>r});var o=n(641);function r(e,t,n){const o=e.columns.toList().find(e=>e.semType===t);if(o)return o;for(const t of n){const n=t.toLowerCase(),o=e.columns.toList().find(e=>e.name.toLowerCase().includes(n));if(o)return o}return null}function s(e){return{proteinId:r(e,o.iu.PROTEIN_ID,["protein id","majority protein id","accession","uniprot"]),geneName:r(e,o.iu.GENE_SYMBOL,["gene name","gene symbol"]),log2fc:r(e,o.iu.LOG2FC,["log2fc","log2 fold","logfc"]),pValue:r(e,o.iu.P_VALUE,["p-value","pvalue","adj.p","fdr","q-value"])}}},117(e,t,n){"use strict";n.d(t,{FH:()=>h,I5:()=>i,KK:()=>g,Rw:()=>l,eA:()=>d,no:()=>p,oA:()=>m,qo:()=>f,rv:()=>E});var o=n(328),r=n(304),s=n(641),a=n(623);const i="proteomics-gene-labels",l="14-r1-1",c="__schema_v",u=["ENSRNOG","ENSMUSG","LOC","ENSG","ENSDARG","ENSRNO","MGP_","RGD","AABR"];function m(e){return e.startsWith("ENS")||e.startsWith("MGP_")}function p(e){for(const t of u)if(e.startsWith(t))return!0;return!1}function d(e){return e.startsWith("ENSG")?"homo_sapiens":e.startsWith("ENSMUSG")||e.startsWith("MGP_")?"mus_musculus":e.startsWith("ENSRNOG")||e.startsWith("ENSRNO")?"rattus_norvegicus":e.startsWith("ENSDARG")?"danio_rerio":null}function f(e){if(null==e||""===e)return null;let t=String(e);t=t.split("[")[0].trim(),t=t.replace(/^Predicted to enable\s+/i,""),t=t.replace(/^Predicted to be involved in\s+/i,""),t=t.replace(/^Predicted to be located in\s+/i,""),t=t.replace(/^Predicted to be part of\s+/i,""),t=t.replace(/^Predicted to be\s+/i,""),t=t.replace(/^Predicted to\s+/i,"");const n=t.split(".");return n.length>0&&(t=n[0].trim()),t=t.replace(/_RAT$/i,""),t=t.replace(/_MOUSE$/i,""),t=t.replace(/_HUMAN$/i,""),t.length>0&&t[0]===t[0].toLowerCase()&&t[0]!==t[0].toUpperCase()&&(t=t[0].toUpperCase()+t.slice(1)),t.length>60&&(t=t.slice(0,57)+"..."),""===t||t.length<3||t.toLowerCase().includes("uncharacterized")?null:t}function g(e,t,n){return e+(t?"*":"")+(n?"†":"")}async function h(e){const t=new Map;if(0===e.length)return t;const n=async()=>o.dapi.fetchProxy("https://rest.ensembl.org/lookup/id",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({ids:e})});let r,s;try{r=await n()}catch(e){return console.warn(`Ensembl lookup/id batch failed (network): ${e?.message??e}`),t}if(429===r.status){const e=parseFloat(r.headers.get("Retry-After")??"1"),o=Math.min(3e4,Math.max(0,1e3*e));await new Promise(e=>setTimeout(e,o));try{r=await n()}catch(e){return console.warn(`Ensembl lookup/id retry failed: ${e?.message??e}`),t}}if(!r.ok)return console.warn(`Ensembl lookup/id returned status ${r.status}; continuing`),t;try{s=await r.json()}catch(e){return console.warn(`Ensembl lookup/id JSON parse failed: ${e?.message??e}`),t}if(s&&"object"==typeof s)for(const[e,n]of Object.entries(s))if(n&&"object"==typeof n){const o=n,r={};"string"==typeof o.display_name&&(r.display_name=o.display_name),"string"==typeof o.external_name&&(r.external_name=o.external_name),"string"==typeof o.description&&(r.description=o.description),"string"==typeof o.species&&(r.species=o.species),"string"==typeof o.biotype&&(r.biotype=o.biotype),"string"==typeof o.object_type&&(r.object_type=o.object_type),t.set(e,r)}return t}function y(e,t){if(!t)return null;const n=[t.external_name,t.display_name,t.description?t.description.split("[")[0].trim():void 0];for(const t of n)if(t&&t!==e&&!p(t))return t;return null}async function E(e,t){const n=(0,r.k)(e,s.iu.GENE_SYMBOL,["gene name","gene names","gene symbol"]),u=e.rowCount,d=new Array(u).fill(""),E=new Array(u).fill("");if(null!=n)for(let e=0;e<u;e++){const t=n.get(e),o=null==t?"":String(t);d[e]=o}const w=(0,r.k)(e,s.iu.PROTEIN_ID,["protein ids","primary protein id","protein id","majority protein ids","accession","uniprot"]),v=[],_=(e,t,n)=>{if(!t)return!1;const o=t.includes("*"),r=t.replace(/[*†]/g,"");return!!p(r)&&(v.push({row:e,clean:r,hadAsterisk:o,source:n}),!0)};for(let e=0;e<u;e++){const t=null!=n?n.get(e):null;if(!_(e,null==t?"":String(t),"gene")&&null!=w){const t=w.get(e);_(e,null==t?"":String(t).split(";")[0],"protein")}}for(const t of["Display Name","Source ID"])null!=e.col(t)&&e.columns.remove(t);if(0===v.length){const t=e.columns.addNewString("Display Name");t.init(e=>d[e]),t.semType=s.iu.DISPLAY_NAME;const n=e.columns.addNewString("Source ID");return n.init(e=>E[e]),void(n.semType=s.iu.SOURCE_ID)}const C=[...new Set(v.map(e=>e.clean))].filter(e=>m(e)),b=await async function(){try{const e=await o.dapi.userDataStorage.get(i)??{};return e[c]!==l?{[c]:l}:e}catch{return{[c]:l}}}(),T={},P=new Map;for(const e of C){const t=b[e];t&&"object"==typeof t&&P.set(e,t)}const S=C.filter(e=>!P.has(e));let N=!1;if(S.length>0){const e=function(e){const t=[];for(let n=0;n<e.length;n+=1e3)t.push(e.slice(n,n+1e3));return t}(S),n=e.length;let r=0;try{await(0,a.Pd)(e,6,async e=>{const o=await h(e);for(const[e,t]of o)P.set(e,t),T[e]=t;for(const t of e)o.has(t)||(N=!0);r++,t?.(r,n,"lookup")})}finally{await async function(e,t){try{await o.dapi.userDataStorage.put(i,{...e,...t,[c]:l})}catch(e){console.warn(`Gene-label cache write failed: ${e?.message??e}`)}}(b,T)}}const A=e.col("Protein Descriptions")??e.col("Protein names")??e.col("Description")??e.col("protein_descriptions");for(const e of v){const t=P.get(e.clean);let n=y(e.clean,t);if(null==n&&null!=t){const o=f(t.description??null);null==o||o===e.clean||p(o)||(n=o)}if(null==n&&null!=A){const t=A.get(e.row),o=f(null==t?null:String(t));null!=o&&o!==e.clean&&!p(o)&&o.length>3&&(n=o)}const o=g(n??e.clean,e.hadAsterisk,!0);d[e.row]=o,E[e.row]=e.clean}t?.(v.length,v.length,"apply");const x=new Map,D=new Map;for(let e=0;e<u;e++){const t=d[e],n=E[e];t&&n&&(x.has(t)||x.set(t,new Set),x.get(t).add(n),D.has(t)||D.set(t,[]),D.get(t).push(e))}let L=0;for(const[e,t]of x)if(!(t.size<=1))for(const t of D.get(e)??[]){const n=E[t];n&&(d[t]=`${e} (${n})`,L++)}if(L>0&&o.shell.warning(`${L} duplicate gene names disambiguated with source IDs.`),N){const e=v.filter(e=>m(e.clean)&&!P.has(e.clean)).length;o.shell.warning(`Ensembl gene-label resolution unavailable. Showing raw IDs (${e} unresolved). Re-import to retry.`)}const F=e.columns.addNewString("Display Name");F.init(e=>d[e]),F.semType=s.iu.DISPLAY_NAME;const I=e.columns.addNewString("Source ID");I.init(e=>E[e]),I.semType=s.iu.SOURCE_ID}},935(e,t,n){"use strict";n.d(t,{$S:()=>a,Ae:()=>o,Vr:()=>c,X3:()=>s,qj:()=>i});const o=[{display:"Homo sapiens (Human)",code:"hsapiens"},{display:"Mus musculus (Mouse)",code:"mmusculus"},{display:"Rattus norvegicus (Rat)",code:"rnorvegicus"},{display:"Saccharomyces cerevisiae (Yeast)",code:"scerevisiae"},{display:"Escherichia coli (K12)",code:"ecoli"},{display:"Danio rerio (Zebrafish)",code:"drerio"},{display:"Drosophila melanogaster (Fruit fly)",code:"dmelanogaster"},{display:"Arabidopsis thaliana",code:"athaliana"},{display:"Caenorhabditis elegans",code:"celegans"}],r=o.map(e=>({scientific:e.display.split("(")[0].trim().toLowerCase(),code:e.code}));function s(e){return o.find(t=>t.code===e)?.display}function a(e){return o.find(t=>t.display===e)?.code}function i(e){if(!e)return;const t=e.toLowerCase();for(const{scientific:e,code:n}of r)if(t.includes(e))return n}const l=["pg.organisms","organism","organisms","species"];function c(e){const t=function(e){for(const t of e.columns.toList()){const e=t.name.toLowerCase();if(l.some(t=>e===t||e.includes(t)))return t}return null}(e);if(!t)return;const n=new Set;for(let e=0;e<t.length;e++){if(t.isNone(e))continue;const o=i(t.get(e));if(o&&n.add(o),n.size>1)return}return 1===n.size?[...n][0]:void 0}},641(e,t,n){"use strict";n.d(t,{Dx:()=>s,M5:()=>r,PL:()=>a,iu:()=>o});const o={PROTEIN_ID:"Proteomics-ProteinId",GENE_SYMBOL:"Proteomics-GeneSymbol",LOG2FC:"Proteomics-Log2FC",P_VALUE:"Proteomics-PValue",INTENSITY:"Proteomics-Intensity",SUBCELLULAR_LOCATION:"Proteomics-SubcellularLocation",DISPLAY_NAME:"Proteomics-DisplayName",SOURCE_ID:"Proteomics-SourceId",NUMERATOR_MEAN:"Proteomics-NumeratorMean",DENOMINATOR_MEAN:"Proteomics-DenominatorMean"},r=1,s=.05,a={enrichedG1:4294902015,enrichedG2:4278255615,notSig:4289374890}},897(e,t,n){"use strict";n.d(t,{$i:()=>m,E0:()=>p,YS:()=>w,aB:()=>h,bC:()=>u,q6:()=>E});var o=n(328),r=n(389),s=n(82),a=n(858),i=n(304),l=n(641);let c=[];const u="negLog10FDR",m="~enrichChartTop";function p(e,t=15){const n=e.col("FDR");if(!n)return;const o=-Math.log10(Number.MIN_VALUE),r=n.getRawData();e.columns.contains(u)&&e.columns.remove(u);const s=e.columns.addNewFloat(u);s.init(e=>r[e]>0?-Math.log10(r[e]):o),s.setTag(".hidden","true");const a=e.col("Direction"),i=new Map;for(let t=0;t<e.rowCount;t++){if(n.isNone(t))continue;const e=a?String(a.get(t)):"";i.has(e)||i.set(e,[]),i.get(e).push({idx:t,fdr:n.get(t)})}const l=new Array(e.rowCount).fill(!1);for(const e of i.values()){e.sort((e,t)=>e.fdr-t.fdr);for(let n=0;n<Math.min(t,e.length);n++)l[e[n].idx]=!0}e.columns.contains(m)&&e.columns.remove(m),e.columns.addNewBool(m).init(e=>l[e])}function d(e){const t=[`\${${m}}`];return e&&t.push(`\${Direction} == "${e}"`),t.join(" and ")}function f(e,t){return s.Viewer.scatterPlot(e,{x:"Gene Ratio",y:"Term Name",sizeColumnName:"Gene Count",colorColumnName:u,markerMinSize:5,markerMaxSize:25,filter:d(t),title:t?`Enrichment — ${t}`:"Enrichment Dot Plot"})}function g(e,t){return s.Viewer.barChart(e,{splitColumnName:"Term Name",valueColumnName:u,valueAggrType:"avg",barSortType:"by value",barSortOrder:"desc",orientation:"Horizontal",filter:d(t),title:t?`Top Enriched — ${t}`:"Top Enriched Terms"})}function h(e,t){const n=(0,i.k)(t,l.iu.GENE_SYMBOL,["gene name","gene symbol"]);if(!n)return a.Subscription.EMPTY;const o=new Map;for(let e=0;e<t.rowCount;e++)if(!n.isNone(e)){const t=n.get(e).trim();o.has(t)||o.set(t,[]),o.get(t).push(e)}return e.onCurrentRowChanged.subscribe(()=>{const n=e.currentRowIdx;if(n<0)return;const r=e.col("Intersection");if(!r)return;const s=r.get(n);if(!s)return;const a=s.split(",").map(e=>e.trim()).filter(Boolean);t.selection.setAll(!1,!1);for(const e of a){const n=o.get(e);if(n)for(const e of n)t.selection.set(e,!0,!1)}t.selection.fireChanged()})}function y(e,t){const n=e.col("Direction");if(!n)return!1;for(let o=0;o<e.rowCount;o++)if(n.get(o)===t)return!0;return!1}function E(e,t){for(const e of c)e.unsubscribe();let n;c=[];for(const t of o.shell.tableViews)if(t.dataFrame?.dart===e.dart){n=t;break}const a=n??o.shell.addTableView(e);o.shell.v=a;const i=a;if("true"===e.getTag("proteomics.enrichment_smart_filtered")){const t=e.getTag("proteomics.enrichment_smart_filtered_kept")??"?",n=e.getTag("proteomics.enrichment_smart_filtered_total")??"?",o=e.getTag("proteomics.enrichment_smart_filtered_dropped_parents")??"?",i=e.getTag("proteomics.enrichment_smart_filtered_cap")??"15",l=r.divText(`Smart pathway filter active: showing ${t} of ${n} terms (dropped ${o} generic parents, capped at ${i} per source). Re-run with the filter off to see all.`);l.dataset.smartFilterBanner="true",a.dockManager.dock(l,s.DOCK_TYPE.TOP,null,"Smart Filter Info",.1)}return w(i,e),c.push(h(e,t)),a}function w(e,t){if(p(t),y(t,"Up")&&y(t,"Down")){const n=e.dockManager.dock(f(t,"Up"),s.DOCK_TYPE.RIGHT,null,"Up — Dot Plot",.6),o=e.dockManager.dock(f(t,"Down"),s.DOCK_TYPE.RIGHT,n,"Down — Dot Plot",.5);return e.dockManager.dock(g(t,"Up"),s.DOCK_TYPE.DOWN,n,"Up — Bar Chart",.5),void e.dockManager.dock(g(t,"Down"),s.DOCK_TYPE.DOWN,o,"Down — Bar Chart",.5)}const n=e.dockManager.dock(f(t),s.DOCK_TYPE.RIGHT,null,"Dot Plot",.5);e.dockManager.dock(g(t),s.DOCK_TYPE.DOWN,n,"Bar Chart",.5)}},644(e,t,n){"use strict";n.d(t,{CN:()=>g,Z7:()=>h,hy:()=>p,nc:()=>d});var o=n(82),r=n(304),s=n(641),a=n(252);const i="Numerator Mean",l="Denominator Mean",c=`\${${i}} = \${${l}}`;function u(e,t){return e.columns.contains(t)&&e.columns.remove(t),e.columns.addNewFloat(t)}function m(e,t){let n=0,o=0;for(const r of e)r.isNone(t)||(n+=r.get(t),o++);return o>0?n/o:NaN}function p(e,t){const n=t.group1.columns.map(t=>e.col(t)).filter(e=>null!=e),r=t.group2.columns.map(t=>e.col(t)).filter(e=>null!=e),a=e.rowCount,c=new Float32Array(a),p=new Float32Array(a);for(let e=0;e<a;e++){const t=m(n,e),s=m(r,e);c[e]=isNaN(t)?o.FLOAT_NULL:t,p[e]=isNaN(s)?o.FLOAT_NULL:s}const d=u(e,i);d.init(e=>c[e]),d.semType=s.iu.NUMERATOR_MEAN;const f=u(e,l);f.init(e=>p[e]),f.semType=s.iu.DENOMINATOR_MEAN}function d(e,t){let n=0,r=0,s=0;for(let a=0;a<e.length;a++){const i=e[a],l=t[a];Number.isFinite(i)&&Number.isFinite(l)&&i!==o.FLOAT_NULL&&l!==o.FLOAT_NULL&&(r+=i,s+=l,n++)}if(0===n)return NaN;const a=r/n,i=s/n;let l=0,c=0,u=0;for(let n=0;n<e.length;n++){const r=e[n],s=t[n];if(!Number.isFinite(r)||!Number.isFinite(s)||r===o.FLOAT_NULL||s===o.FLOAT_NULL)continue;const m=r-a,p=s-i;l+=m*p,c+=m*m,u+=p*p}const m=Math.sqrt(c*u);return 0===m?NaN:l/m}function f(e){const t=e.map((e,t)=>({v:e,i:t}));t.sort((e,t)=>e.v-t.v);const n=new Array(e.length);let o=0;for(;o<t.length;){let e=o;for(;e+1<t.length&&t[e+1].v===t[o].v;)e++;const r=(o+e)/2+1;for(let s=o;s<=e;s++)n[t[s].i]=r;o=e+1}return n}function g(e,t){return d(f(e),f(t))}function h(e,t){const n=(0,a.f)(e);if(!n)throw new Error("Annotate experimental groups first (Proteomics | Annotate Experiment)");p(e,n);const u=e.plot.scatter({x:i,y:l,color:"direction"}),m=(0,r.k)(e,s.iu.DISPLAY_NAME,["display name"])??(0,r.k)(e,s.iu.GENE_SYMBOL,["gene name","gene symbol"]);m&&(u.props.labelColumnNames=[m.name],u.props.showLabelsFor="MouseOverRow"),e.meta.formulaLines.items=e.meta.formulaLines.items.filter(e=>{const t=e.formula??"";return!("string"==typeof t&&t.includes(i)&&t.includes(l))}),e.meta.formulaLines.addLine({formula:c,color:"#888888",width:1,visible:!0}),u.props.showViewerFormulaLines=!0;const{r:f,rho:h}=function(e,t,n){const r=e.col(t),s=e.col(n);if(!r||!s)return{r:NaN,rho:NaN};const a=r.getRawData(),i=s.getRawData(),l=[],c=[];for(let t=0;t<e.rowCount;t++){if(!e.filter.get(t))continue;const n=a[t],r=i[t];n!==o.FLOAT_NULL&&r!==o.FLOAT_NULL&&Number.isFinite(n)&&Number.isFinite(r)&&(l.push(n),c.push(r))}return{r:d(l,c),rho:g(l,c)}}(e,i,l),y=t?.title??"Group-Mean Correlation",E=Number.isFinite(f)?f.toFixed(2):"NA",w=Number.isFinite(h)?h.toFixed(2):"NA";return u.setOptions({title:`${y} — r=${E} (Pearson), ρ=${w} (Spearman)`,xColumnLabel:`${n.group1.name} mean (log2 intensity)`,yColumnLabel:`${n.group2.name} mean (log2 intensity)`}),u}},715(e,t,n){"use strict";n.d(t,{Hc:()=>a,JZ:()=>m,Pq:()=>u,ho:()=>p,iQ:()=>c,j4:()=>d,rA:()=>f});var o=n(82),r=n(641),s=n(304);function a(e){return e.columns.toList().filter(e=>e.semType===r.iu.INTENSITY&&e.name.startsWith("log2(")).map(e=>e.name)}function i(e,t){let n=0,o=0;for(const r of e)r.isNone(t)||(n+=r.get(t),o++);return o>0?n/o:NaN}function l(e,t){return e.columns.contains(t)&&e.columns.remove(t),e.columns.addNewFloat(t)}function c(e,t){const n=t.group1.columns.map(t=>e.col(t)),r=t.group2.columns.map(t=>e.col(t)),s=e.rowCount,a=new Float32Array(s),c=new Float32Array(s);for(let e=0;e<s;e++){const t=i(n,e),s=i(r,e);isNaN(t)||isNaN(s)?(a[e]=o.FLOAT_NULL,c[e]=o.FLOAT_NULL):(a[e]=s-t,c[e]=(t+s)/2)}l(e,"M").init(e=>a[e]),l(e,"A").init(e=>c[e])}function u(e,t=.1){const n=e.col("A"),r=e.col("M");if(!n||!r)return void l(e,"MA_trend");const s=n.getRawData(),a=r.getRawData(),i=[];for(let t=0;t<e.rowCount;t++)s[t]!==o.FLOAT_NULL&&a[t]!==o.FLOAT_NULL&&i.push({idx:t,a:s[t],m:a[t]});const c=new Float32Array(e.rowCount);if(c.fill(o.FLOAT_NULL),i.length<3)return void l(e,"MA_trend").init(e=>c[e]);i.sort((e,t)=>e.a-t.a);const u=Math.max(Math.round(i.length*t/2),5);for(let e=0;e<i.length;e++){const t=Math.max(0,e-u),n=Math.min(i.length-1,e+u);let o=0,r=0;for(let e=t;e<=n;e++)o+=i[e].m,r++;c[i[e].idx]=o/r}l(e,"MA_trend").init(e=>c[e])}function m(e,t,n,r){const s=t.map(t=>e.col(t)).filter(e=>null!=e&&e.type===o.COLUMN_TYPE.FLOAT).map(e=>e.getRawData()),a=e.rowCount,i=new Float32Array(a),c=new Float32Array(a);for(let e=0;e<a;e++){let t=0,n=0,r=0;for(const a of s){const s=a[e];if(s!==o.FLOAT_NULL){const e=Math.pow(2,s);t++;const o=e-n;n+=o/t,r+=o*(e-n)}}if(t<1)i[e]=o.FLOAT_NULL,c[e]=o.FLOAT_NULL;else if(t<2)i[e]=o.FLOAT_NULL,c[e]=n;else{const s=r/(t-1),a=Math.sqrt(Math.max(0,s));i[e]=n>0?a/n:o.FLOAT_NULL,c[e]=n}}l(e,n).init(e=>i[e]),l(e,r).init(e=>c[e])}function p(e,t){const n=[],a=(0,s.k)(e,r.iu.PROTEIN_ID,["protein id","accession"]);a&&n.push(a.clone());for(const r of t){const t=e.col(r),s=t.type===o.COLUMN_TYPE.FLOAT?t.getRawData():null,a=new Int32Array(e.rowCount);if(s)for(let t=0;t<e.rowCount;t++)a[t]=s[t]===o.FLOAT_NULL?0:1;else for(let n=0;n<e.rowCount;n++)a[n]=t.isNone(n)?0:1;n.push(o.Column.fromInt32Array(r,a))}const i=o.DataFrame.fromColumns(n);return i.name="Missing Values",i}function d(e,t){const n=(0,s.k)(e,r.iu.PROTEIN_ID,["protein id","accession"]),a=[],i=[],l=[];for(let o=0;o<e.rowCount;o++){const r=n?n.get(o)??String(o):String(o);for(const n of t){const t=e.col(n);t.isNone(o)||(a.push(r),i.push(n),l.push(t.get(o)))}}const c=o.DataFrame.fromColumns([o.Column.fromStrings("ProteinId",a),o.Column.fromStrings("Sample",i),o.Column.fromFloat32Array("Intensity",new Float32Array(l))]);return c.name="Intensity Distributions",c}function f(e,t,n){const r=[],s=[],a=[],i=new Set(n.group1.columns),l=new Set(n.group2.columns);for(const o of t){const t=e.col(o);let c=0;for(let n=0;n<e.rowCount;n++)t.isNone(n)&&c++;r.push(o),s.push(c/e.rowCount*100),i.has(o)?a.push(n.group1.name):l.has(o)?a.push(n.group2.name):a.push("Other")}const c=o.DataFrame.fromColumns([o.Column.fromStrings("Sample",r),o.Column.fromFloat32Array("MissingPct",new Float32Array(s)),o.Column.fromStrings("Group",a)]);return c.name="Missing Values per Sample",c}},589(e,t,n){"use strict";n.d(t,{aggregateParetoCounts:()=>E,computeControlLines:()=>g,createSpcChartPanel:()=>y,r9:()=>C,resolveDrillDown:()=>h});var o=n(328),r=n(389),s=n(82),a=n(655),i=n(883);const l=["median_intensity","missing_pct","control_corr","protein_count"],c={median_intensity:"Median log2 intensity",missing_pct:"Missing %",control_corr:"Control replicate correlation",protein_count:"Protein count"},u="#888888",m="#666666",p="spc.last_picked_instrument",d={rule_1_only:"Expected false-alarm rate at this rule set: ~0.27%. (Rule 1 only — a point beyond 3σ.)",rules_1_5:"Expected false-alarm rate at this rule set: ~0.4%. (Rules 1 + 5 — a single point beyond 3σ, or 2 of 3 beyond 2σ.)",rules_1_5_2:"Enabling rules 1+5+2 raises the expected false-alarm rate to ~1.1%.",rules_all_8:"Expected false-alarm rate at this rule set: ~2.65%. Enabling all 8 rules will flag roughly 1 in 38 normal-operation runs.",rules_other:"More rules enabled → higher false-alarm rate. The Nelson 1+5 default is calibrated for ~0.4%."};function f(e){const t=e.median_intensity,n=Object.entries(t).filter(([e,t])=>t).map(([e])=>e).sort();return 1===n.length&&"nelson_1"===n[0]?"rule_1_only":2===n.length&&"nelson_1"===n[0]&&"nelson_5"===n[1]?"rules_1_5":3===n.length&&n.includes("nelson_1")&&n.includes("nelson_5")&&n.includes("nelson_2")?"rules_1_5_2":8===n.length?"rules_all_8":"rules_other"}function g(e,t){if(!e)return{ucl:NaN,cl:NaN,lcl:NaN};const n=e.metrics[t];return n&&Number.isFinite(n.mean)&&Number.isFinite(n.sd)?{ucl:n.mean+3*n.sd,cl:n.mean,lcl:n.mean-3*n.sd}:{ucl:NaN,cl:NaN,lcl:NaN}}async function h(e,t){if(null==e.source_project_id)return{kind:"toast",message:`Source for '${e.run_label}' is not currently available. Open the run's analyzed file and re-run Compute SPC Status.`};const n=await t.projectsFind(e.source_project_id);return n?(await n.open(),{kind:"opened",id:e.source_project_id}):{kind:"toast",message:`Source for '${e.run_label}' is not currently available. Open the run's analyzed file and re-run Compute SPC Status.`}}function y(e,t,n){const o=s.Viewer.lineChart(e,{xColumnName:"acquisition_datetime",yColumnNames:[n],title:c[n]});if(t){const e=g(t,n);if(Number.isFinite(e.cl)){const t=o?.meta?.formulaLines;if(t&&"function"==typeof t.addLine)try{t.addLine({formula:`\${${n}} = ${e.ucl}`,color:m,width:1,style:"dashed",visible:!0,title:"UCL"}),t.addLine({formula:`\${${n}} = ${e.cl}`,color:u,width:1,style:"solid",visible:!0,title:"CL"}),t.addLine({formula:`\${${n}} = ${e.lcl}`,color:m,width:1,style:"dashed",visible:!0,title:"LCL"})}catch(e){}}}const r=`MR_${n}`,i=s.Viewer.lineChart(e,{xColumnName:"acquisition_datetime",yColumnNames:[r],title:`MR ${c[n]}`});if(t&&e.col(r)){const t=e.col(r);let n=0,o=0;for(let r=0;r<e.rowCount;r++){if(t.isNone(r))continue;const e=Number(t.get(r));Number.isFinite(e)&&(n+=e,o++)}if(o>0){const e=n/o,t=a.Mj*e,s=i?.meta?.formulaLines;if(s&&"function"==typeof s.addLine)try{s.addLine({formula:`\${${r}} = ${t}`,color:m,width:1,style:"dashed",visible:!0,title:"MR UCL"}),s.addLine({formula:`\${${r}} = ${e}`,color:u,width:1,style:"solid",visible:!0,title:"MR CL"})}catch(e){}}}return{iChart:o,mrChart:i}}function E(e){const t=new Map;for(const n of e){const e=Array.isArray(n.rules_tripped)?n.rules_tripped:[];for(const n of e){const e=t.get(n)??0;t.set(n,e+1)}}const n=[];for(const[e,o]of t.entries()){const t=e.indexOf("@");t<0?n.push({rule:e,metric:"",count:o}):n.push({rule:e.slice(0,t),metric:e.slice(t+1),count:o})}return n.sort((e,t)=>t.count-e.count),n}function w(e){switch(e){case"nelson_1":return"Nelson rule 1: a single point beyond 3σ from the centerline.";case"nelson_2":return"Nelson rule 2: 9 consecutive points on the same side of the centerline.";case"nelson_3":return"Nelson rule 3: 6 consecutive points all trending up, or all trending down.";case"nelson_4":return"Nelson rule 4: 14 consecutive points alternating above and below the centerline.";case"nelson_5":return"Nelson rule 5: 2 out of 3 consecutive points beyond 2σ on the same side.";case"nelson_6":return"Nelson rule 6: 4 out of 5 consecutive points beyond 1σ on the same side.";case"nelson_7":return"Nelson rule 7: 15 consecutive points within 1σ of the centerline (unusually stable).";case"nelson_8":return"Nelson rule 8: 8 consecutive points more than 1σ from the centerline on either side."}}function v(e,t){const n=e.rowCount;if(0===n)return;const o={median_intensity:e.col("median_intensity"),missing_pct:e.col("missing_pct"),control_corr:e.col("control_corr"),protein_count:e.col("protein_count")},r=e.col("status"),s=e.col("rules_tripped");if(r&&s){for(let e=0;e<n;e++){const n={median_intensity:Number(o.median_intensity?.get(e)),missing_pct:Number(o.missing_pct?.get(e)),control_corr:Number(o.control_corr?.get(e)),protein_count:Number(o.protein_count?.get(e)),sample_count:0,computed_at:""},i={median_intensity:[],missing_pct:[],control_corr:[],protein_count:[]};for(let t=0;t<e;t++)i.median_intensity.push(Number(o.median_intensity?.get(t))),i.missing_pct.push(Number(o.missing_pct?.get(t))),i.control_corr.push(Number(o.control_corr?.get(t))),i.protein_count.push(Number(o.protein_count?.get(t)));const l=(0,a.uV)(n,i,t.metrics,t.rules_enabled);r.set(e,l.status),s.set(e,JSON.stringify(l.rulesTripped))}a.classifyStatus}}function _(e,t,n,s){const u=!!s,m=u?`Rebuild baseline for ${e}`:`Lock baseline for ${e}`,p=t.slice().sort((e,t)=>e.acquisition_datetime.localeCompare(t.acquisition_datetime)),g=new Set;if(u)for(const e of s.included_run_ids)g.add(e);else{const e=Math.min(7,p.length);for(let t=0;t<e;t++)g.add(p[t].run_id)}const h=[],y=r.divV([]);y.style.maxHeight="300px",y.style.overflowY="auto";for(const e of p){const t=r.input.bool("",{value:g.has(e.run_id)});h.push({run:e,input:t}),y.appendChild(r.divH([t.root,r.divText(e.acquisition_datetime.slice(0,10)),r.divText(e.run_label)]))}const E=r.input.bool("Iterate 3σ outlier removal (recommended)",{value:!u||s.iteration_trace.length>0,tooltipText:"When on, runs more than 3 standard deviations from the baseline mean are dropped from the baseline. Capped at 2 passes."}),v=s?.rules_enabled??(0,a.kY)(),_=["nelson_1","nelson_2","nelson_3","nelson_4","nelson_5","nelson_6","nelson_7","nelson_8"],C={median_intensity:{},missing_pct:{},control_corr:{},protein_count:{}},b=[r.divH([r.divText(""),..._.map(e=>r.divText(e.replace("nelson_","R")))])],T=r.divText(d[f(v)]);for(const e of l){const t=[r.divText(c[e])];for(const n of _){const o=r.input.bool("",{value:v[e][n],tooltipText:w(n)});o.onChanged.subscribe(()=>{const e=P();T.textContent=d[f(e)]}),C[e][n]=o,t.push(o.root)}b.push(r.divH(t))}function P(){const e={};for(const t of l){e[t]={};for(const n of _)e[t][n]=!!C[t][n].value}return e}const S=[];u?S.push(r.divText(`This replaces the locked baseline from ${s.locked_at}. The previous baseline is not kept.`)):S.push(r.divText("Pick the runs that represent normal operation:")),S.push(y),S.push(E.root),S.push(r.h2("Nelson rules")),S.push(r.divV(b)),S.push(T);const N=r.dialog(m);for(const e of S)N.add(e);N.onOK(async()=>{const t=h.filter(e=>!0===e.input.value).map(e=>e.run);if(t.length<3)return void o.shell.warning("At least 3 runs must remain after outlier removal — too few to compute a baseline.");const r=new Set,s=[];if(E.value)for(const e of l){const n=t.map(t=>({run_id:t.run_id,value:t[e]})),o=(0,i.oF)(n,2);for(const e of o.excluded_run_ids)r.add(e);for(const e of o.iteration_trace)s.push(e)}const a=t.filter(e=>!r.has(e.run_id));if(a.length<3)return void o.shell.warning("At least 3 runs must remain after outlier removal — too few to compute a baseline.");const c=(0,i.OI)(a),m={instrument_id:e,locked_at:(new Date).toISOString(),included_run_ids:a.map(e=>e.run_id),excluded_run_ids:Array.from(r),iteration_trace:s,metrics:c,rules_enabled:P()};await n(m),u?o.shell.info(`Baseline rebuilt for ${e}: ${a.length} runs included, ${r.size} excluded. Previous baseline replaced.`):o.shell.info(`Baseline locked for ${e}: ${a.length} runs included, ${r.size} excluded.`)}),N.show()}async function C(){const e=await(0,i.loadRuns)();if(0===e.length)return void o.shell.warning("No SPC runs recorded yet. Open an analyzed file, then run Analyze → Compute SPC Status. The dashboard turns on once at least 4 runs have been computed.");const t=Array.from(new Set(e.map(e=>e.instrument_id))),n=await o.dapi.userDataStorage.get(p),u=n&&n.instrument_id||t[0],m=new Map;for(const e of t)m.set(e,await(0,i.loadBaseline)(e));const g=t.map(e=>m.get(e)?`${e} (baseline locked)`:`${e} (no baseline)`),C=new Map;for(let e=0;e<t.length;e++)C.set(g[e],t[e]);const b=g[t.indexOf(u)]??g[0],T=r.input.choice("Instrument",{value:b,items:g,nullable:!1,tooltipText:"Switches the trend charts and baseline to a different instrument. Only instruments with computed SPC runs are listed."});r.dialog("SPC Dashboard").add(T).onOK(async()=>{const e=C.get(String(T.value))??t[0];await o.dapi.userDataStorage.put(p,{instrument_id:e}),await async function(e){const t=await(0,i.loadRuns)(e);let n;n=0===t.length?s.DataFrame.create(0):(0,i.$G)(t),n.name=`SPC — ${e}`,function(e){for(const t of l){const n=e.col(t);if(!n)continue;const o=`MR_${t}`;e.columns.contains(o)&&e.columns.remove(o);const r=e.columns.addNewFloat(o),s=e.rowCount;let a=null;for(let e=0;e<s;e++){if(0===e){r.set(e,null),a=null;continue}if(n.isNone(e)||n.isNone(e-1)){r.set(e,null);continue}const t=Number(n.get(e)),o=Number(n.get(e-1));Number.isFinite(t)&&Number.isFinite(o)?(r.set(e,Math.abs(t-o)),a=t):r.set(e,null)}}}(n);const u=o.shell.addTableView(n);let m=await(0,i.loadBaseline)(e);const p=()=>{for(const e of l){const{iChart:t,mrChart:o}=y(n,m,e);u.dockManager.dock(t,s.DOCK_TYPE.RIGHT,null,`I-chart ${c[e]}`,.5),u.dockManager.dock(o,s.DOCK_TYPE.DOWN,null,`MR-chart ${c[e]}`,.5)}const t=function(e,t){if(e.rowCount<4)return null;const n=e.col("rules_tripped");if(!n)return null;const o=e.rowCount,r=[];for(let e=0;e<o;e++){const t=String(n.get(e)??"");let o=[];if(t.length>0)try{o=JSON.parse(t)}catch{o=[]}r.push({rules_tripped:o})}const a=E(r);if(0===a.length)return null;const i=s.Column.fromStrings("rule_metric",a.map(e=>e.metric?`${e.rule}@${e.metric}`:e.rule)),l=new Int32Array(a.map(e=>e.count)),c=new Int32Array(a.map(()=>o)),u=new Float32Array(a.map(e=>e.count/o*100)),m=s.DataFrame.fromColumns([i,s.Column.fromInt32Array("trip_count",l),s.Column.fromInt32Array("total_runs",c),s.Column.fromFloat32Array("pct",u)]),p=s.Viewer.barChart(m,{splitColumnName:"rule_metric",valueColumnName:"trip_count",title:`Which rules trip most often — ${t}`});try{p.props.xLabel="(rule, metric)",p.props.yLabel="Times tripped"}catch(e){}return p}(n,e);if(null!==t)u.dockManager.dock(t,s.DOCK_TYPE.DOWN,null,"Pareto",.3);else{const e=r.divV([r.divText("Pareto chart appears once 4 or more runs have been recorded for this instrument.")]);u.dockManager.dock(e,s.DOCK_TYPE.DOWN,null,"Pareto",.3)}},g=function(e,t,n,o){const s=r.h2(`Instrument: ${e}`);let i;i=t?r.divV([r.divText(`Baseline locked: ${t.locked_at}`),r.divText(`${t.included_run_ids.length} runs included · ${t.excluded_run_ids.length} runs excluded (3σ outlier).`),r.button("Rebuild baseline...",n)]):r.divV([r.divText("No baseline locked yet. The dashboard turns on once a baseline exists.")]);const u=["nelson_1","nelson_2","nelson_3","nelson_4","nelson_5","nelson_6","nelson_7","nelson_8"],m=t?.rules_enabled??(0,a.kY)(),p=r.divText(d[f(m)]),g=[];g.push(r.divH([r.divText(""),...u.map(e=>r.divText(e.replace("nelson_","R")))]));for(const e of l){const t=[r.divText(c[e])];for(const n of u){const s=r.input.bool("",{value:m[e][n],tooltipText:w(n)});s.onChanged.subscribe(async t=>{await o(e,n,!!t)}),t.push(s.root)}g.push(r.divH(t))}return{el:r.divV([s,i,r.h2("Nelson rules"),r.divV(g),p]),setDisclosure:e=>{p.textContent=e}}}(e,m,()=>{_(e,t,async t=>{await(0,i.saveBaseline)(e,t),m=t,v(n,t),p()},m??void 0)},async(t,o,r)=>{m&&(m.rules_enabled[t][o]=r,await(0,i.saveBaseline)(e,m),v(n,m))});if(u.dockManager.dock(g.el,s.DOCK_TYPE.LEFT,null,"SPC Controls",.25),null===m){const o=r.divV([r.h2(`No baseline locked for ${e}.`),r.divText("Pick the runs that represent normal operation, then click Lock baseline. The dashboard turns on once a baseline exists."),r.button("Define baseline...",()=>{_(e,t,async t=>{await(0,i.saveBaseline)(e,t),m=t,v(n,t),p()})})]);u.dockManager.dock(o,s.DOCK_TYPE.RIGHT,null,"Baseline",.75)}else p();!function(e,t){e.dataFrame.onCurrentRowChanged.subscribe(async()=>{const e=t.currentRowIdx;if(e<0)return;const n=String(t.col("status")?.get(e)??"");if("flagged"!==n&&"out_of_control"!==n)return;const r=t.col("source_project_id")?.get(e),s=null==r||""===r?null:String(r),a=await h({run_id:String(t.col("run_id")?.get(e)??""),run_label:String(t.col("run_label")?.get(e)??""),source_project_id:s},{projectsFind:async e=>{const t=await o.dapi.projects.find(e);return t?{open:()=>t.open()}:null}});"toast"===a.kind&&o.shell.warning(a.message)})}(u,n)}(e)}).show()}},70(e,t,n){"use strict";n.d(t,{Bb:()=>A,CK:()=>w,DI:()=>N,EO:()=>v,GE:()=>M,MC:()=>C,PL:()=>i.PL,S6:()=>O,XC:()=>k,bX:()=>D,f0:()=>R,fQ:()=>f,gO:()=>$,j9:()=>g,kX:()=>x,m2:()=>G,nj:()=>B,ur:()=>P});var o=n(82),r=n(389),s=n(713),a=n(304),i=n(641),l=n(498),c=n(252),u=n(623);const m=-Math.log10(Number.MIN_VALUE),p="negLog10P",d="direction",f="Subcellular Location",g="proteomics.volcano_metric";let h=[];const y="proteomics-volcano";function E(e,t){if("p-value"===t){const t=e.col("p-value");if(t)return t}const n=e.col("adj.p-value");if(!n)throw new Error("adj.p-value column not found");return n}function w(e,t="adj.p-value"){const n=E(e,t);return(e.col(p)??e.columns.addNewFloat(p)).init(e=>{if(n.isNone(e))return o.FLOAT_NULL;const t=n.get(e);return t>0?-Math.log10(t):m}),p}function v(e,t,n,o="adj.p-value"){const r=e.col("log2FC");if(!r)throw new Error("log2FC column not found");const s=E(e,o),a=(0,c.f)(e),l=a?`Enriched in ${a.group1.name}`:"Enriched in group1",u=a?`Enriched in ${a.group2.name}`:"Enriched in group2",m="Not significant",p=e.rowCount,f=new Array(p);for(let e=0;e<p;e++){if(r.isNone(e)||s.isNone(e)){f[e]=m;continue}const o=r.get(e),a=s.get(e);f[e]=a<=n&&o>t?l:a<=n&&o<-t?u:m}const g=e.col(d)??e.columns.addNewString(d);return g.init(e=>f[e]),g.meta.colors.setCategorical({[l]:i.PL.enrichedG1,[u]:i.PL.enrichedG2,[m]:i.PL.notSig}),d}const _="proteomics.location_acc_hash";async function C(e,t){const n=(0,a.k)(e,i.iu.PROTEIN_ID,["primary protein id","protein id","protein ids","accession","uniprot"])??e.col("Primary Protein ID")??e.col("Protein ID"),o=e.rowCount,r=new Array(o).fill(null),s=new Set;if(n)for(let e=0;e<o;e++){const t=n.get(e),o=t?(0,l.S6)(t):null;r[e]=o,o&&s.add(o)}const m=function(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=t+((t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24))>>>0;return t.toString(16).padStart(8,"0")}([...s].sort().join("|")),p=e.col(f);if(p&&p.getTag(_)===m)return t?.(1,1,"init-column"),f;const d=await(0,u.n0)([...s],(0,c.Di)(e),t),g=new Array(o);for(let e=0;e<o;e++){const t=r[e];g[e]=t&&d.get(t)||"Unknown"}const h=p??e.columns.addNewString(f);return h.init(e=>g[e]),h.meta.colors.setCategorical(u.Jn),h.semType=i.iu.SUBCELLULAR_LOCATION,h.setTag(_,m),t?.(1,1,"init-column"),f}function b(e,t,n,o){const r=-Math.log10(o),s=`\${${t}}`,a="${log2FC}";e.meta.formulaLines.items=e.meta.formulaLines.items.filter(e=>{const t=e.formula??"";return!("string"==typeof t&&(t.startsWith(s)||t.startsWith(a)))}),e.meta.formulaLines.addLine({formula:`${s} = ${r}`,color:"#888888",width:1,visible:!0}),e.meta.formulaLines.addLine({formula:`${a} = ${n}`,color:"#888888",width:1,visible:!0}),e.meta.formulaLines.addLine({formula:`${a} = ${-n}`,color:"#888888",width:1,visible:!0})}function T(e){return"p-value"===e?"-Log10(p-value)":"-Log10(Q-value)"}function P(e,t){const n=t.getOptions(),o=(n?.look??{}).colorColumnName===f?"location":"significance";return{metric:e.getTag(g)??"adj.p-value",colorDim:o}}function S(e,t){const n=e.root.querySelector("[data-volcano-axis-y]");if(n){const e=t.getTag(g);n.textContent=T(e)}}function N(e,t){x(e);const n=e.root;n.style.position=n.style.position||"relative";const o=r.divV([]);o.dataset.volcanoBusy="true",Object.assign(o.style,{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",padding:"12px 20px",background:"rgba(255,255,255,0.95)",border:"1px solid #ccc",borderRadius:"6px",boxShadow:"0 2px 8px rgba(0,0,0,0.15)",fontSize:"0.95em",textAlign:"center",pointerEvents:"none",zIndex:"6",maxWidth:"320px"});const s=r.divText(t);s.style.fontWeight="bold",s.style.marginBottom="4px";const a=r.divText("");a.style.fontSize="0.85em",a.style.color="#666",o.appendChild(s),o.appendChild(a),n.appendChild(o)}function A(e,t,n){const o=e.root.querySelector("[data-volcano-busy]");if(!o)return;const[r,s]=Array.from(o.children);r&&(r.textContent=t),s&&(s.textContent=n??"")}function x(e){e.root.querySelectorAll("[data-volcano-busy]").forEach(e=>e.remove())}const D="~Volcano label",L="proteomics.volcano_top_n",F="proteomics.volcano_x_max",I="proteomics.volcano_y_max";function M(e){const t=t=>{const n=parseFloat(e.getTag(t)??"");return Number.isFinite(n)&&n>0?n:null};return{xMax:t(F),yMax:t(I)}}function O(e,t,n){const o=(t,n)=>e.setTag(t,null!=n&&Number.isFinite(n)&&n>0?String(n):"");o(F,t),o(I,n)}function R(e,t){const{xMax:n,yMax:o}=M(t);if(null!=n)e.props.xMin=-n,e.props.xMax=n;else{const n=t.col("log2FC");if(null!=n&&Number.isFinite(n.min)&&Number.isFinite(n.max)){const t=Math.max(.05*(n.max-n.min),1e-6);e.props.xMin=n.min-t,e.props.xMax=n.max+t}}if(null!=o)e.props.yMin=0,e.props.yMax=o;else{const n=t.col(p);null!=n&&Number.isFinite(n.max)&&(e.props.yMin=0,e.props.yMax=1.05*n.max+1e-6)}}function G(e){const t=parseInt(e.getTag(L)??"",10);return Number.isFinite(t)&&t>=0?t:15}function k(e,t,n=15,r){e.setTag(L,String(n));const s=function(e){return(0,a.k)(e,i.iu.DISPLAY_NAME,["display name"])??(0,a.k)(e,i.iu.GENE_SYMBOL,["gene name","gene symbol"])}(e);if(!s)return;const l=e.col(D)??e.columns.addNewString(D),c=new Set(function(e,t){if(t<=0)return[];const n=e.col(p),r=e.col("log2FC");if(!n||!r)return[];const s=n.getRawData(),a=r.getRawData(),i=[];for(let t=0;t<e.rowCount;t++)e.filter.get(t)&&s[t]!==o.FLOAT_NULL&&a[t]!==o.FLOAT_NULL&&i.push(t);return i.sort((e,t)=>{const n=s[t]-s[e];return 0!==n?n:Math.abs(a[t])-Math.abs(a[e])}),i.slice(0,t)}(e,n));if(r)for(const e of r)c.add(e);l.init(e=>c.has(e)?String(s.get(e)??""):""),t.props.labelColumnNames=[D],t.props.showLabelsFor="All"}function $(e,t){const n=t?.fcThreshold??i.M5,o=t?.pThreshold??i.Dx;!function(){for(const e of h)e.unsubscribe();h=[]}();const a=e.getTag(g)??"adj.p-value";e.setTag(g,a);const l=w(e,a),u=v(e,n,o,a),m=e.plot.scatter({x:"log2FC",y:l,color:u});b(e,l,n,o),m.props.showViewerFormulaLines=!0,function(){const e="proteomics-volcano-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent=`.${y} .d4-column-selector.d4-vertical,.${y} .d4-column-selector.d4-bottom-center{display:none !important;}`,document.head.appendChild(t)}(),m.root.classList.add(y);const p=t?.title??function(e){const t=(0,c.f)(e);return t?`Volcano Plot: ${t.group1.name} vs ${t.group2.name}`:"Volcano Plot"}(e);return m.setOptions({title:p}),function(e,t){const n=e.root;n.style.position=n.style.position||"relative";const o=r.divText("Log2 Fold Change");o.dataset.volcanoAxisX="true",Object.assign(o.style,{position:"absolute",bottom:"4px",left:"50%",transform:"translateX(-50%)",fontSize:"0.85em",pointerEvents:"none",background:"rgba(255,255,255,0.7)",padding:"0 4px",zIndex:"4"}),n.appendChild(o);const a=t.getTag(g),i=r.divText(T(a));i.dataset.volcanoAxisY="true",Object.assign(i.style,{position:"absolute",left:"4px",top:"50%",transform:"translateY(-50%) rotate(-90deg)",transformOrigin:"left center",fontSize:"0.85em",pointerEvents:"none",background:"rgba(255,255,255,0.7)",padding:"0 4px",zIndex:"4"}),n.appendChild(i),h.push(e.onPropertyValueChanged.pipe((0,s.debounceTime)(50)).subscribe(()=>S(e,t)))}(m,e),function(e,t){const n=e.root;n.style.position=n.style.position||"relative";const o=r.divV([]);o.dataset.volcanoCounter="true",Object.assign(o.style,{position:"absolute",bottom:"8px",right:"8px",padding:"8px 16px",background:"rgba(255,255,255,0.85)",borderRadius:"4px",fontSize:"0.9em",pointerEvents:"none",zIndex:"5"}),n.appendChild(o);const a=()=>{const n=t.filter.trueCount,s=e.props.colorColumnName,a=s?t.col(s):null,i=new Map;let l=!1;if(a&&(s===d||s===f)){l=!0;for(const e of a.categories)i.set(e,0);for(let e=0;e<t.rowCount;e++){if(!t.filter.get(e))continue;if(a.isNone(e))continue;const n=a.get(e);i.set(n,(i.get(n)??0)+1)}}o.replaceChildren();const c=r.divText("Visible Proteins");if(c.style.fontWeight="bold",o.appendChild(c),o.appendChild(r.divText(`Total: ${n.toLocaleString()}`)),l)for(const[e,t]of i)o.appendChild(r.divText(`${e}: ${t.toLocaleString()}`))};a(),h.push(t.onFilterChanged.pipe((0,s.debounceTime)(50)).subscribe(a),t.onSelectionChanged.pipe((0,s.debounceTime)(50)).subscribe(a),e.onPropertyValueChanged.pipe((0,s.debounceTime)(50)).subscribe(a))}(m,e),R(m,e),k(e,m,t?.topNLabels??15),m}async function B(e,t,n,o,r=i.M5,s=i.Dx,a){e.setTag(g,n);const l=w(e,n),c=v(e,r,s,n);b(e,l,r,s),t.props.xColumnName="log2FC",t.props.yColumnName=l,t.props.colorColumnName="location"===o?await C(e,a):c,S(t,e),R(t,e)}},82(e){"use strict";e.exports=DG},328(e){"use strict";e.exports=grok},858(e){"use strict";e.exports=rxjs},713(e){"use strict";e.exports=rxjs.operators},389(e){"use strict";e.exports=ui}},t={};function n(o){var r=t[o];if(void 0!==r)return r.exports;var s=t[o]={exports:{}};return e[o].call(s.exports,s,s.exports,n),s.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var o in t)n.o(t,o)&&!n.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var o={};(()=>{"use strict";n.r(o),n.d(o,{_package:()=>je,initAutoTests:()=>qe,test:()=>Ve,tests:()=>t.CN});var e=n(82),t=n(749),r=n(312),s=n(641);function a(e,t){return[t.join("\t"),...e.map(e=>e.join("\t"))].join("\n")}const i=["Protein IDs","Majority protein IDs","Gene names","Potential contaminant","Reverse","Only identified by site","LFQ intensity Sample1","LFQ intensity Sample2","iBAQ"];(0,t.L1)("Parsers",()=>{(0,t.t6)("MaxQuant: filters contaminant rows",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"],["P99999","P99999","TP53","+","","","3000","4000","600"]],i),n=await(0,r.E)(e);(0,t.E3)(n.rowCount,1)}),(0,t.t6)("MaxQuant: filters reverse rows",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"],["P99999","P99999","TP53","","+","","3000","4000","600"]],i),n=await(0,r.E)(e);(0,t.E3)(n.rowCount,1)}),(0,t.t6)("MaxQuant: filters only-by-site rows",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"],["P99999","P99999","TP53","","","+","3000","4000","600"]],i),n=await(0,r.E)(e);(0,t.E3)(n.rowCount,1)}),(0,t.t6)("MaxQuant: filters CON__ prefix rows",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"],["CON__P99999","CON__P99999","KRT1","","","","3000","4000","600"]],i),n=await(0,r.E)(e);(0,t.E3)(n.rowCount,1)}),(0,t.t6)("MaxQuant: filters REV__ prefix rows",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"],["REV__P99999","REV__P99999","TP53","","","","3000","4000","600"]],i),n=await(0,r.E)(e);(0,t.E3)(n.rowCount,1)}),(0,t.t6)("MaxQuant: detects LFQ intensity columns",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"]],i),n=await(0,r.E)(e);(0,t.E3)(null!==n.col("LFQ intensity Sample1"),!0),(0,t.E3)(null!==n.col("log2(LFQ intensity Sample1)"),!0),(0,t.E3)(null!==n.col("log2(LFQ intensity Sample2)"),!0)}),(0,t.t6)("MaxQuant: log2 transforms intensity values correctly",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1024","2048","500"]],i),n=(await(0,r.E)(e)).col("log2(LFQ intensity Sample1)");(0,t.E3)(null!==n,!0),n&&(0,t.E3)(Math.abs(n.get(0)-10)<.001,!0)}),(0,t.t6)("MaxQuant: zero intensity produces FLOAT_NULL in log2",async()=>{const e=a([["P12345","P12345","BRCA1","","","","0","2048","500"]],i),n=(await(0,r.E)(e)).col("log2(LFQ intensity Sample1)");(0,t.E3)(null!==n,!0),n&&(0,t.E3)(n.isNone(0),!0)}),(0,t.t6)("MaxQuant: assigns semantic types",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"]],i),n=await(0,r.E)(e);(0,t.E3)(n.col("Protein IDs")?.semType,s.iu.PROTEIN_ID),(0,t.E3)(n.col("Gene names")?.semType,s.iu.GENE_SYMBOL),(0,t.E3)(n.col("LFQ intensity Sample1")?.semType,s.iu.INTENSITY),(0,t.E3)(n.col("log2(LFQ intensity Sample1)")?.semType,s.iu.INTENSITY)}),(0,t.t6)("MaxQuant: parses primary protein ID from semicolon-delimited",async()=>{const e=a([["P12345;Q67890;R11111","P12345","BRCA1;BRCA2","","","","1000","2000","500"]],i),n=await(0,r.E)(e),o=n.col("Primary Protein ID");(0,t.E3)(null!==o,!0),o&&(0,t.E3)(o.get(0),"P12345");const s=n.col("Primary Gene Name");(0,t.E3)(null!==s,!0),s&&(0,t.E3)(s.get(0),"BRCA1")}),(0,t.t6)("MaxQuant: no contaminant IDs remain after filtering",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"],["P22222","P22222","TP53","","","","3000","4000","600"],["CON__P99999","CON__P99999","KRT1","+","","","5000","6000","700"],["REV__P88888","REV__P88888","FAKE1","","+","","7000","8000","800"],["P77777","P77777","FAKE2","","","+","9000","1000","900"]],i),n=await(0,r.E)(e);(0,t.E3)(n.rowCount,2);const o=n.col("Protein IDs");for(let e=0;e<n.rowCount;e++){const t=o.get(e);if(t.startsWith("CON__")||t.startsWith("REV__"))throw new Error(`Found filtered ID in output: ${t}`)}}),(0,t.t6)("MaxQuant: assigns intensity semantic type to log2 columns",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"]],i),n=await(0,r.E)(e);(0,t.E3)(n.col("log2(LFQ intensity Sample1)")?.semType,s.iu.INTENSITY),(0,t.E3)(n.col("log2(LFQ intensity Sample2)")?.semType,s.iu.INTENSITY),(0,t.E3)(n.col("log2(iBAQ)")?.semType,s.iu.INTENSITY)}),(0,t.t6)("MaxQuant: handles MQ 2.x dot column names",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000"],["P99999","P99999","TP53","+","","","3000"]],["Protein IDs","Majority protein IDs","Gene names","Potential.contaminant","Reverse","Only.identified.by.site","LFQ intensity Sample1"]),n=await(0,r.E)(e);(0,t.E3)(n.rowCount,1)}),(0,t.t6)("MaxQuant: parser tags proteomics.source",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"]],i),n=await(0,r.E)(e);(0,t.E3)(n.getTag("proteomics.source"),"maxquant")}),(0,t.t6)("MaxQuant: iBAQ columns detected as intensity",async()=>{const e=a([["P12345","P12345","BRCA1","","","","1000","2000","500"]],i),n=await(0,r.E)(e);(0,t.E3)(n.col("iBAQ")?.semType,s.iu.INTENSITY),(0,t.E3)(null!==n.col("log2(iBAQ)"),!0)})});var l=n(252),c=n(350),u=n(47),m=n(829);function p(t,n,o,r,a){const i=[];i.push(e.Column.fromStrings("Protein ID",Array.from({length:t},(e,t)=>`P${t}`)));const l=[...n,...o],c=r&&a?[...r,...a]:void 0;for(let n=0;n<l.length;n++){const o=new Float32Array(t);if(c&&c[n])for(let e=0;e<t;e++)o[e]=c[n][e];const r=e.Column.fromFloat32Array(l[n],o);r.semType=s.iu.INTENSITY,i.push(r)}return e.DataFrame.fromColumns(i)}(0,t.L1)("Experiment Setup",()=>{(0,t.t6)("setGroups persists group assignments as tag",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0"]),e.Column.fromFloat32Array("s1",new Float32Array([1]))]);(0,l.$Y)(n,{group1:{name:"Control",columns:["s1"]},group2:{name:"Treatment",columns:["s2"]}});const o=n.getTag("proteomics.groups");(0,t.E3)(null!==o&&""!==o,!0);const r=JSON.parse(o);(0,t.E3)(r.group1.name,"Control"),(0,t.E3)(r.group2.name,"Treatment")}),(0,t.t6)("getGroups returns null for untagged DataFrame",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0"])]),o=(0,l.f)(n);(0,t.E3)(o,null)}),(0,t.t6)("getOrganism returns undefined until set, then round-trips the code",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0"])]);(0,t.E3)(void 0===(0,l.Di)(n),!0),(0,l.Np)(n,"rnorvegicus"),(0,t.E3)((0,l.Di)(n),"rnorvegicus")}),(0,t.t6)("applyAnnotation persists the organism alongside the groups",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0"])]);(0,l.applyAnnotation)(n,{group1:{name:"Control",columns:["s1","s2"]},group2:{name:"Treatment",columns:["s3","s4"]},organism:"rnorvegicus"}),(0,t.E3)((0,l.Di)(n),"rnorvegicus"),(0,t.E3)((0,l.f)(n).group1.name,"Control");const o=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0"])]);(0,l.applyAnnotation)(o,{group1:{name:"A",columns:["s1"]},group2:{name:"B",columns:["s2"]}}),(0,t.E3)(void 0===(0,l.Di)(o),!0)}),(0,t.t6)("getGroups round-trips GroupAssignment correctly",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0"])]);(0,l.$Y)(n,{group1:{name:"Control",columns:["s1","s2","s3"]},group2:{name:"Treatment",columns:["s4","s5","s6"]}});const o=(0,l.f)(n);(0,t.E3)(null!==o,!0),(0,t.E3)(o.group1.name,"Control"),(0,t.E3)(o.group2.name,"Treatment"),(0,t.E3)(o.group1.columns.length,3),(0,t.E3)(o.group2.columns.length,3),(0,t.E3)(o.group1.columns[0],"s1"),(0,t.E3)(o.group2.columns[2],"s6")}),(0,t.t6)("seedAnnotationDialogInputs returns Control/Treatment defaults when no tag",async()=>{const e=p(3,["s1","s2"],["s3","s4"]),n=(0,l.Yf)(e,["s1","s2","s3","s4"]);(0,t.E3)(n.group1Name,"Control"),(0,t.E3)(n.group2Name,"Treatment"),(0,t.E3)(n.group1Cols.length,0),(0,t.E3)(n.group2Cols.length,0)}),(0,t.t6)("seedAnnotationDialogInputs reads names + columns from existing groups",async()=>{const e=p(3,["s1","s2"],["s3","s4"]);(0,l.$Y)(e,{group1:{name:"DMD",columns:["s1","s2"]},group2:{name:"WT",columns:["s3","s4"]}});const n=(0,l.Yf)(e,["s1","s2","s3","s4"]);(0,t.E3)(n.group1Name,"DMD"),(0,t.E3)(n.group2Name,"WT"),(0,t.E3)(n.group1Cols.length,2),(0,t.E3)(n.group2Cols.length,2),(0,t.E3)(n.group1Cols[0].name,"s1"),(0,t.E3)(n.group2Cols[1].name,"s4")}),(0,t.t6)("seedAnnotationDialogInputs drops column refs not in the DataFrame",async()=>{const e=p(3,["s1","s2"],["s3","s4"]);(0,l.$Y)(e,{group1:{name:"DMD",columns:["s1","gone","s2"]},group2:{name:"WT",columns:["also-gone","s3","s4"]}});const n=(0,l.Yf)(e,["s1","s2","s3","s4"]);(0,t.E3)(n.group1Cols.length,2),(0,t.E3)(n.group2Cols.length,2),(0,t.E3)(n.group1Cols.map(e=>e.name).join(","),"s1,s2"),(0,t.E3)(n.group2Cols.map(e=>e.name).join(","),"s3,s4")}),(0,t.t6)("seedAnnotationDialogInputs drops column refs not in available list",async()=>{const e=p(3,["s1","s2"],["s3","s4"]);(0,l.$Y)(e,{group1:{name:"A",columns:["s1","s2"]},group2:{name:"B",columns:["s3","s4"]}});const n=(0,l.Yf)(e,["s1","s3"]);(0,t.E3)(n.group1Cols.length,1),(0,t.E3)(n.group2Cols.length,1),(0,t.E3)(n.group1Cols[0].name,"s1"),(0,t.E3)(n.group2Cols[0].name,"s3")}),(0,t.t6)("seedAnnotationDialogInputs falls back to defaults when stored names are empty",async()=>{const e=p(3,["s1","s2"],["s3","s4"]);(0,l.$Y)(e,{group1:{name:"",columns:["s1","s2"]},group2:{name:"",columns:["s3","s4"]}});const n=(0,l.Yf)(e,["s1","s2","s3","s4"]);(0,t.E3)(n.group1Name,"Control"),(0,t.E3)(n.group2Name,"Treatment")})}),(0,t.L1)("Normalization",()=>{(0,t.t6)("median normalization shifts column medians to zero",async()=>{const n=e.Column.fromFloat32Array("intensity",new Float32Array([2,4,6,8,10]));n.semType=s.iu.INTENSITY;const o=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3","P4"]),n]);(0,c.aj)(o,["intensity"]);const r=o.col("intensity");(0,t.E3)(Math.abs(r.get(0)- -4)<.01,!0),(0,t.E3)(Math.abs(r.get(1)- -2)<.01,!0),(0,t.E3)(Math.abs(r.get(2)-0)<.01,!0),(0,t.E3)(Math.abs(r.get(3)-2)<.01,!0),(0,t.E3)(Math.abs(r.get(4)-4)<.01,!0)}),(0,t.t6)("median normalization skips null values",async()=>{const n=e.Column.fromFloat32Array("intensity",new Float32Array([2,e.FLOAT_NULL,6,8,e.FLOAT_NULL]));n.semType=s.iu.INTENSITY;const o=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3","P4"]),n]);(0,c.aj)(o,["intensity"]);const r=o.col("intensity");(0,t.E3)(r.isNone(1),!0),(0,t.E3)(r.isNone(4),!0),(0,t.E3)(!r.isNone(0),!0),(0,t.E3)(!r.isNone(2),!0),(0,t.E3)(!r.isNone(3),!0)}),(0,t.t6)("normalization sets proteomics.normalized tag",async()=>{const n=e.Column.fromFloat32Array("intensity",new Float32Array([1,2,3]));n.semType=s.iu.INTENSITY;const o=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2"]),n]);(0,c.aj)(o,["intensity"]),(0,t.E3)(o.getTag("proteomics.normalized"),"true")}),(0,t.t6)("quantile normalization aligns column distributions",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([5,2,3,6])),o=e.Column.fromFloat32Array("s2",new Float32Array([4,14,8,2])),r=e.Column.fromFloat32Array("s3",new Float32Array([3,1,9,7]));n.semType=s.iu.INTENSITY,o.semType=s.iu.INTENSITY,r.semType=s.iu.INTENSITY;const a=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3"]),n,o,r]);(0,c.VD)(a,["s1","s2","s3"]);const i=[a.col("s1").get(0),a.col("s1").get(1),a.col("s1").get(2),a.col("s1").get(3)],l=[a.col("s2").get(0),a.col("s2").get(1),a.col("s2").get(2),a.col("s2").get(3)],u=[a.col("s3").get(0),a.col("s3").get(1),a.col("s3").get(2),a.col("s3").get(3)];i.sort((e,t)=>e-t),l.sort((e,t)=>e-t),u.sort((e,t)=>e-t);for(let e=0;e<4;e++)(0,t.E3)(Math.abs(i[e]-l[e])<.01,!0),(0,t.E3)(Math.abs(i[e]-u[e])<.01,!0)}),(0,t.t6)("quantile normalization preserves null values",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([5,e.FLOAT_NULL,3,6])),o=e.Column.fromFloat32Array("s2",new Float32Array([4,14,8,e.FLOAT_NULL]));n.semType=s.iu.INTENSITY,o.semType=s.iu.INTENSITY;const r=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3"]),n,o]);(0,c.VD)(r,["s1","s2"]),(0,t.E3)(r.col("s1").isNone(1),!0),(0,t.E3)(r.col("s2").isNone(3),!0),(0,t.E3)(!r.col("s1").isNone(0),!0),(0,t.E3)(!r.col("s2").isNone(0),!0)}),(0,t.t6)("quantile normalization sets proteomics.normalized tag",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([1,2,3])),o=e.Column.fromFloat32Array("s2",new Float32Array([4,5,6]));n.semType=s.iu.INTENSITY,o.semType=s.iu.INTENSITY;const r=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2"]),n,o]);(0,c.VD)(r,["s1","s2"]),(0,t.E3)(r.getTag("proteomics.normalized"),"true")}),(0,t.t6)("quantile normalization with < 2 columns returns without error",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([1,2,3]));n.semType=s.iu.INTENSITY;const o=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2"]),n]);(0,c.VD)(o,["s1"]),(0,t.E3)(Math.abs(o.col("s1").get(0)-1)<.01,!0)}),(0,t.t6)("vsnNormalize falls back to quantile on R failure",async()=>{const n=e.Column.fromFloat32Array("log2(s1)",new Float32Array([5,2,3,6])),o=e.Column.fromFloat32Array("log2(s2)",new Float32Array([4,14,8,2]));n.semType=s.iu.INTENSITY,o.semType=s.iu.INTENSITY;const r=e.Column.fromFloat32Array("s1",new Float32Array([32,4,8,64])),a=e.Column.fromFloat32Array("s2",new Float32Array([16,16384,256,4])),i=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3"]),r,a,n,o]);await(0,c.Nx)(i,["log2(s1)","log2(s2)"]),(0,t.E3)(i.getTag("proteomics.normalized"),"true")})}),(0,t.L1)("Imputation",()=>{(0,t.t6)("MinProb imputation fills all NaN values",async()=>{const n=new Float32Array([10,e.FLOAT_NULL,14,e.FLOAT_NULL,12]),o=e.Column.fromFloat32Array("intensity",n);o.semType=s.iu.INTENSITY;const r=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3","P4"]),o]);(0,u.U0)(r,["intensity"]);const a=r.col("intensity");for(let e=0;e<a.length;e++)(0,t.E3)(a.isNone(e),!1)}),(0,t.t6)("imputed values are below the observed mean",async()=>{const n=new Float32Array([10,12,14,16,e.FLOAT_NULL,e.FLOAT_NULL]),o=e.Column.fromFloat32Array("intensity",n);o.semType=s.iu.INTENSITY;const r=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3","P4","P5"]),o]);(0,u.U0)(r,["intensity"],1.8,.3);const a=r.col("intensity");(0,t.E3)(a.get(4)<13,!0),(0,t.E3)(a.get(5)<13,!0)}),(0,t.t6)("imputation sets proteomics.imputed tag",async()=>{const n=e.Column.fromFloat32Array("intensity",new Float32Array([1,e.FLOAT_NULL,3]));n.semType=s.iu.INTENSITY;const o=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2"]),n]);(0,u.U0)(o,["intensity"]),(0,t.E3)(o.getTag("proteomics.imputed"),"true")}),(0,t.t6)("kNN imputation fills missing values using nearest neighbors",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([10,11,10.5,12,100])),o=e.Column.fromFloat32Array("s2",new Float32Array([20,21,e.FLOAT_NULL,22,200])),r=e.Column.fromFloat32Array("s3",new Float32Array([30,31,30.5,32,300]));n.semType=s.iu.INTENSITY,o.semType=s.iu.INTENSITY,r.semType=s.iu.INTENSITY;const a=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3","P4"]),n,o,r]),i=(0,u.Mx)(a,["s1","s2","s3"],3);(0,t.E3)(i,1);const l=a.col("s2").get(2);(0,t.E3)(Math.abs(l-21)<1,!0)}),(0,t.t6)("kNN imputation falls back to column mean when no neighbors have values",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([10,e.FLOAT_NULL,e.FLOAT_NULL])),o=e.Column.fromFloat32Array("s2",new Float32Array([20,e.FLOAT_NULL,e.FLOAT_NULL]));n.semType=s.iu.INTENSITY,o.semType=s.iu.INTENSITY;const r=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2"]),n,o]),a=(0,u.Mx)(r,["s1","s2"],10);(0,t.E3)(a>=2,!0)}),(0,t.t6)("kNN imputation returns correct count and sets tag",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([1,2,e.FLOAT_NULL,4])),o=e.Column.fromFloat32Array("s2",new Float32Array([5,e.FLOAT_NULL,7,8]));n.semType=s.iu.INTENSITY,o.semType=s.iu.INTENSITY;const r=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3"]),n,o]),a=(0,u.Mx)(r,["s1","s2"],3);(0,t.E3)(a,2),(0,t.E3)(r.getTag("proteomics.imputed"),"true");for(let e=0;e<4;e++)(0,t.E3)(r.col("s1").isNone(e),!1),(0,t.E3)(r.col("s2").isNone(e),!1)}),(0,t.t6)("imputeZero replaces all nulls with 0",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([1,e.FLOAT_NULL,3,e.FLOAT_NULL]));n.semType=s.iu.INTENSITY;const o=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3"]),n]),r=(0,u.fX)(o,["s1"]);(0,t.E3)(r,2),(0,t.E3)(Math.abs(o.col("s1").get(1)-0)<.01,!0),(0,t.E3)(Math.abs(o.col("s1").get(3)-0)<.01,!0),(0,t.E3)(o.getTag("proteomics.imputed"),"true")}),(0,t.t6)("imputeMean replaces all nulls with column mean",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([2,e.FLOAT_NULL,6,e.FLOAT_NULL]));n.semType=s.iu.INTENSITY;const o=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3"]),n]),r=(0,u.Q2)(o,["s1"]);(0,t.E3)(r,2),(0,t.E3)(Math.abs(o.col("s1").get(1)-4)<.01,!0),(0,t.E3)(Math.abs(o.col("s1").get(3)-4)<.01,!0),(0,t.E3)(o.getTag("proteomics.imputed"),"true")}),(0,t.t6)("imputeMedian replaces all nulls with column median",async()=>{const n=e.Column.fromFloat32Array("s1",new Float32Array([2,e.FLOAT_NULL,6,10,e.FLOAT_NULL]));n.semType=s.iu.INTENSITY;const o=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P0","P1","P2","P3","P4"]),n]),r=(0,u.p4)(o,["s1"]);(0,t.E3)(r,2),(0,t.E3)(Math.abs(o.col("s1").get(1)-6)<.01,!0),(0,t.E3)(Math.abs(o.col("s1").get(4)-6)<.01,!0),(0,t.E3)(o.getTag("proteomics.imputed"),"true")})}),(0,t.L1)("Differential Expression",()=>{(0,t.t6)("DE produces correct log2FC sign for known groups",async()=>{const e=["ctrl1","ctrl2","ctrl3"],n=["treat1","treat2","treat3"],o=e.map(()=>Array.from({length:5},()=>5)),r=n.map(()=>Array.from({length:5},()=>10)),s=p(5,e,n,o,r);(0,m.ps)(s,e,n,"Control","Treatment");const a=s.col("log2FC");for(let e=0;e<5;e++)(0,t.E3)(a.get(e)>0,!0)}),(0,t.t6)("DE produces valid p-values between 0 and 1",async()=>{const e=["ctrl1","ctrl2","ctrl3"],n=["treat1","treat2","treat3"],o=p(3,e,n,[[4.8,5.1,5.3],[4.9,5,5.2],[5.1,4.8,5]],[[9.8,10.1,10.3],[9.9,10,10.2],[10.1,9.8,10]]);(0,m.ps)(o,e,n,"Control","Treatment");const r=o.col("p-value"),s=o.col("adj.p-value");for(let e=0;e<3;e++)(0,t.E3)(r.get(e)>=0&&r.get(e)<=1,!0),(0,t.E3)(s.get(e)>=0&&s.get(e)<=1,!0)}),(0,t.t6)("proteins with <2 replicates get null p-values",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["P0"]),e.Column.fromFloat32Array("ctrl1",new Float32Array([5])),e.Column.fromFloat32Array("ctrl2",new Float32Array([e.FLOAT_NULL])),e.Column.fromFloat32Array("ctrl3",new Float32Array([e.FLOAT_NULL])),e.Column.fromFloat32Array("treat1",new Float32Array([10])),e.Column.fromFloat32Array("treat2",new Float32Array([10.5])),e.Column.fromFloat32Array("treat3",new Float32Array([9.5]))]);(0,m.ps)(n,["ctrl1","ctrl2","ctrl3"],["treat1","treat2","treat3"],"Control","Treatment");const o=n.col("p-value");(0,t.E3)(o.isNone(0),!0)}),(0,t.t6)("significant column marks proteins passing both thresholds",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["P_significant","P_not_significant"]),e.Column.fromFloat32Array("ctrl1",new Float32Array([5,5])),e.Column.fromFloat32Array("ctrl2",new Float32Array([5.1,5.1])),e.Column.fromFloat32Array("ctrl3",new Float32Array([4.9,4.9])),e.Column.fromFloat32Array("treat1",new Float32Array([12,5.2])),e.Column.fromFloat32Array("treat2",new Float32Array([12.1,4.8])),e.Column.fromFloat32Array("treat3",new Float32Array([11.9,5]))]);(0,m.ps)(n,["ctrl1","ctrl2","ctrl3"],["treat1","treat2","treat3"],"Control","Treatment",1,.05);const o=n.col("significant");(0,t.E3)(o.get(0),!0),(0,t.E3)(o.get(1),!1)}),(0,t.t6)("DE sets proteomics.de_complete tag",async()=>{const e=["ctrl1","ctrl2","ctrl3"],n=["treat1","treat2","treat3"],o=e.map(()=>Array.from({length:2},()=>5)),r=n.map(()=>Array.from({length:2},()=>10)),s=p(2,e,n,o,r);(0,m.ps)(s,e,n,"Control","Treatment"),(0,t.E3)(s.getTag("proteomics.de_complete"),"true")}),(0,t.t6)("D-09: DE dialog defaults to the declared (group1 = numerator) contrast",async()=>{(0,t.E3)((0,m.zV)("DMD","WT"),"DMD vs WT"),(0,t.E3)((0,m.zV)("WT","DMD"),"WT vs DMD")}),(0,t.t6)("D-09: contrast is direction-only — reversing flips sign, not |log2FC|",async()=>{const e=["dmd1","dmd2","dmd3"],n=["wt1","wt2","wt3"],o=e.map(()=>Array.from({length:3},()=>9)),r=n.map(()=>Array.from({length:3},()=>4)),s=p(3,e,n,o,r);(0,m.ps)(s,n,e,"WT","DMD");const a=s.col("log2FC").get(0),i=p(3,e,n,o,r);(0,m.ps)(i,e,n,"DMD","WT");const l=i.col("log2FC").get(0);(0,t.E3)(a>0,!0),(0,t.E3)(l<0,!0),(0,t.E3)(Math.abs(Math.abs(a)-Math.abs(l))<1e-6,!0)}),(0,t.t6)("DE assigns correct semantic types",async()=>{const e=["ctrl1","ctrl2","ctrl3"],n=["treat1","treat2","treat3"],o=e.map(()=>Array.from({length:2},()=>5)),r=n.map(()=>Array.from({length:2},()=>10)),a=p(2,e,n,o,r);(0,m.ps)(a,e,n,"Control","Treatment"),(0,t.E3)(a.col("log2FC").semType,s.iu.LOG2FC),(0,t.E3)(a.col("p-value").semType,s.iu.P_VALUE),(0,t.E3)(a.col("adj.p-value").semType,s.iu.P_VALUE)})}),(0,t.L1)("DE result alignment",()=>{(0,t.t6)("copyDEResultsToFrame realigns by row key, not position",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["P0","P1","P2","P3"])]),o=[3,1,4,2],r=e.DataFrame.fromColumns([e.Column.fromList("int","row",o),e.Column.fromList("double","log2FC",o.map(e=>e-1)),e.Column.fromList("double","p.value",o.map(e=>e-1)),e.Column.fromList("double","adj.p.value",o.map(e=>e-1)),e.Column.fromList("bool","significant",o.map(e=>e-1==0))]),s=(0,m.pd)(n,r);for(let e=0;e<4;e++)(0,t.E3)(n.col("log2FC").get(e),e),(0,t.E3)(n.col("p-value").get(e),e),(0,t.E3)(n.col("adj.p-value").get(e),e),(0,t.E3)(n.col("significant").get(e),0===e);(0,t.E3)(s,1)}),(0,t.t6)("copyDEResultsToFrame falls back to positional without row key",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["P0","P1","P2"])]),o=e.DataFrame.fromColumns([e.Column.fromList("double","log2FC",[10,20,30]),e.Column.fromList("double","p.value",[1,2,3]),e.Column.fromList("double","adj.p.value",[4,5,6]),e.Column.fromList("bool","significant",[!1,!0,!1])]);(0,m.pd)(n,o),(0,t.E3)(n.col("log2FC").get(1),20),(0,t.E3)(n.col("adj.p-value").get(2),6),(0,t.E3)(n.col("significant").get(1),!0),(0,t.E3)(n.col("significant").get(0),!1)})});var d=n(954);function f(e){const t=e.delimiter??",";return[e.headers.join(t),...e.rows.map(e=>e.join(t))].join("\n")}(0,t.L1)("Generic Parser",()=>{(0,t.t6)("Generic: parses CSV with comma delimiter",async()=>{const n=f({headers:["Protein","Intensity A","Intensity B","Intensity C"],rows:[["P12345","1000","2000","3000"],["P67890","4000","5000","6000"]]}),o=(0,d.T6)(n);(0,t.E3)(o,",");const r=e.DataFrame.fromCsv(n,{delimiter:","});(0,t.E3)(r.columns.length,4),(0,t.E3)(r.rowCount,2)}),(0,t.t6)("Generic: parses TSV with tab delimiter",async()=>{const n=f({headers:["Protein","Intensity A","Intensity B","Intensity C"],rows:[["P12345","1000","2000","3000"],["P67890","4000","5000","6000"]],delimiter:"\t"}),o=(0,d.T6)(n);(0,t.E3)(o,"\t");const r=e.DataFrame.fromCsv(n,{delimiter:"\t"});(0,t.E3)(r.columns.length,4),(0,t.E3)(r.rowCount,2)}),(0,t.t6)("Generic: auto-suggests protein ID column",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein IDs",["P12345"]),e.Column.fromStrings("Gene names",["BRCA1"]),e.Column.fromList(e.COLUMN_TYPE.FLOAT,"Intensity A",[1e3])]),o=(0,d.q2)(n);(0,t.E3)(null!==o,!0),(0,t.E3)(o.name,"Protein IDs")}),(0,t.t6)("Generic: auto-suggests intensity columns",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("id",["P12345"]),e.Column.fromList(e.COLUMN_TYPE.FLOAT,"Intensity Sample1",[1e3]),e.Column.fromList(e.COLUMN_TYPE.FLOAT,"LFQ Sample2",[2e3]),e.Column.fromStrings("notes",["some note"])]),o=(0,d.WI)(n);(0,t.E3)(o.length,2),(0,t.E3)(o.includes("Intensity Sample1"),!0),(0,t.E3)(o.includes("LFQ Sample2"),!0)}),(0,t.t6)("Generic: detects raw intensities for log2 toggle",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromList(e.COLUMN_TYPE.FLOAT,"vals",[5e4,1e5,2e5])]),o=(0,d.eY)(n,["vals"]);(0,t.E3)(o.isLog2,!1)}),(0,t.t6)("Generic: detects already-log2 data",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromList(e.COLUMN_TYPE.FLOAT,"vals",[15.2,18.7,12.1])]),o=(0,d.eY)(n,["vals"]);(0,t.E3)(o.isLog2,!0)}),(0,t.t6)("Generic: log2TransformColumns produces correct values",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromList(e.COLUMN_TYPE.FLOAT,"Intensity A",[1024,0,2048])]);(0,d.Kh)(n,["Intensity A"]);const o=n.col("log2(Intensity A)");(0,t.E3)(null!==o,!0),o&&((0,t.E3)(Math.abs(o.get(0)-10)<.001,!0),(0,t.E3)(o.isNone(1),!0),(0,t.E3)(Math.abs(o.get(2)-11)<.001,!0),(0,t.E3)(o.semType,s.iu.INTENSITY));const r=n.col("Intensity A");(0,t.E3)(r.semType,s.iu.INTENSITY)}),(0,t.t6)("Generic: copyAsLog2Columns copies values without transform",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromList(e.COLUMN_TYPE.FLOAT,"Intensity A",[15.2,18.7])]);(0,d.l3)(n,["Intensity A"]);const o=n.col("log2(Intensity A)");(0,t.E3)(null!==o,!0),o&&((0,t.E3)(Math.abs(o.get(0)-15.2)<.001,!0),(0,t.E3)(Math.abs(o.get(1)-18.7)<.001,!0))}),(0,t.t6)("Generic: addPrimaryColumnIfNeeded creates column for semicolons",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein",["P12345;Q67890","P11111"])]);(0,d.wK)(n,"Protein","Primary Protein",s.iu.PROTEIN_ID);const o=n.col("Primary Protein");(0,t.E3)(null!==o,!0),o&&((0,t.E3)(o.get(0),"P12345"),(0,t.E3)(o.get(1),"P11111"))}),(0,t.t6)("Generic: addPrimaryColumnIfNeeded skips when no semicolons",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein",["P12345","P11111"])]);(0,d.wK)(n,"Protein","Primary Protein",s.iu.PROTEIN_ID);const o=n.col("Primary Protein");(0,t.E3)(o,null)}),(0,t.t6)("Generic: assigns semantic types to selected columns",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein",["P12345"])]).col("Protein");n.semType=s.iu.PROTEIN_ID,(0,t.E3)(n.semType,s.iu.PROTEIN_ID)})});var g=n(715);(0,t.L1)("QC Dashboard",()=>{(0,t.t6)("getIntensityColumns",async()=>{const n=e.Column.fromFloat32Array("log2(sample1)",new Float32Array([1,2]));n.semType=s.iu.INTENSITY;const o=e.Column.fromFloat32Array("other",new Float32Array([3,4])),r=e.Column.fromFloat32Array("log2(sample2)",new Float32Array([5,6]));r.semType=s.iu.INTENSITY;const a=e.DataFrame.fromColumns([n,o,r]),i=(0,g.Hc)(a);(0,t.E3)(i.length,2),(0,t.E3)(i[0],"log2(sample1)"),(0,t.E3)(i[1],"log2(sample2)")}),(0,t.t6)("MA computation",async()=>{const n=e.Column.fromFloat32Array("log2(ctrl1)",new Float32Array([10,5,8]));n.semType=s.iu.INTENSITY;const o=e.Column.fromFloat32Array("log2(ctrl2)",new Float32Array([12,7,6]));o.semType=s.iu.INTENSITY;const r=e.Column.fromFloat32Array("log2(treat1)",new Float32Array([8,3,e.FLOAT_NULL]));r.semType=s.iu.INTENSITY;const a=e.Column.fromFloat32Array("log2(treat2)",new Float32Array([6,5,e.FLOAT_NULL]));a.semType=s.iu.INTENSITY;const i=e.DataFrame.fromColumns([n,o,r,a]);(0,g.iQ)(i,{group1:{name:"Control",columns:["log2(ctrl1)","log2(ctrl2)"]},group2:{name:"Treatment",columns:["log2(treat1)","log2(treat2)"]}});const l=i.col("M"),c=i.col("A");(0,t.E3)(Math.abs(l.get(0)- -4)<.01,!0),(0,t.E3)(Math.abs(c.get(0)-9)<.01,!0),(0,t.E3)(l.isNone(2),!0),(0,t.E3)(c.isNone(2),!0)}),(0,t.t6)("CV computation",async()=>{const n=e.Column.fromFloat32Array("log2(s1)",new Float32Array([2,3]));n.semType=s.iu.INTENSITY;const o=e.Column.fromFloat32Array("log2(s2)",new Float32Array([2,5]));o.semType=s.iu.INTENSITY;const r=e.Column.fromFloat32Array("log2(s3)",new Float32Array([2,7]));r.semType=s.iu.INTENSITY;const a=e.DataFrame.fromColumns([n,o,r]);(0,g.JZ)(a,["log2(s1)","log2(s2)","log2(s3)"],"CV","Mean");const i=a.col("CV"),l=a.col("Mean");(0,t.E3)(Math.abs(i.get(0))<.001,!0),(0,t.E3)(Math.abs(l.get(0)-4)<.01,!0),(0,t.E3)(i.get(1)>0,!0)}),(0,t.t6)("Loess/moving-average trend",async()=>{let n=12345;const o=()=>(n=1664525*n+1013904223>>>0,n/4294967295),r=new Float32Array(25),s=new Float32Array(25);for(let e=0;e<25;e++)r[e]=e+1,s[e]=.5*Math.sin(e/5)+.3*(o()-.5);const a=e.DataFrame.fromColumns([e.Column.fromFloat32Array("A",r),e.Column.fromFloat32Array("M",s)]);(0,g.Pq)(a,.5);const i=a.col("MA_trend");(0,t.E3)(null!==i,!0);let l=0;for(let e=0;e<25;e++)i.isNone(e)||l++;(0,t.E3)(l>0,!0);let c=0,u=0,m=0,p=0,d=0,f=0;for(let e=0;e<25;e++){const t=s[e];if(c+=t,u+=t*t,m++,!i.isNone(e)){const t=i.get(e);p+=t,d+=t*t,f++}}const h=u/m-c/m*(c/m),y=d/f-p/f*(p/f);(0,t.E3)(y<h,!0)}),(0,t.t6)("Missingness matrix",async()=>{const n=e.Column.fromFloat32Array("log2(s1)",new Float32Array([5,e.FLOAT_NULL]));n.semType=s.iu.INTENSITY;const o=e.Column.fromFloat32Array("log2(s2)",new Float32Array([e.FLOAT_NULL,3]));o.semType=s.iu.INTENSITY;const r=e.DataFrame.fromColumns([n,o]),a=(0,g.ho)(r,["log2(s1)","log2(s2)"]);(0,t.E3)(a.rowCount,2),(0,t.E3)(a.name,"Missing Values");const i=a.col("log2(s1)"),l=a.col("log2(s2)");(0,t.E3)(i.get(0),1),(0,t.E3)(l.get(0),0),(0,t.E3)(i.get(1),0),(0,t.E3)(l.get(1),1)}),(0,t.t6)("Unpivot intensities",async()=>{const n=e.Column.fromStrings("Protein ID",["P0","P1"]);n.semType=s.iu.PROTEIN_ID;const o=e.Column.fromFloat32Array("log2(s1)",new Float32Array([10,e.FLOAT_NULL]));o.semType=s.iu.INTENSITY;const r=e.Column.fromFloat32Array("log2(s2)",new Float32Array([20,30]));r.semType=s.iu.INTENSITY;const a=e.DataFrame.fromColumns([n,o,r]),i=(0,g.j4)(a,["log2(s1)","log2(s2)"]);(0,t.E3)(i.name,"Intensity Distributions"),(0,t.E3)(i.rowCount,3),(0,t.E3)(null!==i.col("ProteinId"),!0),(0,t.E3)(null!==i.col("Sample"),!0),(0,t.E3)(null!==i.col("Intensity"),!0)}),(0,t.t6)("Missing bar data",async()=>{const n=e.Column.fromFloat32Array("log2(ctrl1)",new Float32Array([5,e.FLOAT_NULL,7]));n.semType=s.iu.INTENSITY;const o=e.Column.fromFloat32Array("log2(treat1)",new Float32Array([10,11,12]));o.semType=s.iu.INTENSITY;const r=e.DataFrame.fromColumns([n,o]),a=(0,g.rA)(r,["log2(ctrl1)","log2(treat1)"],{group1:{name:"Control",columns:["log2(ctrl1)"]},group2:{name:"Treatment",columns:["log2(treat1)"]}});(0,t.E3)(a.rowCount,2);const i=a.col("MissingPct"),l=a.col("Group");(0,t.E3)(Math.abs(i.get(0)-33.333)<1,!0),(0,t.E3)(Math.abs(i.get(1))<.01,!0),(0,t.E3)(l.get(0),"Control"),(0,t.E3)(l.get(1),"Treatment")})});var h=n(230),y=n(897);(0,t.L1)("Enrichment",()=>{(0,t.t6)("buildEnrichmentDf creates correct schema",async()=>{const e=(0,h.Mz)([{native:"GO:0006915",name:"apoptotic process",source:"GO:BP",p_value:.001,significant:!0,term_size:500,query_size:50,intersection_size:10,effective_domain_size:2e4,precision:.2,recall:.02,intersections:[["IEA"],["IDA"],[],["TAS"]]},{native:"KEGG:04210",name:"Apoptosis",source:"KEGG",p_value:.03,significant:!0,term_size:120,query_size:50,intersection_size:5,effective_domain_size:2e4,precision:.1,recall:.042,intersections:[[],["evidence"],[],[]]},{native:"REAC:R-HSA-109581",name:"Apoptosis",source:"REAC",p_value:.12,significant:!1,term_size:80,query_size:50,intersection_size:3,effective_domain_size:2e4,precision:.06,recall:.0375,intersections:[["IEA"],[],[],[]]}],["TP53","BRCA1","EGFR","MYC"]);(0,t.E3)(e.columns.length,8),(0,t.E3)(null!==e.col("Source"),!0),(0,t.E3)(null!==e.col("Term ID"),!0),(0,t.E3)(null!==e.col("Term Name"),!0),(0,t.E3)(null!==e.col("FDR"),!0),(0,t.E3)(null!==e.col("Gene Count"),!0),(0,t.E3)(null!==e.col("Gene Ratio"),!0),(0,t.E3)(null!==e.col("Intersection"),!0),(0,t.E3)(null!==e.col("Significant"),!0),(0,t.E3)(e.rowCount,3)}),(0,t.t6)("buildEnrichmentDf sets enrichment tag",async()=>{const e=(0,h.Mz)([{native:"GO:0006915",name:"apoptotic process",source:"GO:BP",p_value:.001,significant:!0,term_size:500,query_size:50,intersection_size:10,effective_domain_size:2e4,precision:.2,recall:.02,intersections:[["IEA"],["IDA"],[],["TAS"]]},{native:"KEGG:04210",name:"Apoptosis",source:"KEGG",p_value:.03,significant:!0,term_size:120,query_size:50,intersection_size:5,effective_domain_size:2e4,precision:.1,recall:.042,intersections:[[],["evidence"],[],[]]},{native:"REAC:R-HSA-109581",name:"Apoptosis",source:"REAC",p_value:.12,significant:!1,term_size:80,query_size:50,intersection_size:3,effective_domain_size:2e4,precision:.06,recall:.0375,intersections:[["IEA"],[],[],[]]}],["TP53","BRCA1","EGFR","MYC"]);(0,t.E3)(e.getTag("proteomics.enrichment"),"true")}),(0,t.t6)("buildEnrichmentDf marks significant terms",async()=>{const e=(0,h.Mz)([{native:"GO:0006915",name:"apoptotic process",source:"GO:BP",p_value:.001,significant:!0,term_size:500,query_size:50,intersection_size:10,effective_domain_size:2e4,precision:.2,recall:.02,intersections:[["IEA"],["IDA"],[],["TAS"]]},{native:"KEGG:04210",name:"Apoptosis",source:"KEGG",p_value:.03,significant:!0,term_size:120,query_size:50,intersection_size:5,effective_domain_size:2e4,precision:.1,recall:.042,intersections:[[],["evidence"],[],[]]},{native:"REAC:R-HSA-109581",name:"Apoptosis",source:"REAC",p_value:.12,significant:!1,term_size:80,query_size:50,intersection_size:3,effective_domain_size:2e4,precision:.06,recall:.0375,intersections:[["IEA"],[],[],[]]}],["TP53","BRCA1","EGFR","MYC"]).col("Significant");(0,t.E3)(e.get(0),!0),(0,t.E3)(e.get(1),!0),(0,t.E3)(e.get(2),!1)}),(0,t.t6)("buildEnrichmentDf extracts intersection genes",async()=>{const e=(0,h.Mz)([{native:"GO:0006915",name:"apoptotic process",source:"GO:BP",p_value:.01,significant:!0,term_size:500,query_size:4,intersection_size:2,effective_domain_size:2e4,precision:.5,recall:.004,intersections:[["IEA"],[],["TAS"],[]]}],["TP53","BRCA1","EGFR","MYC"]).col("Intersection").get(0);(0,t.E3)(e,"TP53, EGFR")}),(0,t.t6)("countSignificantProteins counts correctly",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromFloat32Array("log2FC",new Float32Array([2,.5,-1.5,3])),e.Column.fromFloat32Array("adjP",new Float32Array([.01,.001,.1,.03]))]),o=(0,h.bM)(n,1,.05,n.col("log2FC"),n.col("adjP"));(0,t.E3)(o.significant,2),(0,t.E3)(o.total,4)}),(0,t.t6)("countSignificantProteins handles null values",async()=>{const n=e.Column.fromFloat32Array("log2FC",new Float32Array([2,0,-1.5])),o=e.Column.fromFloat32Array("adjP",new Float32Array([.01,0,.03]));n.set(1,e.FLOAT_NULL),o.set(1,e.FLOAT_NULL);const r=e.DataFrame.fromColumns([n,o]),s=(0,h.bM)(r,1,.05,n,o);(0,t.E3)(s.significant,2),(0,t.E3)(s.total,3)}),(0,t.t6)("splitGenesByDirection splits significant genes by fc sign, shared background",async()=>{const e=new Map([[0,"A"],[1,"B"],[2,"C"],[3,"D"]]),n=new Float32Array([2,-2,.5,-3]),o=new Float32Array([.01,.01,.001,.2]),{upGenes:r,downGenes:s,background:a}=(0,h.Bx)(e,n,o,1,.05);(0,t.E3)(r.length,1),(0,t.E3)(r[0],"A"),(0,t.E3)(s.length,1),(0,t.E3)(s[0],"B"),(0,t.E3)(a.length,4),(0,t.E3)(a.includes("A")&&a.includes("B")&&a.includes("C")&&a.includes("D"),!0),(0,t.E3)(r.some(e=>s.includes(e)),!1)}),(0,t.t6)("splitGenesByDirection skips null fc/p rows",async()=>{const n=new Map([[0,"A"],[1,"B"]]),o=new Float32Array([2,0]),r=new Float32Array([.01,0]);o[1]=e.FLOAT_NULL,r[1]=e.FLOAT_NULL;const{upGenes:s,downGenes:a,background:i}=(0,h.Bx)(n,o,r,1,.05);(0,t.E3)(s.length,1),(0,t.E3)(a.length,0),(0,t.E3)(i.length,2)}),(0,t.t6)("buildEnrichmentDf adds Direction column when label given",async()=>{const e=(0,h.Mz)([{native:"GO:0006915",name:"apoptotic process",source:"GO:BP",p_value:.001,significant:!0,term_size:500,query_size:50,intersection_size:10,effective_domain_size:2e4,precision:.2,recall:.02,intersections:[["IEA"],["IDA"],[],["TAS"]]},{native:"KEGG:04210",name:"Apoptosis",source:"KEGG",p_value:.03,significant:!0,term_size:120,query_size:50,intersection_size:5,effective_domain_size:2e4,precision:.1,recall:.042,intersections:[[],["evidence"],[],[]]},{native:"REAC:R-HSA-109581",name:"Apoptosis",source:"REAC",p_value:.12,significant:!1,term_size:80,query_size:50,intersection_size:3,effective_domain_size:2e4,precision:.06,recall:.0375,intersections:[["IEA"],[],[],[]]}],["TP53","BRCA1","EGFR","MYC"],.05,"Up"),n=e.col("Direction");(0,t.E3)(null!==n,!0),(0,t.E3)(n.get(0),"Up"),(0,t.E3)(n.get(1),"Up"),(0,t.E3)(e.columns.length,9),(0,t.E3)(null!==e.col("Intersection"),!0),(0,t.E3)(e.getTag("proteomics.enrichment"),"true")}),(0,t.t6)("buildEnrichmentDf omits Direction column when no label",async()=>{const e=(0,h.Mz)([{native:"GO:0006915",name:"apoptotic process",source:"GO:BP",p_value:.001,significant:!0,term_size:500,query_size:50,intersection_size:10,effective_domain_size:2e4,precision:.2,recall:.02,intersections:[["IEA"],["IDA"],[],["TAS"]]},{native:"KEGG:04210",name:"Apoptosis",source:"KEGG",p_value:.03,significant:!0,term_size:120,query_size:50,intersection_size:5,effective_domain_size:2e4,precision:.1,recall:.042,intersections:[[],["evidence"],[],[]]},{native:"REAC:R-HSA-109581",name:"Apoptosis",source:"REAC",p_value:.12,significant:!1,term_size:80,query_size:50,intersection_size:3,effective_domain_size:2e4,precision:.06,recall:.0375,intersections:[["IEA"],[],[],[]]}],["TP53","BRCA1","EGFR","MYC"]);(0,t.E3)(e.col("Direction"),null),(0,t.E3)(e.columns.length,8)}),(0,t.t6)("wireEnrichmentToVolcano selects matching proteins, source DF unmutated",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Intersection",["TP53, EGFR"]),e.Column.fromStrings("Direction",["Up"])]),o=e.Column.fromStrings("Gene Symbol",["TP53","EGFR","MYC"]);o.semType=s.iu.GENE_SYMBOL;const r=e.DataFrame.fromColumns([o]),a=(0,y.aB)(n,r);n.currentRowIdx=0,(0,t.E3)(r.selection.trueCount,2),(0,t.E3)(r.selection.get(2),!1),(0,t.E3)(n.rowCount,1),(0,t.E3)(r.rowCount,3),a.unsubscribe()}),(0,t.t6)("ORGANISM_LIST contains 9 entries with valid codes",async()=>{(0,t.E3)(h.Ae.length,9),(0,t.E3)(h.Ae[0].display,"Homo sapiens (Human)"),(0,t.E3)(h.Ae[0].code,"hsapiens");for(const e of h.Ae)(0,t.E3)(e.display.length>0,!0),(0,t.E3)(e.code.length>0,!0)})});var E=n(989);function w(){const t=e.DataFrame.fromColumns([e.Column.fromStrings("Gene names",["G1","G2","G3"]),e.Column.fromFloat32Array("log2FC",new Float32Array([2,-2,.1])),e.Column.fromFloat32Array("adj.p-value",new Float32Array([.01,.01,.5]))]);return t.col("Gene names").semType=s.iu.GENE_SYMBOL,t.col("log2FC").semType=s.iu.LOG2FC,t.col("adj.p-value").semType=s.iu.P_VALUE,t}(0,t.L1)("Enrichment Export",()=>{(0,t.t6)("buildEnrichmentInputsCsv: up/down/background split matches thresholds",async()=>{const{csv:e,counts:n}=(0,E.J)(w(),1,.05);(0,t.E3)(n.up,1,"one up gene"),(0,t.E3)(n.down,1,"one down gene"),(0,t.E3)(n.background,3,"all three genes in background");const o=e.split("\n");(0,t.E3)(o[0],"gene,list","tidy long header"),(0,t.E3)(o.includes("G1,up"),!0,"G1 is up"),(0,t.E3)(o.includes("G2,down"),!0,"G2 is down"),(0,t.E3)(o.includes("G1,background")&&o.includes("G2,background")&&o.includes("G3,background"),!0,"all genes listed as background"),(0,t.E3)(o.includes("G3,up")||o.includes("G3,down"),!1,"G3 stays background-only")}),(0,t.t6)("buildEnrichmentInputsCsv: looser thresholds pull more genes in",async()=>{const{counts:e}=(0,E.J)(w(),0,.6);(0,t.E3)(e.up,2,"G1 and G3 now up"),(0,t.E3)(e.down,1,"G2 still down"),(0,t.E3)(e.background,3,"background unchanged")}),(0,t.t6)("buildEnrichmentInputsCsv: quotes a gene containing a comma",async()=>{const e=w();e.col("Gene names").set(0,"G1,alias");const{csv:n}=(0,E.J)(e,1,.05);(0,t.E3)(n.includes('"G1,alias",up'),!0,"comma-bearing field is CSV-quoted")}),(0,t.t6)("buildEnrichmentInputsCsv: throws without DE columns",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Gene names",["G1"])]);n.col("Gene names").semType=s.iu.GENE_SYMBOL;let o=!1;try{(0,E.J)(n,1,.05)}catch{o=!0}(0,t.E3)(o,!0,"missing log2FC/adj.p-value is an error")})});var v=n(328),_=n(858);function C(t,n){const o=[],r=[],s=[],a=[],i=[],l=[],c=[],u=[],m=[];for(let e=0;e<t;e++){o.push(e%2==0?"GO:BP":"KEGG"),r.push(`GO:${String(e).padStart(7,"0")}`),s.push(n&&0===e?n:`Term ${e+1}`);const t=.001*(e+1);a.push(t),i.push(t),l.push(10-Math.min(e,9)),c.push(.2-.005*e),u.push("TP53, BRCA1"),m.push(t<.05)}const p=e.DataFrame.fromColumns([e.Column.fromStrings("Source",o),e.Column.fromStrings("Term ID",r),e.Column.fromStrings("Term Name",s),e.Column.fromFloat32Array("P-value",new Float32Array(a)),e.Column.fromFloat32Array("FDR",new Float32Array(i)),e.Column.fromInt32Array("Gene Count",new Int32Array(l)),e.Column.fromFloat32Array("Gene Ratio",new Float32Array(c)),e.Column.fromStrings("Intersection",u),e.Column.fromList("bool","Significant",m)]);return p.setTag("proteomics.enrichment","true"),p}function b(){const t=e.Column.fromStrings("Gene Name",["TP53","BRCA1","EGFR","MYC","AKT1"]);return t.semType=s.iu.GENE_SYMBOL,e.DataFrame.fromColumns([t,e.Column.fromFloat32Array("log2FC",new Float32Array([1.5,-2,.5,3,-1])),e.Column.fromFloat32Array("adj.p-value",new Float32Array([.001,.01,.5,1e-4,.04]))])}function T(t,n){t.columns.add(e.Column.fromStrings("Direction",n))}function P(e,t){let n=0;for(const o of e.viewers)o.dataFrame?.dart===t.dart&&n++;return n}function S(e){let t=0;for(const n of e.viewers)t++;return t}function N(e){let t=0;for(let n=0;n<e.length;n++)!0===e.get(n)&&t++;return t}(0,t.L1)("Enrichment Visualization",()=>{(0,t.t6)("prepareEnrichmentChartColumns adds negLog10FDR on the same frame",async()=>{const e=C(20);(0,y.E0)(e,15);const n=e.col(y.bC);(0,t.E3)(null!==n,!0);const o=n.get(0);(0,t.E3)(Math.abs(o-3)<.01,!0),(0,t.E3)(e.rowCount,20)}),(0,t.t6)("prepareEnrichmentChartColumns marks exactly topN terms (no Direction)",async()=>{const e=C(20);(0,y.E0)(e,15);const n=e.col(y.$i);(0,t.E3)(N(n),15)}),(0,t.t6)("prepareEnrichmentChartColumns marks topN per direction",async()=>{const e=C(20);T(e,Array.from({length:20},(e,t)=>t<10?"Up":"Down")),(0,y.E0)(e,5);const n=e.col(y.$i);(0,t.E3)(N(n),10)}),(0,t.t6)("prepareEnrichmentChartColumns marks all when fewer rows than topN",async()=>{const e=C(5);(0,y.E0)(e,15);const n=e.col(y.$i);(0,t.E3)(N(n),5)}),(0,t.t6)("prepareEnrichmentChartColumns is idempotent on re-run",async()=>{const e=C(20);(0,y.E0)(e,15);const n=e.columns.length;(0,y.E0)(e,15),(0,t.E3)(e.columns.length,n)}),(0,t.t6)("wireEnrichmentToVolcano returns EMPTY without gene column",async()=>{const n=C(3),o=e.DataFrame.fromColumns([e.Column.fromStrings("SomeColumn",["A","B","C"])]),r=(0,y.aB)(n,o);(0,t.E3)(r===_.Subscription.EMPTY,!0)}),(0,t.t6)("wireEnrichmentToVolcano selects matching genes on protein DataFrame",async()=>{const e=C(3);e.col("Intersection").set(0,"TP53, BRCA1");const n=b(),o=(0,y.aB)(e,n);(0,t.E3)(o!==_.Subscription.EMPTY,!0),e.currentRowIdx=0,(0,t.E3)(n.selection.get(0),!0),(0,t.E3)(n.selection.get(1),!0),(0,t.E3)(n.selection.get(2),!1),(0,t.E3)(n.selection.get(3),!1),(0,t.E3)(n.selection.get(4),!1),o.unsubscribe()}),(0,t.t6)("wireEnrichmentToVolcano clears selection before new selection",async()=>{const e=C(3);e.col("Intersection").set(0,"TP53"),e.col("Intersection").set(1,"EGFR");const n=b();n.selection.set(4,!0,!1),n.selection.fireChanged();const o=(0,y.aB)(e,n);e.currentRowIdx=0,(0,t.E3)(n.selection.get(4),!1),(0,t.E3)(n.selection.get(0),!0),o.unsubscribe()}),(0,t.t6)("openEnrichmentVisualization docks dot/bar on enrichment view (directional)",async()=>{const e=C(4);T(e,["Up","Up","Down","Down"]),e.name="Enrichment (test B)";const n=b();n.name="Protein (test B)";const o=v.shell.addTableView(n),r=S(o),s=(0,y.q6)(e,n);try{(0,t.E3)(S(o),r,"protein view must not gain dot/bar viewers; gained "+(S(o)-r)),(0,t.E3)(S(s)>=4,!0,`enrichment view should carry ≥4 dot/bar viewers; got ${S(s)}`),(0,t.E3)(P(s,n),0,"enrichment view must not carry a proteinDf-bound volcano"),e.currentRowIdx=0,(0,t.E3)(n.selection.trueCount>=1,!0,"selecting an enrichment row should still highlight matching protein rows")}finally{s.close(),o.close()}}),(0,t.t6)("openEnrichmentVisualization docks dot/bar on enrichment view (single-direction)",async()=>{const e=C(3);e.name="Enrichment (test C)";const n=b();n.name="Protein (test C)";const o=v.shell.addTableView(n),r=S(o),s=(0,y.q6)(e,n);try{(0,t.E3)(S(o),r,"protein view must not gain dot/bar viewers; gained "+(S(o)-r)),(0,t.E3)(S(s)>=2,!0,`enrichment view should carry ≥2 dot/bar viewers; got ${S(s)}`),(0,t.E3)(P(s,n),0,"enrichment view must not carry a proteinDf-bound volcano")}finally{s.close(),o.close()}}),(0,t.t6)("openEnrichmentVisualization switches focus to enrichment TableView",async()=>{const e=C(4);T(e,["Up","Up","Down","Down"]),e.name="Enrichment (test D)";const n=b();n.name="Protein (test D)";const o=v.shell.addTableView(n),r=(0,y.q6)(e,n);try{const n=v.shell.v?.dataFrame?.dart;(0,t.E3)(n===e.dart,!0,"focused view should be the enrichment TableView after enrichment runs")}finally{r.close(),o.close()}}),(0,t.t6)("enrichmentBannerRendersWhenTagSet",async()=>{const e=C(3);e.name="Enrichment (banner-on)",e.setTag("proteomics.enrichment_smart_filtered","true"),e.setTag("proteomics.enrichment_smart_filtered_kept","20"),e.setTag("proteomics.enrichment_smart_filtered_total","47"),e.setTag("proteomics.enrichment_smart_filtered_dropped_parents","3"),e.setTag("proteomics.enrichment_smart_filtered_cap","15");const n=b(),o=(0,y.q6)(e,n);try{const e=o.root.querySelectorAll('[data-smart-filter-banner="true"]');(0,t.E3)(e.length>=1,!0,"banner should be docked when tag is set");const n=e[0].textContent??"";(0,t.E3)(n.includes("Smart pathway filter active"),!0),(0,t.E3)(n.includes("showing 20 of 47 terms"),!0),(0,t.E3)(n.includes("dropped 3 generic parents"),!0),(0,t.E3)(n.includes("capped at 15 per source"),!0),(0,t.E3)(n.includes("Re-run with the filter off"),!0)}finally{o.close()}}),(0,t.t6)("enrichmentBannerAbsentWhenTagUnset",async()=>{const e=C(3);e.name="Enrichment (banner-off)";const n=b(),o=(0,y.q6)(e,n);try{const e=o.root.querySelectorAll('[data-smart-filter-banner="true"]');(0,t.E3)(e.length,0)}finally{o.close()}})});var A=n(53),x=n(110);function D(e){const t=[["R.FileName","R.Condition","R.Replicate","PG.ProteinGroups","PG.Organisms",e.quantityColumn??"PG.IBAQ","EG.Qvalue","PEP.StrippedSequence","EG.ModifiedPeptide","FG.Charge","FG.Id"].join("\t")],n=[{strip:"PEPTIDER",mod:"_PEPTIDER_",charge:"2",fg:"FG1"},{strip:"ANOTHERPEP",mod:"_ANOTHERPEP_",charge:"3",fg:"FG2"}],o=(e,o,r,s,a,i,l)=>{for(const c of n)t.push([e,o,String(r),s,a,i,l,c.strip,c.mod,c.charge,c.fg].join("\t"))};let r=100;for(const t of e.proteins){const n=e.ibaqValues?.get(t.id)??r++;for(const r of e.conditions)for(const s of e.replicates){const a=(e.fileNameTemplate??"file")+`_${r}_${s}`,i=e.qValues?.get(t.id)??.001,l=t.organism??"Homo sapiens";o(a,r,s,t.id,l,String(n),String(i))}}if(e.extraRows){let t=500;for(const n of e.extraRows){const r=n.quantity??t++;for(const t of e.conditions)for(const s of e.replicates){const a=(e.fileNameTemplate??"file")+`_${t}_${s}`,i=n.organism??"Homo sapiens";o(a,t,s,n.id,i,String(r),String(n.qValue))}}}return t.join("\n")}(0,t.L1)("Spectronaut",()=>{const e=[{id:"P12345"},{id:"Q67890"},{id:"O15439"}],n={proteins:e,conditions:["CondA","CondB"],replicates:[1,2]};async function o(e){return await(0,A.A)(new File([e],"fixture.tsv",{type:"text/tab-separated-values"}))}async function r(e){return je.files.readAsText(`demo/${e}`)}function a(e){return e.columns.toList().filter(e=>e.semType===s.iu.INTENSITY&&!e.name.startsWith("log2(")).map(e=>e.name).sort()}function i(e){const t=e.col("Primary Protein ID")??e.col("PG.ProteinGroups"),n=new Map;for(let o=0;o<e.rowCount;o++)n.set(String(t.get(o)),o);return{col:t,map:n}}async function c(e){const t=[],n=v.shell.info.bind(v.shell);v.shell.info=e=>{t.push(String(e))};try{return{df:await o(e),infos:t}}finally{v.shell.info=n}}(0,t.t6)("pivot produces correct protein count",async()=>{const e=D(n),o=await(0,A.parseSpectronautText)(e);(0,t.E3)(o.rowCount,3)}),(0,t.t6)("pivot produces correct sample column names",async()=>{const e=D(n),o=await(0,A.parseSpectronautText)(e);(0,t.E3)(null!==o.col("CondA_1"),!0),(0,t.E3)(null!==o.col("CondA_2"),!0),(0,t.E3)(null!==o.col("CondB_1"),!0),(0,t.E3)(null!==o.col("CondB_2"),!0)}),(0,t.t6)("CON__ and REV__ prefixed proteins are excluded",async()=>{const e=D({...n,proteins:[{id:"P12345"},{id:"CON__P99999"},{id:"REV__Q11111"}]}),o=await(0,A.parseSpectronautText)(e);(0,t.E3)(o.rowCount,1),(0,t.E3)(o.col("PG.ProteinGroups").get(0),"P12345")}),(0,t.t6)("rows with numeric EG.Qvalue > threshold are excluded",async()=>{const o=new Map;o.set("P12345",.001),o.set("Q67890",.05),o.set("O15439",.005);const r=D({...n,proteins:e,qValues:o}),s=await(0,A.parseSpectronautText)(r);(0,t.E3)(s.rowCount,2)}),(0,t.t6)("non-numeric EG.Qvalue rows treated as passing",async()=>{const o=new Map;o.set("P12345",.001),o.set("Q67890","Profiled"),o.set("O15439","NaN");const r=D({...n,proteins:e,qValues:o}),s=await(0,A.parseSpectronautText)(r);(0,t.E3)(s.rowCount,3)}),(0,t.t6)("PG.ProteinGroups has PROTEIN_ID semantic type",async()=>{const e=D(n),o=await(0,A.parseSpectronautText)(e);(0,t.E3)(o.col("PG.ProteinGroups")?.semType,s.iu.PROTEIN_ID)}),(0,t.t6)("intensity columns have INTENSITY semantic type",async()=>{const e=D(n),o=await(0,A.parseSpectronautText)(e);(0,t.E3)(o.col("CondA_1")?.semType,s.iu.INTENSITY),(0,t.E3)(o.col("CondB_2")?.semType,s.iu.INTENSITY)}),(0,t.t6)("R.FileName stored as spectronaut.fileName tag on intensity columns",async()=>{const e=D({...n,fileNameTemplate:"run"}),o=(await(0,A.parseSpectronautText)(e)).col("CondA_1");if((0,t.E3)(null!==o,!0),o){const e=o.getTag("spectronaut.fileName");(0,t.E3)(null!==e&&""!==e,!0),(0,t.E3)(e.includes("run"),!0)}}),(0,t.t6)("groups auto-populated via setGroups when exactly 2 conditions",async()=>{const e=D(n),o=await(0,A.parseSpectronautText)(e),r=(0,l.f)(o);(0,t.E3)(null!==r,!0),r&&((0,t.E3)(r.group1.columns.length,2),(0,t.E3)(r.group2.columns.length,2))}),(0,t.t6)("groups not set when more than 2 conditions",async()=>{const e=D({...n,conditions:["CondA","CondB","CondC"]}),o=await(0,A.parseSpectronautText)(e),r=(0,l.f)(o);(0,t.E3)(r,null)}),(0,t.t6)("pre-normalized tag set for raw (non-log2) intensity data",async()=>{const e=D(n),o=await(0,A.parseSpectronautText)(e);(0,t.E3)(o.getTag("proteomics.preNormalized"),"true")}),(0,t.t6)("pre-normalized tag set when detectLog2Status detects log2-range values",async()=>{const e=new Map;e.set("P12345",15.2),e.set("Q67890",22.7),e.set("O15439",18.1);const o=D({...n,ibaqValues:e}),r=await(0,A.parseSpectronautText)(o);(0,t.E3)(r.getTag("proteomics.preNormalized"),"true")}),(0,t.t6)("both raw and log2 intensity columns present in output",async()=>{const e=D(n),o=await(0,A.parseSpectronautText)(e);(0,t.E3)(null!==o.col("CondA_1"),!0),(0,t.E3)(null!==o.col("log2(CondA_1)"),!0),(0,t.E3)(null!==o.col("log2(CondB_2)"),!0)}),(0,t.t6)("proteomics.source tag set to spectronaut",async()=>{const e=D(n),o=await(0,A.parseSpectronautText)(e);(0,t.E3)(o.getTag("proteomics.source"),"spectronaut")}),(0,t.t6)("PG.Quantity accepted as alternative to PG.IBAQ",async()=>{const e=D({...n,quantityColumn:"PG.Quantity"}),o=await(0,A.parseSpectronautText)(e);(0,t.E3)(o.rowCount,3),(0,t.E3)(null!==o.col("CondA_1"),!0),(0,t.E3)(null!==o.col("CondB_2"),!0),(0,t.E3)(o.col("CondA_1")?.semType,s.iu.INTENSITY)}),(0,t.t6)("throws when neither PG.IBAQ nor PG.Quantity is present",async()=>{const e=D({...n,quantityColumn:"PG.Bogus"});let o=!1;try{await(0,A.parseSpectronautText)(e)}catch(e){o=!0,(0,t.E3)(e.message.includes("PG.IBAQ"),!0),(0,t.E3)(e.message.includes("PG.Quantity"),!0)}(0,t.E3)(o,!0)}),(0,t.t6)("demo file produces correct dimensions",async()=>{const e=[];for(let t=0;t<93;t++)e.push({id:`P${String(t).padStart(5,"0")}`});const n=D({proteins:e,conditions:["HYE mix A","HYE mix B"],replicates:[1,2,3,4]}),o=await(0,A.parseSpectronautText)(n);(0,t.E3)(o.rowCount,93);const r=o.columns.toList().filter(e=>e.semType===s.iu.INTENSITY&&!e.name.startsWith("log2("));(0,t.E3)(r.length,8)}),(0,t.t6)("streams precursor fixture",async()=>{const e=await r("spectronaut-hye-precursor.tsv"),n=await o(e);(0,t.E3)(n.rowCount>0,!0);const a=n.columns.toList().find(e=>e.semType===s.iu.INTENSITY&&!e.name.startsWith("log2(")&&(e.name.startsWith("CondA_")||e.name.startsWith("CondB_")));(0,t.E3)(void 0!==a,!0),(0,t.E3)(n.col("PG.ProteinGroups")?.semType,s.iu.PROTEIN_ID)}),(0,t.t6)("sniffIsPrecursor routes by header",async()=>{const e=["R.FileName","R.Condition","R.Replicate","PG.ProteinGroups","PG.Organisms","PG.Quantity","EG.Qvalue","EG.ModifiedPeptide","FG.Charge","PEP.StrippedSequence"].join("\t"),n=["run_CondA_1","CondA","1","P1","Homo sapiens","10","0.001","_PEP_","2","PEP"].join("\t"),o=["R.FileName","R.Condition","R.Replicate","PG.ProteinGroups","PG.Organisms","PG.IBAQ"].join("\t"),r=["run_CondA_1","CondA","1","P1","Homo sapiens","10"].join("\t");(0,t.E3)(await(0,x.sniffIsPrecursor)(new File([e+"\n"+n],"p.tsv")),!0),(0,t.E3)(await(0,x.sniffIsPrecursor)(new File([o+"\n"+r],"pg.tsv")),!1)}),(0,t.t6)("stream path matches text path",async()=>{const e=D(n),r=await(0,A.parseSpectronautText)(e),s=await o(e);(0,t.E3)(s.rowCount,r.rowCount);const c=a(r),u=a(s);(0,t.E3)(u.join(","),c.join(","));for(const e of c)(0,t.E3)(null!==s.col(`log2(${e})`),null!==r.col(`log2(${e})`));(0,t.E3)(s.getTag("proteomics.source"),r.getTag("proteomics.source")),(0,t.E3)(s.getTag("proteomics.preNormalized"),r.getTag("proteomics.preNormalized"));const m=(0,l.f)(r),p=(0,l.f)(s);(0,t.E3)(null!==p,null!==m),m&&p&&((0,t.E3)(p.group1.columns.length,m.group1.columns.length),(0,t.E3)(p.group2.columns.length,m.group2.columns.length));const d=i(r),f=i(s);(0,t.E3)(f.map.size,d.map.size);for(const[e,n]of d.map){const o=f.map.get(e);(0,t.E3)(void 0!==o,!0);for(const e of c){const a=r.col(e),i=s.col(e),l=a.isNone(n),c=i.isNone(o);if((0,t.E3)(c,l),!l&&!c){const e=a.get(n),r=i.get(o);(0,t.E3)(Math.abs(e-r)<=.001,!0)}}}}),(0,t.t6)("streaming filter parity",async()=>{const e=D({...n,proteins:[{id:"KEEP1"},{id:"KEEP2"}],extraRows:[{id:"CON__C1",qValue:.001},{id:"REV__R1",qValue:.001},{id:"HIGHQ",qValue:.05},{id:"PROF",qValue:"Profiled"},{id:"EMPTYQ",qValue:""}]}),r=await o(e),s=r.col("PG.ProteinGroups"),a=new Set;for(let e=0;e<r.rowCount;e++)a.add(String(s.get(e)));(0,t.E3)(a.has("CON__C1"),!1),(0,t.E3)(a.has("REV__R1"),!1),(0,t.E3)(a.has("HIGHQ"),!1),(0,t.E3)(a.has("PROF"),!0),(0,t.E3)(a.has("EMPTYQ"),!0),(0,t.E3)(r.rowCount,4)}),(0,t.t6)("by-design-filtered rows are not counted malformed",async()=>{const e=D({...n,proteins:[{id:"KEEP1"},{id:"KEEP2"}],extraRows:[{id:"CON__C1",qValue:.001},{id:"REV__R1",qValue:.001},{id:"HIGHQ",qValue:.05}]}),{df:o,infos:r}=await c(e),s=o.col("PG.ProteinGroups"),a=new Set;for(let e=0;e<o.rowCount;e++)a.add(String(s.get(e)));(0,t.E3)(a.has("KEEP1"),!0),(0,t.E3)(a.has("KEEP2"),!0),(0,t.E3)(a.has("CON__C1"),!1),(0,t.E3)(a.has("REV__R1"),!1),(0,t.E3)(a.has("HIGHQ"),!1),(0,t.E3)(o.rowCount,2);const i=r.filter(e=>/malformed/i.test(e));(0,t.E3)(i.length,0)}),(0,t.t6)("truncated line is counted malformed",async()=>{const e=D({...n,proteins:[{id:"KEEP1"},{id:"KEEP2"}]})+"\nfile\tCondA\t1",{df:o,infos:r}=await c(e),s=o.col("PG.ProteinGroups"),a=new Set;for(let e=0;e<o.rowCount;e++)a.add(String(s.get(e)));(0,t.E3)(a.has("KEEP1"),!0),(0,t.E3)(a.has("KEEP2"),!0),(0,t.E3)(o.rowCount,2);const i=r.some(e=>/skipped \d+ malformed line\(s\)/.test(e));(0,t.E3)(i,!0)}),(0,t.t6)("empty-protein rows are filtered silently (streaming↔text parity)",async()=>{const e=D({...n,proteins:[{id:"KEEP1"},{id:"KEEP2"}],extraRows:[{id:"",qValue:.001},{id:"",qValue:.002}]}),{df:o,infos:r}=await c(e),s=o.col("PG.ProteinGroups"),a=new Set;for(let e=0;e<o.rowCount;e++)a.add(String(s.get(e)));(0,t.E3)(a.has("KEEP1"),!0),(0,t.E3)(a.has("KEEP2"),!0),(0,t.E3)(a.has(""),!1),(0,t.E3)(o.rowCount,2);const i=r.filter(e=>/malformed/i.test(e));(0,t.E3)(i.length,0)}),(0,t.t6)("both-numeric-casts-null rows are filtered silently (streaming↔text parity)",async()=>{const e=D({...n,proteins:[{id:"KEEP1"},{id:"KEEP2"}],extraRows:[{id:"NULLPAIR",quantity:"NaN",qValue:"NA"}]}),{df:o,infos:r}=await c(e);(0,t.E3)(o.rowCount,2);const s=r.filter(e=>/malformed/i.test(e));(0,t.E3)(s.length,0)}),(0,t.t6)("streaming tag set and groups",async()=>{const e=await o(D(n));(0,t.E3)(e.getTag("proteomics.source"),"spectronaut"),(0,t.E3)(e.getTag("proteomics.preNormalized"),"true");const r=(0,l.f)(e);(0,t.E3)(null!==r,!0),r&&((0,t.E3)(r.group1.columns.length,2),(0,t.E3)(r.group2.columns.length,2))}),(0,t.t6)("streaming output equals duckdb golden",async()=>{const e=JSON.parse(await r("spectronaut-hye-precursor-golden.json")),n=await r("spectronaut-hye-precursor.tsv"),s=await o(n),{map:l}=i(s),c=a(s),u=Object.keys(e);(0,t.E3)(u.length>0,!0);for(const n of u){const o=n.match(/^(.*?)((?:Cond[A-Za-z]+)_\d+)$/);(0,t.E3)(null!==o,!0);const r=o[1],a=o[2],i=l.get(r);(0,t.E3)(void 0!==i,!0);const c=s.col(a);(0,t.E3)(null!==c,!0),(0,t.E3)(c.isNone(i),!1);const u=c.get(i);(0,t.E3)(Math.abs(u-e[n].quantity)<=.001,!0)}const m=new Set;for(const[e,t]of l)for(const n of c)s.col(n).isNone(t)||m.add(`${e}${n}`);const p=new Set(u);(0,t.E3)(m.size,p.size);for(const e of m)(0,t.E3)(p.has(e),!0);for(const e of p)(0,t.E3)(m.has(e),!0)}),(0,t.t6)("duckdb fallback tooling is committed",async()=>{(0,t.E3)(!0,!0),(0,t.E3)(!0,!0),(0,t.E3)("-- Aggregate a long-form Spectronaut Report (peptide/precursor/fragment-level rows)\n-- down to one row per (protein-group × condition × replicate), in the shape\n-- packages/Proteomics/src/parsers/spectronaut-parser.ts expects.\n--\n-- This is the bundled, documented manual fallback (D-05) for a Spectronaut report\n-- too large for the in-browser streaming importer, AND the D-04 equivalence oracle\n-- the Wave-0 golden test pins to.\n--\n-- Template tokens __IN_PATH__ and __OUT_PATH__ are replaced by the shell wrapper\n-- before this script is passed to duckdb. (DuckDB's COPY ... TO does not accept\n-- variables, so we can't use SET VARIABLE here.)\n\n-- Streaming aggregation — duckdb spills to disk if it can't fit memory.\nPRAGMA memory_limit='8GB';\nPRAGMA threads=8;\n\nCOPY (\n SELECT\n \"PG.ProteinGroups\",\n -- DIVERGENCE FROM /tmp/spectronaut-aggregate.sql: the two carry-along\n -- any_value() SELECT terms for the gene-symbol and protein-accession columns\n -- (present in the /tmp original) were DROPPED here. The package's Spectronaut\n -- data (files/demo/spectronaut-hye-mix.tsv and the synthetic precursor\n -- fixture) does not carry those two columns and\n -- pivotSpectronaut/aggToPivotResult never consume them, so they are not part\n -- of the parity contract; keeping them would Binder-Error duckdb on the\n -- fixture (ignore_errors does NOT cover Binder Errors) and the entire Wave-0\n -- oracle chain (golden → sidecar → 12-03 golden test) would have no source.\n --\n -- ============================ WARNING ============================\n -- REFERENCE-FILE-ONLY: the CASE below is a one-off correction for the\n -- mislabeled reference file `2026-05-13 BP DMD WT.tsv` ONLY. Cross-tab\n -- against R.FileName showed every WT* filename tagged DMD and every DMD*\n -- filename tagged WT (24/24); this restores the convention so DE direction\n -- matches what the filenames imply. It is a STRUCTURAL NO-OP on any data\n -- whose R.Condition is not literally 'DMD'/'WT' — including the CondA/CondB\n -- synthetic fixture, which is exactly why this same script doubles as the\n -- D-04 golden oracle without perturbing the golden. The streaming TS\n -- aggregator MUST NOT port this flip (RESEARCH Pitfall 1 — the single\n -- highest-risk parity trap). Do not \"generalize\" or remove it either: the\n -- manual-fallback path still needs it for the mislabeled reference file.\n -- =================================================================\n CASE \"R.Condition\"\n WHEN 'DMD' THEN 'WT'\n WHEN 'WT' THEN 'DMD'\n ELSE \"R.Condition\"\n END AS \"R.Condition\",\n \"R.Replicate\",\n any_value(\"R.FileName\") AS \"R.FileName\",\n -- PG.Quantity is constant per (protein-group, run) in Spectronaut output;\n -- max() collapses the precursor-level duplicates safely.\n max(TRY_CAST(\"PG.Quantity\" AS DOUBLE)) AS \"PG.Quantity\",\n -- Best precursor q-value backing this protein in this run.\n min(TRY_CAST(\"EG.Qvalue\" AS DOUBLE)) AS \"EG.Qvalue\"\n FROM read_csv(\n '__IN_PATH__',\n delim='\\t',\n header=true,\n sample_size=-1, -- scan everything for type inference; columns are messy\n ignore_errors=true, -- tolerate stray malformed lines in a 2.6 GB file\n nullstr=['', 'NaN', 'NA']\n )\n WHERE\n -- Mirror the parser's precursor-level filter: drop EG rows with q-value > 0.01.\n -- Non-numeric q-values (e.g. 'Profiled') pass — same as the TS parser.\n (TRY_CAST(\"EG.Qvalue\" AS DOUBLE) IS NULL OR TRY_CAST(\"EG.Qvalue\" AS DOUBLE) <= 0.01)\n -- Drop decoys / contaminants up front; parser does this too but it's cheaper here.\n AND \"PG.ProteinGroups\" IS NOT NULL\n AND \"PG.ProteinGroups\" NOT LIKE 'CON\\_\\_%' ESCAPE '\\'\n AND \"PG.ProteinGroups\" NOT LIKE 'REV\\_\\_%' ESCAPE '\\'\n GROUP BY \"PG.ProteinGroups\", \"R.Condition\", \"R.Replicate\"\n) TO '__OUT_PATH__' (FORMAT csv, DELIMITER '\\t', HEADER);\n\n-- Summary so we can sanity-check the collapse ratio.\nSELECT\n count(*) AS output_rows,\n count(DISTINCT \"PG.ProteinGroups\") AS proteins,\n count(DISTINCT (\"R.Condition\" || '_' || \"R.Replicate\")) AS samples,\n list(DISTINCT \"R.Condition\") AS conditions\nFROM read_csv('__OUT_PATH__', delim='\\t', header=true);\n".includes("max(TRY_CAST"),!0),(0,t.E3)('#!/usr/bin/env bash\n# Collapse a long-form Spectronaut Report into the protein-group × sample shape\n# the Proteomics package\'s parseSpectronautText parser consumes.\n#\n# This is the documented MANUAL FALLBACK for a Spectronaut report too large for\n# the in-browser streaming importer: run it locally, then import the small\n# aggregated .tsv it produces. It is also the D-04 equivalence oracle the Wave-0\n# golden test pins to (see files/demo/README.md).\n#\n# Run: tools/spectronaut-aggregate.sh <input.tsv> [output.tsv]\n#\n# Requires the `duckdb` CLI on PATH (v1.3.0 used to derive the committed golden).\n\nset -euo pipefail\n\nif [[ $# -lt 1 ]]; then\n echo "Usage: $0 <input.tsv> [output.tsv]" >&2\n exit 1\nfi\n\nIN="$1"\nOUT="${2:-${IN%.tsv}.aggregated.tsv}"\nSQL="$(dirname "$0")/spectronaut-aggregate.sql"\n\nif [[ ! -f "$IN" ]]; then\n echo "Input not found: $IN" >&2\n exit 1\nfi\n\necho "Aggregating: $IN"\necho "Output: $OUT"\n\n# Substitute paths into the SQL template. DuckDB\'s COPY ... TO doesn\'t accept\n# variables, so we materialize the SQL first. SQL single-quote escaping: double up\n# any embedded \' in the paths.\nIN_ESC="${IN//\\\'/\\\'\\\'}"\nOUT_ESC="${OUT//\\\'/\\\'\\\'}"\nTMP_SQL="$(mktemp -t spectronaut-aggregate.XXXXXX.sql)"\ntrap \'rm -f "$TMP_SQL"\' EXIT\nsed -e "s|__IN_PATH__|${IN_ESC}|g" -e "s|__OUT_PATH__|${OUT_ESC}|g" "$SQL" > "$TMP_SQL"\n\nduckdb < "$TMP_SQL"\n\necho\necho "Input size: $(du -h "$IN" | cut -f1)"\necho "Output size: $(du -h "$OUT" | cut -f1)"\n'.includes("spectronaut-aggregate.sql"),!0)})});var L=n(86);function F(e,t){return[t.join("\t"),...e.map(e=>e.join("\t"))].join("\n")}const I=["Comparison (group1/group2)","PG.ProteinGroups","PG.Genes","AVG Log2 Ratio","Qvalue","Pvalue"];function M(e,t,n,o,r,s){return[e,t,n,o,r,s]}function O(t){for(const n of t.viewers)if(n.type===e.VIEWER.FILTERS)return n;return null}function R(t={}){const{withDisplayName:n=!0,withSourceId:o=!0,withFlags:r=!0,withProteinId:a=!0,comparisons:i=["T1 / Control","T2 / Control","T1 / Control","T2 / Control"]}=t,l=[e.Column.fromStrings("Comparison (group1/group2)",i),e.Column.fromList("double","log2FC",Array.from({length:i.length},(e,t)=>t-1.5))];if(a){const t=e.Column.fromStrings("Primary Protein ID",i.map((e,t)=>`P${1e4+t}`));t.semType=s.iu.PROTEIN_ID,l.push(t)}if(n){const t=e.Column.fromStrings("Display Name",i.map((e,t)=>`Gene${t+1}`));t.semType=s.iu.DISPLAY_NAME,l.push(t)}if(o){const t=e.Column.fromStrings("Source ID",i.map((e,t)=>`ENSG${1e4+t}`));t.semType=s.iu.SOURCE_ID,l.push(t)}return r&&l.push(e.Column.fromBitSet("Flags",e.BitSet.create(i.length,e=>e%2==0))),e.DataFrame.fromColumns(l)}function G(e){return[["Comparison (group1/group2)","PG.ProteinGroups","PG.Genes","AVG Log2 Ratio","Qvalue","Pvalue"].join("\t"),...e.map(e=>e.join("\t"))].join("\n")}function k(t){for(const n of t.viewers)if(n.type===e.VIEWER.FILTERS)return!0;return!1}(0,t.L1)("SpectronautCandidates",()=>{(0,t.t6)("parses standard rows",async()=>{const e=F([M("Treatment / Control","P04637","TP53","2.5","1e-5","1e-6"),M("Treatment / Control","P38398","BRCA1","-2.3","1e-4","1e-5")],I),n=await(0,L.R)(e);(0,t.E3)(n.rowCount,2)}),(0,t.t6)("sets proteomics.source to spectronaut-candidates",async()=>{const e=F([M("A / B","P04637","TP53","2.5","1e-5","1e-6")],I),n=await(0,L.R)(e);(0,t.E3)(n.getTag("proteomics.source"),"spectronaut-candidates")}),(0,t.t6)("sets de_complete and de_method tags",async()=>{const e=F([M("A / B","P04637","TP53","2.5","1e-5","1e-6")],I),n=await(0,L.R)(e);(0,t.E3)(n.getTag("proteomics.de_complete"),"true"),(0,t.E3)(n.getTag("proteomics.de_method"),"spectronaut")}),(0,t.t6)("names contrast groups from the Comparison string (volcano legend)",async()=>{const e=F([M("DMT / WT","P04637","TP53","2.5","1e-5","1e-6"),M("DMT / WT","P38398","BRCA1","-2.3","1e-4","1e-5")],I),n=await(0,L.R)(e),o=(0,l.f)(n);(0,t.E3)(null!=o,!0);const r=[o.group1.name,o.group2.name].sort();(0,t.E3)(r[0],"DMT"),(0,t.E3)(r[1],"WT"),(0,t.E3)(o.group1.columns.length,0),(0,t.E3)(o.group2.columns.length,0)}),(0,t.t6)("renames AVG Log2 Ratio to log2FC",async()=>{const e=F([M("A / B","P04637","TP53","2.5","1e-5","1e-6")],I),n=await(0,L.R)(e);(0,t.E3)(null!==n.col("log2FC"),!0),(0,t.E3)(n.col("AVG Log2 Ratio"),null),(0,t.E3)(Math.abs(n.col("log2FC").get(0)-2.5)<.01,!0)}),(0,t.t6)("renames Qvalue to adj.p-value",async()=>{const e=F([M("A / B","P04637","TP53","2.5","0.001","0.0001")],I),n=await(0,L.R)(e);(0,t.E3)(null!==n.col("adj.p-value"),!0),(0,t.E3)(n.col("Qvalue"),null),(0,t.E3)(Math.abs(n.col("adj.p-value").get(0)-.001)<1e-6,!0)}),(0,t.t6)("renames Pvalue to p-value when present",async()=>{const e=F([M("A / B","P04637","TP53","2.5","0.001","0.0001")],I),n=await(0,L.R)(e);(0,t.E3)(null!==n.col("p-value"),!0),(0,t.E3)(n.col("Pvalue"),null)}),(0,t.t6)("works without a Pvalue column",async()=>{const e=F([["P04637","TP53","2.5","0.001"]],["PG.ProteinGroups","PG.Genes","AVG Log2 Ratio","Qvalue"]),n=await(0,L.R)(e);(0,t.E3)(n.rowCount,1),(0,t.E3)(n.col("p-value"),null),(0,t.E3)(null!==n.col("adj.p-value"),!0)}),(0,t.t6)("assigns canonical semantic types",async()=>{const e=F([M("A / B","P04637","TP53","2.5","0.001","0.0001")],I),n=await(0,L.R)(e);(0,t.E3)(n.col("PG.ProteinGroups").semType,s.iu.PROTEIN_ID),(0,t.E3)(n.col("PG.Genes").semType,s.iu.GENE_SYMBOL),(0,t.E3)(n.col("log2FC").semType,s.iu.LOG2FC),(0,t.E3)(n.col("adj.p-value").semType,s.iu.P_VALUE),(0,t.E3)(n.col("p-value").semType,s.iu.P_VALUE)}),(0,t.t6)("computes significant column from |log2FC| >= 1 and adj.p <= 0.05",async()=>{const e=F([M("A / B","P_sig_up","A","2.5","0.001","0.0001"),M("A / B","P_sig_down","B","-1.5","0.001","0.0001"),M("A / B","P_small_fc","C","0.3","0.001","0.0001"),M("A / B","P_big_qvalue","D","2.0","0.5","0.4"),M("A / B","P_just_inside","E","1.01","0.04","0.03")],I),n=(await(0,L.R)(e)).col("significant");(0,t.E3)(n.get(0),!0),(0,t.E3)(n.get(1),!0),(0,t.E3)(n.get(2),!1),(0,t.E3)(n.get(3),!1),(0,t.E3)(n.get(4),!0)}),(0,t.t6)("filters contam_ rows",async()=>{const e=F([M("A / B","P04637","TP53","2.5","0.001","0.0001"),M("A / B","contam_P99999","KRT1","0.1","0.5","0.4")],I),n=await(0,L.R)(e);(0,t.E3)(n.rowCount,1),(0,t.E3)(n.col("PG.ProteinGroups").get(0),"P04637")}),(0,t.t6)("filters rev_ decoy rows",async()=>{const e=F([M("A / B","P04637","TP53","2.5","0.001","0.0001"),M("A / B","rev_P12345","FAKE","0.1","0.5","0.4")],I),n=await(0,L.R)(e);(0,t.E3)(n.rowCount,1)}),(0,t.t6)("throws on missing protein-group column",async()=>{const e=F([["A / B","2.5","0.001"]],["Comparison","AVG Log2 Ratio","Qvalue"]);let n=!1;try{await(0,L.R)(e)}catch(e){n=!0,(0,t.E3)(String(e.message).includes("protein-group"),!0)}(0,t.E3)(n,!0)}),(0,t.t6)("throws on missing log2 ratio column",async()=>{const e=F([["P04637","TP53","0.001"]],["PG.ProteinGroups","PG.Genes","Qvalue"]);let n=!1;try{await(0,L.R)(e)}catch(e){n=!0,(0,t.E3)(String(e.message).includes("log2 ratio"),!0)}(0,t.E3)(n,!0)}),(0,t.t6)("throws on missing q-value column",async()=>{const e=F([["P04637","TP53","2.5"]],["PG.ProteinGroups","PG.Genes","AVG Log2 Ratio"]);let n=!1;try{await(0,L.R)(e)}catch(e){n=!0,(0,t.E3)(String(e.message).includes("q-value"),!0)}(0,t.E3)(n,!0)}),(0,t.t6)("accepts alternative column names (ProteinGroups, Log2 Ratio, Q-Value)",async()=>{const e=F([["P04637","TP53","2.5","0.001"]],["ProteinGroups","Genes","Log2 Ratio","Q-Value"]),n=await(0,L.R)(e);(0,t.E3)(n.rowCount,1),(0,t.E3)(null!==n.col("log2FC"),!0),(0,t.E3)(null!==n.col("adj.p-value"),!0)}),(0,t.t6)("keeps Comparison column for multi-comparison files",async()=>{const e=F([M("Treatment1 / Control","P04637","TP53","2.5","0.001","0.0001"),M("Treatment2 / Control","P04637","TP53","1.8","0.002","0.0005"),M("Treatment1 / Control","P38398","BRCA1","-2.3","0.001","0.0001")],I),n=await(0,L.R)(e);(0,t.E3)(n.rowCount,3),(0,t.E3)(null!==n.col("Comparison (group1/group2)"),!0)});const e=["Comparison (group1/group2)","PG.ProteinGroups","PG.Genes","AVG Log2 Ratio","Qvalue","Pvalue","AVG Group Quantity Numerator","AVG Group Quantity Denominator","Condition Numerator","Condition Denominator"];(0,t.t6)("flips reversed-comparison rows; canonical rows untouched",async()=>{const n=F([["DMD / WT","P1","G1","-2.0","0.001","0.0001","100","400","DMD","WT"],["WT / DMD","P2","G2","3.0","0.001","0.0001","800","100","WT","DMD"]],e),o=await(0,L.R)(n),r=o.col("Comparison (group1/group2)"),s=o.col("log2FC"),a=o.col("AVG Group Quantity Numerator"),i=o.col("AVG Group Quantity Denominator");(0,t.E3)(r.get(0),"DMD / WT"),(0,t.E3)(Math.abs(s.get(0)- -2)<1e-6,!0),(0,t.E3)(Math.abs(a.get(0)-100)<1e-4,!0),(0,t.E3)(Math.abs(i.get(0)-400)<1e-4,!0),(0,t.E3)(r.get(1),"DMD / WT"),(0,t.E3)(Math.abs(s.get(1)- -3)<1e-6,!0),(0,t.E3)(Math.abs(a.get(1)-100)<1e-4,!0),(0,t.E3)(Math.abs(i.get(1)-800)<1e-4,!0),(0,t.E3)(o.col("Condition Numerator").get(1),"DMD"),(0,t.E3)(o.col("Condition Denominator").get(1),"WT")}),(0,t.t6)("flips log2FC without AVG Group Quantity columns (no swap, no throw)",async()=>{const e=F([M("DMD / WT","P1","G1","-2.0","0.001","0.0001"),M("WT / DMD","P2","G2","3.0","0.001","0.0001")],I),n=await(0,L.R)(e),o=n.col("log2FC");(0,t.E3)(Math.abs(o.get(0)- -2)<1e-6,!0),(0,t.E3)(Math.abs(o.get(1)- -3)<1e-6,!0),(0,t.E3)(n.col("Comparison (group1/group2)").get(1),"DMD / WT"),(0,t.E3)(n.col("AVG Group Quantity Numerator"),null)}),(0,t.t6)("single-orientation file is not mirrored",async()=>{const e=F([M("Treatment / Control","P1","A","2.5","0.001","0.0001"),M("Treatment / Control","P2","B","-1.7","0.002","0.0005")],I),n=await(0,L.R)(e),o=n.col("log2FC");(0,t.E3)(Math.abs(o.get(0)-2.5)<1e-6,!0),(0,t.E3)(Math.abs(o.get(1)- -1.7)<1e-6,!0),(0,t.E3)(n.col("Comparison (group1/group2)").get(0),"Treatment / Control")}),(0,t.t6)("parses CSV when delimiter is comma",async()=>{const e=await(0,L.R)("PG.ProteinGroups,PG.Genes,AVG Log2 Ratio,Qvalue\nP04637,TP53,2.5,0.001\nP38398,BRCA1,-2.3,0.001");(0,t.E3)(e.rowCount,2),(0,t.E3)(null!==e.col("log2FC"),!0)}),(0,t.t6)("creates Primary Protein ID for semicolon-delimited IDs",async()=>{const e=F([M("A / B","P04637;Q9Y6R7","TP53","2.5","0.001","0.0001")],I),n=(await(0,L.R)(e)).col("Primary Protein ID");(0,t.E3)(null!==n,!0),(0,t.E3)(n.get(0),"P04637")})}),(0,t.L1)("Proteomics: 14-03",()=>{(0,t.t6)("filtersScopingNoFlags",async()=>{const e=R(),n=v.shell.addTableView(e);try{const o=(0,x.dockComparisonFilterIfMultiContrast)(n,e);(0,t.E3)(o,!0),(0,t.E3)(null!==O(n),!0)}finally{n.close()}}),(0,t.t6)("filtersScopingSingleContrast",async()=>{const e=R({comparisons:["T1 / Control","T1 / Control","T1 / Control"]}),n=v.shell.addTableView(e);try{const o=(0,x.dockComparisonFilterIfMultiContrast)(n,e);(0,t.E3)(o,!1),(0,t.E3)(O(n),null)}finally{n.close()}}),(0,t.t6)("filtersScopingFallbackToProteinIdWhenNoDisplayName",async()=>{const e=R({withDisplayName:!1,withSourceId:!1}),n=v.shell.addTableView(e);try{const o=(0,x.dockComparisonFilterIfMultiContrast)(n,e);(0,t.E3)(o,!0),(0,t.E3)(null!==O(n),!0)}finally{n.close()}})});const $=["Homo sapiens","Saccharomyces cerevisiae","Escherichia coli"];(0,t.L1)("SpectronautCandidates E2E",()=>{(0,t.t6)("parses HYE candidates fixture and reproduces expected DE signal",async()=>{const e=await je.files.readAsText("demo/spectronaut-hye-candidates.tsv"),n=await(0,L.R)(e);(0,t.E3)(n.rowCount,93),(0,t.E3)(n.getTag("proteomics.source"),"spectronaut-candidates"),(0,t.E3)(n.getTag("proteomics.de_complete"),"true"),(0,t.E3)(n.getTag("proteomics.de_method"),"spectronaut"),(0,t.E3)(null!==n.col("log2FC"),!0),(0,t.E3)(null!==n.col("adj.p-value"),!0),(0,t.E3)(null!==n.col("p-value"),!0),(0,t.E3)(null!==n.col("significant"),!0),(0,t.E3)(n.col("AVG Log2 Ratio"),null),(0,t.E3)(n.col("Qvalue"),null),(0,t.E3)(n.col("Pvalue"),null),(0,t.E3)(n.col("ProteinGroups").semType,s.iu.PROTEIN_ID),(0,t.E3)(n.col("log2FC").semType,s.iu.LOG2FC),(0,t.E3)(n.col("p-value").semType,s.iu.P_VALUE),(0,t.E3)(n.col("adj.p-value").semType,s.iu.P_VALUE);const o=n.col("log2FC"),r=n.col("significant");let a=0,i=0,l=0;for(let e=0;e<n.rowCount;e++)r.get(e)?o.get(e)>0?a++:i++:l++;(0,t.E3)(a,26),(0,t.E3)(i,17),(0,t.E3)(l,50);const c=n.col("Organisms"),u=new Set;for(let e=0;e<n.rowCount;e++){const t=c.get(e);"string"==typeof t&&u.add(t)}for(const e of $){const n=Array.from(u).some(t=>t.includes(e));(0,t.E3)(n,!0)}}),(0,t.t6)("multi-comparison file docks a Comparison Filters viewer",async()=>{const e=await(0,L.R)(G([["T1 / Control","P1","G1","2.0","0.001","0.0001"],["T2 / Control","P2","G2","-1.7","0.002","0.0005"],["T1 / Control","P3","G3","1.2","0.01","0.005"]])),n=v.shell.addTableView(e);try{const o=(0,x.dockComparisonFilterIfMultiContrast)(n,e);(0,t.E3)(o,!0),(0,t.E3)(k(n),!0)}finally{n.close()}}),(0,t.t6)("single-comparison file docks no Filters viewer",async()=>{const e=await(0,L.R)(G([["T1 / Control","P1","G1","2.0","0.001","0.0001"],["T1 / Control","P2","G2","-1.7","0.002","0.0005"]])),n=v.shell.addTableView(e);try{const o=(0,x.dockComparisonFilterIfMultiContrast)(n,e);(0,t.E3)(o,!1),(0,t.E3)(k(n),!1)}finally{n.close()}}),(0,t.t6)("candidates import auto-opens the volcano",async()=>{const n=await(0,L.R)(G([["T1 / Control","P1","G1","2.0","0.001","0.0001"],["T1 / Control","P2","G2","-1.7","0.002","0.0005"],["T1 / Control","P3","G3","0.1","0.9","0.8"]])),o=(0,x.openCandidatesAnalysisView)(n);try{let n=0,r=null;for(const t of o.viewers)t.type===e.VIEWER.SCATTER_PLOT&&(n++,r=t);(0,t.E3)(n,1),(0,t.E3)(r.props.xColumnName,"log2FC")}finally{o.close()}})});var B=n(119);function U(e,t){return[t.join("\t"),...e.map(e=>e.join("\t"))].join("\n")}const j=["Protein","Protein ID","Entry Name","Gene","Length","Organism","Protein Description","Sample1 Spectral Count","Sample1 Intensity","Sample1 MaxLFQ Intensity","Sample2 Spectral Count","Sample2 Intensity","Sample2 MaxLFQ Intensity"];function V(e,t,n,o,r,s){return[`sp|${e}|${t}_HUMAN`,e,`${t}_HUMAN`,t,"500","Homo sapiens",`${t} protein`,"12",n,o,"15",r,s]}(0,t.L1)("FragPipe",()=>{(0,t.t6)("parses standard rows",async()=>{const e=U([V("P12345","BRCA1","10000","12000","20000","24000"),V("Q67890","TP53","30000","36000","40000","48000")],j),n=await(0,B.p)(e);(0,t.E3)(n.rowCount,2)}),(0,t.t6)("filters contam_ rows",async()=>{const e=U([V("P12345","BRCA1","10000","12000","20000","24000"),V("contam_P99999","KRT1","30000","36000","40000","48000")],j),n=await(0,B.p)(e);(0,t.E3)(n.rowCount,1),(0,t.E3)(n.col("Protein ID").get(0),"P12345")}),(0,t.t6)("filters rev_ rows",async()=>{const e=U([V("P12345","BRCA1","10000","12000","20000","24000"),V("rev_P99999","DECOY","30000","36000","40000","48000")],j),n=await(0,B.p)(e);(0,t.E3)(n.rowCount,1)}),(0,t.t6)("filters CON__/REV__ rows for MaxQuant-style FASTAs",async()=>{const e=U([V("P12345","BRCA1","10000","12000","20000","24000"),V("CON__P99999","KRT1","30000","36000","40000","48000"),V("REV__P88888","FAKE1","50000","60000","70000","80000")],j),n=await(0,B.p)(e);(0,t.E3)(n.rowCount,1)}),(0,t.t6)("assigns semantic types",async()=>{const e=U([V("P12345","BRCA1","10000","12000","20000","24000")],j),n=await(0,B.p)(e);(0,t.E3)(n.col("Protein ID")?.semType,s.iu.PROTEIN_ID),(0,t.E3)(n.col("Gene")?.semType,s.iu.GENE_SYMBOL),(0,t.E3)(n.col("Sample1 MaxLFQ Intensity")?.semType,s.iu.INTENSITY)}),(0,t.t6)("prefers MaxLFQ for log2 transform",async()=>{const e=U([V("P12345","BRCA1","1024","2048","4096","8192")],j),n=await(0,B.p)(e);(0,t.E3)(null!==n.col("log2(Sample1 MaxLFQ Intensity)"),!0),(0,t.E3)(null!==n.col("log2(Sample2 MaxLFQ Intensity)"),!0),(0,t.E3)(n.col("log2(Sample1 Intensity)"),null);const o=n.col("log2(Sample1 MaxLFQ Intensity)");(0,t.E3)(Math.abs(o.get(0)-11)<.001,!0)}),(0,t.t6)("falls back to bare Intensity when no MaxLFQ present",async()=>{const e=U([["sp|P12345|BRCA1_HUMAN","P12345","BRCA1","12","1024","15","4096"]],["Protein","Protein ID","Gene","Sample1 Spectral Count","Sample1 Intensity","Sample2 Spectral Count","Sample2 Intensity"]),n=await(0,B.p)(e);(0,t.E3)(null!==n.col("log2(Sample1 Intensity)"),!0),(0,t.E3)(null!==n.col("log2(Sample2 Intensity)"),!0);const o=n.col("log2(Sample1 Intensity)");(0,t.E3)(Math.abs(o.get(0)-10)<.001,!0)}),(0,t.t6)("zero intensity produces FLOAT_NULL in log2",async()=>{const e=U([V("P12345","BRCA1","0","0","4096","8192")],j),n=(await(0,B.p)(e)).col("log2(Sample1 MaxLFQ Intensity)");(0,t.E3)(n.isNone(0),!0)}),(0,t.t6)("primary protein ID extracted from semicolon-delimited",async()=>{const e=U([["sp|P12345|BRCA1_HUMAN","P12345;Q67890","BRCA1_HUMAN","BRCA1;BRCA2","500","Homo sapiens","BRCA1 protein","12","10000","12000","15","20000","24000"]],j),n=await(0,B.p)(e),o=n.col("Primary Protein ID");(0,t.E3)(null!==o,!0),o&&(0,t.E3)(o.get(0),"P12345");const r=n.col("Primary Gene Name");(0,t.E3)(null!==r,!0),r&&(0,t.E3)(r.get(0),"BRCA1")}),(0,t.t6)("proteomics.source tag set to fragpipe",async()=>{const e=U([V("P12345","BRCA1","10000","12000","20000","24000")],j),n=await(0,B.p)(e);(0,t.E3)(n.getTag("proteomics.source"),"fragpipe")}),(0,t.t6)("intensity columns survive as raw plus log2 pair",async()=>{const e=U([V("P12345","BRCA1","10000","12000","20000","24000")],j),n=await(0,B.p)(e);(0,t.E3)(null!==n.col("Sample1 MaxLFQ Intensity"),!0),(0,t.E3)(null!==n.col("log2(Sample1 MaxLFQ Intensity)"),!0)})});const q={group1:{name:"Control",columns:["log2(Ctrl_1 MaxLFQ Intensity)","log2(Ctrl_2 MaxLFQ Intensity)"]},group2:{name:"Treatment",columns:["log2(Treat_1 MaxLFQ Intensity)","log2(Treat_2 MaxLFQ Intensity)"]}},Y=["TP53","AKT1","F2"],z=["BRCA1","PRKCD"],H=["EGFR","MTOR","HRAS"];(0,t.L1)("FragPipe E2E",()=>{(0,t.t6)("full pipeline (parse → normalize → impute → DE) on fragpipe-smoke-test.tsv",async()=>{const e=await je.files.readAsText("demo/fragpipe-smoke-test.tsv"),n=await(0,B.p)(e);(0,t.E3)(n.rowCount,8),(0,t.E3)(n.getTag("proteomics.source"),"fragpipe"),(0,t.E3)(n.col("Protein ID").semType,s.iu.PROTEIN_ID),(0,t.E3)(n.col("Gene").semType,s.iu.GENE_SYMBOL),(0,t.E3)(null!==n.col("log2(Ctrl_1 MaxLFQ Intensity)"),!0),(0,t.E3)(null!==n.col("log2(Treat_2 MaxLFQ Intensity)"),!0),(0,l.$Y)(n,q),(0,t.E3)(null!==n.getTag("proteomics.groups"),!0);const o=[...q.group1.columns,...q.group2.columns];(0,c.aj)(n,o),(0,t.E3)(n.getTag("proteomics.normalized"),"true");for(const e of o)(0,t.E3)(Math.abs(n.col(e).stats.med)<1e-4,!0);(0,u.Q2)(n,o),(0,t.E3)(n.getTag("proteomics.imputed"),"true"),(0,m.ps)(n,q.group1.columns,q.group2.columns,"Control","Treatment",1,.05),(0,t.E3)(n.getTag("proteomics.de_complete"),"true"),(0,t.E3)(null!==n.col("log2FC"),!0),(0,t.E3)(null!==n.col("p-value"),!0),(0,t.E3)(null!==n.col("adj.p-value"),!0),(0,t.E3)(null!==n.col("significant"),!0);const r={},a=n.col("Gene");for(let e=0;e<n.rowCount;e++)r[a.get(e)]=e;const i=n.col("log2FC"),p=n.col("significant");for(const e of Y)(0,t.E3)(i.get(r[e])>1,!0),(0,t.E3)(p.get(r[e]),!0);for(const e of z)(0,t.E3)(i.get(r[e])<-1,!0),(0,t.E3)(p.get(r[e]),!0);for(const e of H)(0,t.E3)(Math.abs(i.get(r[e]))<.5,!0),(0,t.E3)(p.get(r[e]),!1)})});var Q=n(623),W=n(70);function K(e){const t=v.dapi.userDataStorage.constructor.prototype,n=t.get,o=t.put;return e.get&&(t.get=e.get),e.put&&(t.put=e.put),()=>{t.get=n,t.put=o}}const J={Nucleus:"#FF6B6B",Cytoplasm:"#ECDC44",Mitochondria:"#45B7D1",ER:"#96CEB4",Golgi:"#FAAFFE","Plasma Membrane":"#DDA0DD",Lysosome:"#F39C12",Peroxisome:"#E17055",Ribosome:"#A29BFE",Extracellular:"#FD79A8",Vesicles:"#FDCB6E",Unknown:"#CCCCCC"};(0,t.L1)("SubcellularLocation",()=>{(0,t.t6)("SEMTYPE.SUBCELLULAR_LOCATION literal is stable",async()=>{(0,t.E3)(s.iu.SUBCELLULAR_LOCATION,"Proteomics-SubcellularLocation")}),(0,t.t6)("every ORGANISM_LIST code has an ORGANISM_TAXONOMY mapping",async()=>{for(const e of h.Ae)(0,t.E3)(typeof Q.JO[e.code],"number"),(0,t.E3)(Q.JO[e.code]>0,!0)}),(0,t.t6)("classifier: subcellular field used before GO fallback",async()=>{(0,t.E3)((0,Q.ZF)("Nucleus {ECO:0000269}.","mitochondrion [GO:0005739]"),"Nucleus")}),(0,t.t6)("classifier: GO used only when subcellular field has no match",async()=>{(0,t.E3)((0,Q.ZF)("","cytoplasm [GO:0005737]"),"Cytoplasm"),(0,t.E3)((0,Q.ZF)("phosphopyruvate hydratase complex","ribosome [GO:0005840]"),"Ribosome")}),(0,t.t6)("classifier: earliest character position wins across categories",async()=>{(0,t.E3)((0,Q.ZF)("Mitochondrion. Nucleus.",""),"Mitochondria"),(0,t.E3)((0,Q.ZF)("Nucleus. Mitochondrion.",""),"Nucleus")}),(0,t.t6)("classifier: ties broken by keyword-map insertion order (Nucleus before Cytoplasm)",async()=>{(0,t.E3)((0,Q.ZF)("nucleus",""),"Nucleus"),(0,t.E3)((0,Q.ZF)("cytoplasm",""),"Cytoplasm")}),(0,t.t6)("classifier: raw string not pre-stripped (matches inside SUBCELLULAR LOCATION: ... {ECO})",async()=>{(0,t.E3)((0,Q.ZF)("SUBCELLULAR LOCATION: Cytoplasm {ECO:0000269|PubMed:1234}. Nucleus {ECO:0000250}.",""),"Cytoplasm")}),(0,t.t6)("classifier: empty / no-match → Unknown",async()=>{(0,t.E3)((0,Q.ZF)("",""),"Unknown"),(0,t.E3)((0,Q.ZF)("some unrelated free text","nothing spatial here"),"Unknown")}),(0,t.t6)("LOCATION_COLORS: all 12 ARGB ints equal the locked hex conversion",async()=>{const e=Object.keys(J);(0,t.E3)(e.length,12);for(const n of e){const e=4278190080|parseInt(J[n].slice(1),16);(0,t.E3)(Q.Jn[n],e)}(0,t.E3)(Object.keys(Q.Jn).length,12)}),(0,t.t6)("mergeStreamTsv: header skipped, positional parse, reviewed beats unreviewed",async()=>{const e=["Entry\tSubcellular location [CC]\tGene Ontology (cellular component)\tReviewed\tGene Names (primary)","P1\tNucleus.\t\tunreviewed\tGENA","P1\tMitochondrion.\t\treviewed\tGENA","P2\t\t\tunreviewed\tGENB"].join("\n"),{locByAcc:n,geneByAcc:o}=(0,Q.y)(e);(0,t.E3)(n.get("P1"),"Mitochondria"),(0,t.E3)(n.get("P2"),"Unknown"),(0,t.E3)(o.get("P1"),"GENA"),(0,t.E3)(o.get("P2"),"GENB")}),(0,t.t6)("mergeStreamTsv: existing Unknown is overwritten by a later non-Unknown",async()=>{const e=["Entry\tSubcellular location [CC]\tGO\tReviewed\tGene","P9\t\t\tunreviewed\tG9","P9\tGolgi apparatus.\t\tunreviewed\tG9"].join("\n"),{locByAcc:n}=(0,Q.y)(e);(0,t.E3)(n.get("P9"),"Golgi")}),(0,t.t6)("runWithConcurrency caps in-flight tasks at the supplied limit",async()=>{let e=0,n=0;const o=new Array(20).fill(0).map((e,t)=>t);await(0,Q.Pd)(o,6,async()=>(e++,e>n&&(n=e),await new Promise(e=>setTimeout(e,5)),e--,null)),(0,t.E3)(n<=6,!0,"concurrentMax should be ≤ 6"),(0,t.E3)(n>=2,!0,"should have observed parallel execution")}),(0,t.t6)("getSubcellularLocations emits non-decreasing progress per phase",async()=>{const e=v.dapi.fetchProxy;v.dapi.fetchProxy=async e=>{const t=/accession%3A([A-Z0-9]+)/.exec(e),n=t?t[1]:"P00000";return{ok:!0,status:200,text:async()=>(e=>`Entry\tSubcellular location [CC]\tGO\tReviewed\tGene Names (primary)\n${e}\tNucleus.\t\treviewed\tGENE1\n`)(n)}};const n=K({get:async()=>({}),put:async()=>{}});try{const e=[];for(let t=0;t<250;t++)e.push(`TESTB${String(t).padStart(5,"0")}`);const n=[],o=(e,t,o)=>n.push({done:e,total:t,phase:o});await(0,Q.n0)(e,"hsapiens",o);const r=n.filter(e=>"fetch-acc"===e.phase);(0,t.E3)(r.length,3),(0,t.E3)(r[0].total,3);for(let e=1;e<r.length;e++)(0,t.E3)(r[e].done>=r[e-1].done,!0,"fetch-acc done should be non-decreasing");const s=r[r.length-1];(0,t.E3)(s.done,s.total,"last fetch-acc tuple should have done === total")}finally{v.dapi.fetchProxy=e,n()}}),(0,t.t6)("getSubcellularLocations writes the cache incrementally during fetch",async()=>{const e=v.dapi.fetchProxy;let n=0;v.dapi.fetchProxy=async e=>{const t=0===n++?1e3:6e3;await new Promise(e=>setTimeout(e,t));const o=/accession%3A([A-Z0-9]+)/.exec(e),r=o?o[1]:"P00000";return{ok:!0,status:200,text:async()=>(e=>`Entry\tSubcellular location [CC]\tGO\tReviewed\tGene Names (primary)\n${e}\tNucleus.\t\treviewed\tGENE1\n`)(r)}};let o=0;const r=K({get:async()=>({}),put:async()=>{o++}});try{const e=[];for(let t=0;t<150;t++)e.push(`TESTC${String(t).padStart(5,"0")}`);await(0,Q.n0)(e,"hsapiens"),(0,t.E3)(o>=2,!0,`userDataStorage.put should be called >= 2 times (got ${o})`)}finally{v.dapi.fetchProxy=e,r()}},{timeout:3e4}),(0,t.t6)("STORE export matches the documented userDataStorage key",async()=>{(0,t.E3)(Q.er,"proteomics-subcell-loc")}),(0,t.t6)("ensureLocationColumn short-circuits on accession-set hash match",async()=>{const n=v.dapi.fetchProxy;let o=0;v.dapi.fetchProxy=async e=>{o++;const t=/accession%3A([A-Z0-9]+)/.exec(e),n=t?t[1]:"TESTD00";return{ok:!0,status:200,text:async()=>(e=>`Entry\tSubcellular location [CC]\tGO\tReviewed\tGene Names (primary)\n${e}\tNucleus.\t\treviewed\tGENE1\n`)(n)}};const r=K({get:async()=>({}),put:async()=>{}});try{const n=e.Column.fromStrings("Primary Protein ID",["TESTD01","TESTD02","TESTD03","TESTD04","TESTD05"]);n.semType=s.iu.PROTEIN_ID;const r=e.DataFrame.fromColumns([n]);await(0,W.MC)(r);const a=o;(0,t.E3)(a>=1,!0,"first call should fetch from UniProt"),await(0,W.MC)(r),(0,t.E3)(o,a,"second call on same accession set should short-circuit (no new fetch)"),n.set(0,"TESTD99"),await(0,W.MC)(r),(0,t.E3)(o>a,!0,"third call with mutated accession should fetch again")}finally{v.dapi.fetchProxy=n,r()}}),(0,t.t6)("ensureLocationColumn forwards progress through fetch + emits init-column",async()=>{const n=v.dapi.fetchProxy;v.dapi.fetchProxy=async e=>{const t=/accession%3A([A-Z0-9]+)/.exec(e),n=t?t[1]:"TESTE00";return{ok:!0,status:200,text:async()=>(e=>`Entry\tSubcellular location [CC]\tGO\tReviewed\tGene Names (primary)\n${e}\tNucleus.\t\treviewed\tGENE1\n`)(n)}};const o=K({get:async()=>({}),put:async()=>{}});try{const n=e.Column.fromStrings("Primary Protein ID",["TESTE01","TESTE02","TESTE03"]);n.semType=s.iu.PROTEIN_ID;const o=e.DataFrame.fromColumns([n]),r=[],a=(e,t,n)=>r.push(n);await(0,W.MC)(o,a),(0,t.E3)(r.includes("fetch-acc"),!0,"progress should fire at least once with phase=fetch-acc"),(0,t.E3)(r.includes("init-column"),!0,"progress should fire with phase=init-column after bulk-init"),(0,t.E3)(r[r.length-1],"init-column","init-column should be the final progress phase")}finally{v.dapi.fetchProxy=n,o()}})});var Z=n(935);function X(t,n){return e.DataFrame.fromColumns([e.Column.fromStrings(t,n)])}(0,t.L1)("Organisms",()=>{(0,t.t6)("resolveOrganismCode maps scientific names (incl. strain-qualified) to codes",async()=>{(0,t.E3)((0,Z.qj)("Homo sapiens"),"hsapiens"),(0,t.E3)((0,Z.qj)("Rattus norvegicus"),"rnorvegicus"),(0,t.E3)((0,Z.qj)("Escherichia coli (strain K12)"),"ecoli"),(0,t.E3)((0,Z.qj)("Saccharomyces cerevisiae (strain ATCC 204508 / S288c)"),"scerevisiae")}),(0,t.t6)("resolveOrganismCode returns undefined for unsupported / empty",async()=>{(0,t.E3)(void 0===(0,Z.qj)("Sus scrofa"),!0),(0,t.E3)(void 0===(0,Z.qj)(""),!0),(0,t.E3)(void 0===(0,Z.qj)(null),!0),(0,t.E3)(void 0===(0,Z.qj)(void 0),!0)}),(0,t.t6)("every ORGANISM_LIST display resolves back to its own code",async()=>{for(const e of Z.Ae)(0,t.E3)((0,Z.qj)(e.display),e.code)}),(0,t.t6)("detectOrganismCode: single-species PG.Organisms column → that code",async()=>{const e=X("PG.Organisms",["Rattus norvegicus","Rattus norvegicus","Rattus norvegicus"]);(0,t.E3)((0,Z.Vr)(e),"rnorvegicus")}),(0,t.t6)('detectOrganismCode: works on a generically named "Organism" column',async()=>{const e=X("Organism",["Homo sapiens","Homo sapiens"]);(0,t.E3)((0,Z.Vr)(e),"hsapiens")}),(0,t.t6)("detectOrganismCode: mixed empties/unknowns but one species → that code",async()=>{const e=X("PG.Organisms",["","Homo sapiens","Sus scrofa",""]);(0,t.E3)((0,Z.Vr)(e),"hsapiens")}),(0,t.t6)("detectOrganismCode: multi-species (HYE-style mix) → undefined (do not guess)",async()=>{const e=X("PG.Organisms",["Homo sapiens","Escherichia coli (strain K12)","Saccharomyces cerevisiae"]);(0,t.E3)(void 0===(0,Z.Vr)(e),!0)}),(0,t.t6)("detectOrganismCode: no organism column → undefined",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Gene",["CDK1","CCNB1"])]);(0,t.E3)(void 0===(0,Z.Vr)(n),!0)})});var ee=n(871);function te(){const t=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["P1","P2","P3"]),e.Column.fromFloat32Array("Intensity_S1",new Float32Array([1e3,4e3,16e3])),e.Column.fromFloat32Array("Intensity_S2",new Float32Array([2e3,8e3,32e3]))]);return t.col("Protein ID").semType=s.iu.PROTEIN_ID,t.col("Intensity_S1").semType=s.iu.INTENSITY,t.col("Intensity_S2").semType=s.iu.INTENSITY,t}function ne(t=100){const n=new Float32Array(t),o=new Float32Array(t);for(let e=0;e<t;e++)n[e]=.1*(e-t/2),o[e]=.001+e/t*.5;const r=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",Array.from({length:t},(e,t)=>`P${t}`)),e.Column.fromFloat32Array("log2FC",n),e.Column.fromFloat32Array("adj.p-value",o)]);return r.col("Protein ID").semType=s.iu.PROTEIN_ID,r.col("log2FC").semType=s.iu.LOG2FC,r.col("adj.p-value").semType=s.iu.P_VALUE,r}(0,t.L1)("Log2 Scale",()=>{(0,t.t6)("getIntensityOriginals: only the pristine (non-log2) intensity columns",async()=>{const e=te();(0,d.Kh)(e,["Intensity_S1","Intensity_S2"]);const n=(0,ee.ye)(e);(0,t.E3)(n.length,2,"two originals"),(0,t.E3)(n.includes("Intensity_S1")&&n.includes("Intensity_S2"),!0,"includes both raw columns"),(0,t.E3)(n.some(e=>e.startsWith("log2(")),!1,"excludes the log2 copies")}),(0,t.t6)("detectCurrentLog2Applied: transform vs copy is read from the values",async()=>{const e=te();(0,d.Kh)(e,["Intensity_S1","Intensity_S2"]),(0,t.E3)((0,ee.IZ)(e,(0,ee.ye)(e)),"transform","log2(x) columns read as transform");const n=te();(0,d.l3)(n,["Intensity_S1","Intensity_S2"]),(0,t.E3)((0,ee.IZ)(n,(0,ee.ye)(n)),"copy","copied columns read as copy")}),(0,t.t6)("applyLog2Scale: transform→copy rebuilds values, clears stale tags, is idempotent",async()=>{const e=te();(0,d.Kh)(e,["Intensity_S1","Intensity_S2"]),e.setTag("proteomics.normalized","true"),e.setTag("proteomics.de_complete","true"),e.setTag("proteomics.de_method","t-test"),(0,t.E3)(Math.abs(e.col("log2(Intensity_S1)").get(0)-Math.log2(1e3))<.001,!0,"starts transformed");const n=(0,ee.DA)(e,!0);(0,t.E3)(n,!0,"a real scale change returns true"),(0,t.E3)(e.col("log2(Intensity_S1)").get(0),1e3,"value is now the raw copy"),(0,t.E3)((0,ee.IZ)(e,(0,ee.ye)(e)),"copy","now reads as copy"),(0,t.E3)(e.getTag("proteomics.normalized")||"","","normalized tag cleared"),(0,t.E3)(e.getTag("proteomics.de_complete")||"","","de_complete tag cleared"),(0,t.E3)(e.getTag("proteomics.de_method")||"","","de_method tag cleared"),(0,t.E3)((0,ee.ye)(e).length,2,"still exactly two originals"),(0,t.E3)((0,ee.DA)(e,!0),!1,"no-op when scale already matches returns false")}),(0,t.t6)("applyLog2Scale: copy→transform restores the log2 transform",async()=>{const e=te();(0,d.l3)(e,["Intensity_S1","Intensity_S2"]);const n=(0,ee.DA)(e,!1);(0,t.E3)(n,!0,"scale change returns true"),(0,t.E3)(Math.abs(e.col("log2(Intensity_S2)").get(2)-Math.log2(32e3))<.001,!0,"transform re-applied to raw value"),(0,t.E3)((0,ee.IZ)(e,(0,ee.ye)(e)),"transform","reads as transform")}),(0,t.t6)("getIntensityOriginals: empty when no intensity columns",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["P1","P2"])]);n.col("Protein ID").semType=s.iu.PROTEIN_ID,(0,t.E3)((0,ee.ye)(n).length,0,"no originals"),(0,t.E3)((0,ee.DA)(n,!0),!1,"applyLog2Scale is a no-op with nothing to rescale")})});const oe="Enriched in group1",re="Enriched in group2",se="Not significant";function ae(t){const n=[e.Column.fromStrings("Protein ID",["P1","P2","P3"]),e.Column.fromFloat32Array("log2FC",new Float32Array([2,-2,.1])),e.Column.fromFloat32Array("adj.p-value",new Float32Array([.001,.5,.2]))];!1!==t?.withPValue&&n.push(e.Column.fromFloat32Array("p-value",new Float32Array([.04,.001,.2])));const o=e.DataFrame.fromColumns(n);return o.col("log2FC").semType=s.iu.LOG2FC,o.col("adj.p-value").semType=s.iu.P_VALUE,o.col("Protein ID").semType=s.iu.PROTEIN_ID,o}(0,t.L1)("Volcano",()=>{(0,t.t6)("ensureNegLog10Column: stable name, values re-init in place on metric toggle",async()=>{const e=ae(),n=(0,W.CK)(e,"adj.p-value"),o=e.columns.length,r=e.col(n).get(0),s=(0,W.CK)(e,"p-value");(0,t.E3)(n,s),(0,t.E3)(e.columns.length,o);const a=e.col(s).get(0);(0,t.E3)(Math.abs(r-3)<1e-4,!0),(0,t.E3)(Math.abs(a- -Math.log10(.04))<1e-4,!0),(0,t.E3)(Math.abs(r-a)>1,!0)}),(0,t.t6)("ensureDirectionColumn: parameterized by metric, in-place, ARGB map",async()=>{const e=ae(),n=(0,W.EO)(e,1,.05,"adj.p-value"),o=e.columns.length;(0,t.E3)(e.col(n).get(0),oe),(0,t.E3)(e.col(n).get(1),se),(0,W.EO)(e,1,.05,"p-value"),(0,t.E3)(e.columns.length,o),(0,t.E3)(e.col(n).get(0),oe),(0,t.E3)(e.col(n).get(1),re)}),(0,t.t6)("p-value metric guarded when column absent — stays on adj.p-value",async()=>{const e=ae({withPValue:!1}),n=(0,W.CK)(e,"p-value");(0,t.E3)(Math.abs(e.col(n).get(0)-3)<1e-4,!0);const o=(0,W.EO)(e,1,.05,"p-value");(0,t.E3)(e.col(o).get(0),oe)}),(0,t.t6)("ensureLocationColumn: SEMTYPE + locked LOCATION_COLORS, no network needed",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["","",""]),e.Column.fromFloat32Array("log2FC",new Float32Array([1,2,3])),e.Column.fromFloat32Array("adj.p-value",new Float32Array([.1,.2,.3]))]);n.col("Protein ID").semType=s.iu.PROTEIN_ID;const o=await(0,W.MC)(n),r=n.col(o);(0,t.E3)(r.semType,s.iu.SUBCELLULAR_LOCATION),(0,t.E3)(r.get(0),"Unknown"),(0,t.E3)(Object.keys(Q.Jn).length,12)}),(0,t.t6)("createVolcanoPlot: axis-chip-hiding stylesheet + marker class (custom labels are sole titles)",async()=>{const e=ae(),n=(0,W.gO)(e,{topNLabels:0});(0,t.E3)(n.root.classList.contains("proteomics-volcano"),!0,"volcano marker class set");const o=document.getElementById("proteomics-volcano-styles");(0,t.E3)(null!==o,!0,"scoped stylesheet injected"),(0,t.E3)(o.textContent.includes(".d4-vertical")&&o.textContent.includes(".d4-bottom-center"),!0,"hides both axis chips"),(0,t.E3)(o.textContent.includes(".proteomics-volcano"),!0,"rule is scoped"),(0,t.E3)(o.textContent.includes(".d4-vertical-right"),!1,"color selector preserved")}),(0,t.t6)("recomputeVolcano: Y, class, threshold lines stay consistent across Q↔P toggle",async()=>{const e=ae(),n=(0,W.gO)(e,{fcThreshold:1,pThreshold:.05}),o=n.props.yColumnName;await(0,W.nj)(e,n,"p-value","significance",1,.05),(0,t.E3)(n.props.yColumnName,o),(0,t.E3)(n.props.colorColumnName,"direction"),(0,t.E3)(Math.abs(e.col(o).get(1)- -Math.log10(.001))<1e-4,!0),(0,t.E3)(e.col("direction").get(1),re);const r=e.meta.formulaLines.items.length;await(0,W.nj)(e,n,"adj.p-value","significance",1,.05),(0,t.E3)(Math.abs(e.col(o).get(1)- -Math.log10(.5))<1e-4,!0),(0,t.E3)(e.col("direction").get(1),se),(0,t.E3)(e.meta.formulaLines.items.length,r)}),(0,t.t6)("toggle wiring: every metric × colorDim combination drives recomputeVolcano",async()=>{const e=ae(),n=(0,W.gO)(e,{}),o=n.props.yColumnName;for(const r of["adj.p-value","p-value"])for(const s of["significance","location"])await(0,W.nj)(e,n,r,s,1,.05),(0,t.E3)(n.props.yColumnName,o),(0,t.E3)(n.props.colorColumnName,"location"===s?"Subcellular Location":"direction")}),(0,t.t6)("recomputeVolcano: location color dim sets the Subcellular Location column",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["",""]),e.Column.fromFloat32Array("log2FC",new Float32Array([1,-1])),e.Column.fromFloat32Array("adj.p-value",new Float32Array([.01,.9]))]);n.col("Protein ID").semType=s.iu.PROTEIN_ID;const o=(0,W.gO)(n,{});await(0,W.nj)(n,o,"adj.p-value","location",1,.05),(0,t.E3)(o.props.colorColumnName,"Subcellular Location"),(0,t.E3)(n.col("Subcellular Location").semType,s.iu.SUBCELLULAR_LOCATION)}),(0,t.t6)("showVolcanoBusy attaches overlay, updateVolcanoBusy mutates, hideVolcanoBusy detaches",async()=>{const e=ae(),n=(0,W.gO)(e,{topNLabels:0});try{(0,t.E3)(null==n.root.querySelector("[data-volcano-busy]"),!0,"overlay should not exist before showVolcanoBusy"),(0,W.DI)(n,"Classifying subcellular locations…");const e=n.root.querySelector("[data-volcano-busy]");(0,t.E3)(null!=e,!0,"overlay should attach"),(0,t.E3)((e.textContent??"").includes("Classifying"),!0,"overlay should show the initial label"),(0,W.Bb)(n,"Fetching subcellular locations","15/80 chunks");const o=n.root.querySelector("[data-volcano-busy]").textContent??"";(0,t.E3)(o.includes("Fetching"),!0,"label should update"),(0,t.E3)(o.includes("15/80"),!0,"detail should update"),(0,W.kX)(n),(0,t.E3)(null==n.root.querySelector("[data-volcano-busy]"),!0,"overlay should be removed after hideVolcanoBusy")}finally{n.root.querySelectorAll("[data-volcano-busy], [data-volcano-counter], [data-volcano-axis-x], [data-volcano-axis-y]").forEach(e=>e.remove())}}),(0,t.t6)("ensureLocationColumn short-circuits warm-cache path within one tick",async()=>{const n=e.Column.fromStrings("Primary Protein ID",["P12345","P67890","P11111"]);n.semType=s.iu.PROTEIN_ID;const o=e.DataFrame.fromColumns([n,e.Column.fromFloat32Array("log2FC",new Float32Array([1.5,-2,.5])),e.Column.fromFloat32Array("adj.p-value",new Float32Array([.001,.01,.5]))]),r=function(e){const t=v.dapi.userDataStorage.constructor.prototype,n=t.get,o=t.put;return e.get&&(t.get=e.get),e.put&&(t.put=e.put),()=>{t.get=n,t.put=o}}({get:async()=>({P12345:"Cytoplasm",P67890:"Nucleus",P11111:"Membrane",__schema_v:"13-04-1"}),put:async()=>{}});try{const e=[],n=(t,n,o)=>{e.push(`${o}:${t}/${n}`)};await(0,W.MC)(o,n);const r=o.col("Subcellular Location")?.getTag("proteomics.location_acc_hash");(0,t.E3)(null!=r&&r.length>0,!0,"hash tag should be set after first ensureLocationColumn call"),e.length=0;const s=performance.now();await(0,W.MC)(o,n);const a=performance.now()-s;(0,t.E3)(a<50,!0,`short-circuit path should complete in <50ms; took ${a}ms`),(0,t.E3)(1===e.length&&"init-column:1/1"===e[0],!0,`short-circuit should emit exactly one init-column tick; got ${JSON.stringify(e)}`)}finally{r()}}),(0,t.t6)("axis-max override: set/get round-trips, pins symmetric X + 0-based Y, empty clears",async()=>{const e=ae(),n=(0,W.gO)(e,{topNLabels:0});(0,t.E3)(null===(0,W.GE)(e).xMax,!0,"xMax defaults to null"),(0,t.E3)(null===(0,W.GE)(e).yMax,!0,"yMax defaults to null"),(0,W.S6)(e,5,8);const o=(0,W.GE)(e);(0,t.E3)(o.xMax,5,"xMax round-trips"),(0,t.E3)(o.yMax,8,"yMax round-trips"),(0,W.f0)(n,e),(0,t.E3)(n.props.xMin,-5,"X pins symmetric: xMin = -xMax"),(0,t.E3)(n.props.xMax,5,"X pins symmetric: xMax"),(0,t.E3)(n.props.yMin,0,"Y pins from 0"),(0,t.E3)(n.props.yMax,8,"Y pins to yMax"),(0,W.S6)(e,null,null),(0,t.E3)(null===(0,W.GE)(e).xMax,!0,"xMax cleared"),(0,t.E3)(null===(0,W.GE)(e).yMax,!0,"yMax cleared"),(0,W.f0)(n,e),(0,t.E3)(Number.isFinite(n.props.xMax)&&n.props.xMax>=2&&n.props.xMax<3,!0,`X resets to a finite fit-to-data bound; got ${n.props.xMax}`),(0,t.E3)(Number.isFinite(n.props.xMin)&&n.props.xMin<=-2&&n.props.xMin>-3,!0,`X min resets symmetric-ish to data; got ${n.props.xMin}`),(0,t.E3)(n.props.yMin,0,"Y still starts at 0 after reset"),(0,t.E3)(Number.isFinite(n.props.yMax),!0,"Y max resets to a finite bound"),(0,W.S6)(e,-3,0),(0,t.E3)(null===(0,W.GE)(e).xMax,!0,"negative xMax rejected"),(0,t.E3)(null===(0,W.GE)(e).yMax,!0,"zero yMax rejected")}),(0,t.t6)("axis-max override: survives a metric recompute (tag-based state)",async()=>{const e=ae({withPValue:!0});(0,l.$Y)(e,{group1:{name:"A",columns:[]},group2:{name:"B",columns:[]}});const n=(0,W.gO)(e,{topNLabels:0});(0,W.S6)(e,4,6),await(0,W.nj)(e,n,"p-value","significance",1,.05),(0,t.E3)(n.props.xMin,-4,"X still pinned after recompute"),(0,t.E3)(n.props.xMax,4,"X still pinned after recompute"),(0,t.E3)(n.props.yMax,6,"Y still pinned after recompute")})}),(0,t.L1)("Proteomics: 14-02",()=>{(0,t.t6)("volcanoDirectionStrings: categories derive from proteomics.groups tag",async()=>{const e=ae();(0,l.$Y)(e,{group1:{name:"DMD",columns:[]},group2:{name:"WT",columns:[]}});const n=(0,W.EO)(e,1,.05,"adj.p-value"),o=e.col(n).categories;(0,t.E3)(e.col(n).get(0),"Enriched in DMD"),(0,W.EO)(e,1,.05,"p-value"),(0,t.E3)(e.col(n).get(1),"Enriched in WT"),(0,t.E3)(e.col(n).get(2),"Not significant");for(const e of["up","down","not significant"])(0,t.E3)(o.includes(e),!1)}),(0,t.t6)('volcanoDirectionStringsFallback: no groups → "Enriched in group1/group2" + "Not significant"',async()=>{const e=ae(),n=(0,W.EO)(e,1,.05,"adj.p-value");(0,t.E3)(e.col(n).get(0),"Enriched in group1"),(0,W.EO)(e,1,.05,"p-value"),(0,t.E3)(e.col(n).get(1),"Enriched in group2"),(0,t.E3)(e.col(n).get(2),"Not significant")}),(0,t.t6)("volcanoDirectionColors: categorical color map carries exact ARGB ints",async()=>{const n=ae();(0,l.$Y)(n,{group1:{name:"DMD",columns:[]},group2:{name:"WT",columns:[]}});const o=(0,W.EO)(n,1,.05,"adj.p-value"),r=n.col(o).getTag(e.TAGS.COLOR_CODING_CATEGORICAL);(0,t.E3)(null!=r,!0);const s=JSON.parse(r);(0,t.E3)(s["Enriched in DMD"],W.PL.enrichedG1),(0,t.E3)(s["Enriched in WT"],W.PL.enrichedG2),(0,t.E3)(s["Not significant"],W.PL.notSig),(0,t.E3)(W.PL.enrichedG1,4294902015),(0,t.E3)(W.PL.enrichedG2,4278255615),(0,t.E3)(W.PL.notSig,4289374890)}),(0,t.t6)('volcanoTitle: synthesizes "Volcano Plot: g1 vs g2" from proteomics.groups',async()=>{const e=ae();(0,l.$Y)(e,{group1:{name:"DMD",columns:[]},group2:{name:"WT",columns:[]}});const n=(0,W.gO)(e,{topNLabels:0}).getOptions();(0,t.E3)(n.look.title,"Volcano Plot: DMD vs WT")}),(0,t.t6)('volcanoTitleFallback: no groups → "Volcano Plot"',async()=>{const e=ae(),n=(0,W.gO)(e,{topNLabels:0}).getOptions();(0,t.E3)(n.look.title,"Volcano Plot")}),(0,t.t6)("volcanoAxisLabels: X invariant; Y rewrites live on metric toggle",async()=>{const e=ae(),n=(0,W.gO)(e,{topNLabels:0}),o=n.root.querySelector("[data-volcano-axis-x]");(0,t.E3)(null!=o,!0),(0,t.E3)(o.textContent,"Log2 Fold Change");let r=n.root.querySelector("[data-volcano-axis-y]");(0,t.E3)(null!=r,!0),(0,t.E3)(r.textContent,"-Log10(Q-value)"),await(0,W.nj)(e,n,"p-value","significance",1,.05),r=n.root.querySelector("[data-volcano-axis-y]"),(0,t.E3)(r.textContent,"-Log10(p-value)"),await(0,W.nj)(e,n,"adj.p-value","significance",1,.05),r=n.root.querySelector("[data-volcano-axis-y]"),(0,t.E3)(r.textContent,"-Log10(Q-value)")}),(0,t.t6)("volcanoTopN: applyTopNLabels labels top-15 via the label column, not selection",async()=>{const e=ne(100),n=e.columns.addNewString("Gene name");n.init(e=>`G${e}`),n.semType=s.iu.GENE_SYMBOL;const o=(0,W.gO)(e,{topNLabels:0});(0,t.E3)(e.selection.trueCount,0);const r=e.col(W.bX);let a=0;for(let t=0;t<e.rowCount;t++)r.get(t).length>0&&a++;(0,t.E3)(a,0),(0,W.XC)(e,o,15),(0,t.E3)(e.selection.trueCount,0);const i=e.col(W.bX);for(let e=0;e<15;e++)(0,t.E3)(i.get(e).length>0,!0);for(let e=15;e<100;e++)(0,t.E3)(i.get(e).length,0);(0,t.E3)(o.props.labelColumnNames.includes(W.bX),!0)}),(0,t.t6)("volcanoLabelBindsToDisplayName: label text prefers DISPLAY_NAME over Gene name",async()=>{const e=ae(),n=e.columns.addNewString("Display Name");n.init(e=>`D${e}`),n.semType=s.iu.DISPLAY_NAME;const o=e.columns.addNewString("Gene name");o.init(e=>`G${e}`),o.semType=s.iu.GENE_SYMBOL;const r=(0,W.gO)(e);(0,t.E3)(r.props.labelColumnNames.includes(W.bX),!0);const a=e.col(W.bX);let i=0;for(let n=0;n<e.rowCount;n++){const e=a.get(n);e.length>0&&(i++,(0,t.E3)(e.startsWith("D"),!0))}(0,t.E3)(i>0,!0)}),(0,t.t6)("volcanoLabelFallbackToGeneName: no Display Name → label text uses Gene name",async()=>{const e=ae(),n=e.columns.addNewString("Gene name");n.init(e=>`G${e}`),n.semType=s.iu.GENE_SYMBOL;const o=(0,W.gO)(e);(0,t.E3)(o.props.labelColumnNames.includes(W.bX),!0);const r=e.col(W.bX);let a=0;for(let n=0;n<e.rowCount;n++){const e=r.get(n);e.length>0&&(a++,(0,t.E3)(e.startsWith("G"),!0))}(0,t.E3)(a>0,!0)}),(0,t.t6)("applyTopNLabelsExtraRows: labels top-N plus extra (search) rows; selection untouched",async()=>{const e=ne(50),n=e.columns.addNewString("Gene name");n.init(e=>`G${e}`),n.semType=s.iu.GENE_SYMBOL;const o=(0,W.gO)(e,{topNLabels:0});(0,W.XC)(e,o,5);const r=e.col(W.bX);for(let e=0;e<5;e++)(0,t.E3)(r.get(e).length>0,!0);(0,W.XC)(e,o,5,[40,41,42]);for(let e=0;e<5;e++)(0,t.E3)(r.get(e).length>0,!0);for(const e of[40,41,42])(0,t.E3)(r.get(e).length>0,!0);(0,t.E3)(e.selection.trueCount,0)}),(0,t.t6)("volcanoMetricTagPersistsViaRecompute: recomputeVolcano writes proteomics.volcano_metric",async()=>{const e=ae(),n=(0,W.gO)(e,{topNLabels:0});(0,t.E3)(e.getTag(W.j9),"adj.p-value"),await(0,W.nj)(e,n,"p-value","significance",1,.05),(0,t.E3)(e.getTag(W.j9),"p-value"),await(0,W.nj)(e,n,"adj.p-value","location",1,.05),(0,t.E3)(e.getTag(W.j9),"adj.p-value")}),(0,t.t6)("volcanoCounterRenders: heading + Total + per-direction rows",async()=>{const n=new Float32Array([3,2,-3,-2,.1,.5]),o=new Float32Array([.001,.01,.001,.01,.5,.3]),r=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["P0","P1","P2","P3","P4","P5"]),e.Column.fromFloat32Array("log2FC",n),e.Column.fromFloat32Array("adj.p-value",o)]);r.col("Protein ID").semType=s.iu.PROTEIN_ID,r.col("log2FC").semType=s.iu.LOG2FC,r.col("adj.p-value").semType=s.iu.P_VALUE,(0,l.$Y)(r,{group1:{name:"DMD",columns:[]},group2:{name:"WT",columns:[]}});const a=(0,W.gO)(r,{topNLabels:0}),i=()=>a.root.querySelector("[data-volcano-counter]")?.textContent??"";await(0,t.bk)(()=>i().includes("Visible Proteins"),"volcano counter overlay never rendered",3e3);const c=i();(0,t.E3)(c.includes(`Total: ${r.filter.trueCount.toLocaleString()}`),!0),(0,t.E3)(c.includes("Enriched in DMD"),!0),(0,t.E3)(c.includes("Enriched in WT"),!0),(0,t.E3)(c.includes("Not significant"),!0)}),(0,t.t6)("volcanoCounterFilterRecompute: Total updates within one debounce window on filter change",async()=>{const e=ne(100),n=(0,W.gO)(e,{topNLabels:0});e.filter.setAll(!1),e.filter.set(0,!0),e.filter.set(1,!0),e.filter.fireChanged(),await(0,t.bk)(()=>(n.root.querySelector("[data-volcano-counter]")?.textContent??"").includes("Total: 2"),"volcano counter Total did not update to 2 after filter change",3e3)},{skipReason:"Quarantined: counter overlay not refreshing on filter change on newer Datagrok runtime — see BACKLOG"}),(0,t.t6)("volcanoCounterEmptyFilter: zero rows still renders Total: 0",async()=>{const e=ne(20),n=(0,W.gO)(e,{topNLabels:0});e.filter.setAll(!1),e.filter.fireChanged(),await(0,t.bk)(()=>(n.root.querySelector("[data-volcano-counter]")?.textContent??"").includes("Total: 0"),"volcano counter Total did not reach 0 on empty filter",3e3)},{skipReason:"Quarantined: counter overlay not refreshing on filter change on newer Datagrok runtime — see BACKLOG"}),(0,t.t6)("volcanoCounterSubscriptionsDisposedOnReentry: only one overlay remains after re-create",async()=>{const e=ne(50);(0,W.gO)(e,{topNLabels:0});const n=(0,W.gO)(e,{topNLabels:0}).root.querySelectorAll("[data-volcano-counter]");(0,t.E3)(n.length,1)}),(0,t.t6)("volcanoCounterLocationMode: per-location rows after color switch",async()=>{const e=ne(20);e.col("Protein ID").semType=s.iu.PROTEIN_ID;const n=(0,W.gO)(e,{topNLabels:0});await(0,W.nj)(e,n,"adj.p-value","location",1,.05),await(0,t.bk)(()=>(n.root.querySelector("[data-volcano-counter]")?.textContent??"").includes("Unknown"),"volcano counter did not show a location row after color switch",3e3)}),(0,t.t6)("volcanoOptionsPreloadMetric: readVolcanoState reflects last recompute metric",async()=>{const e=ae(),n=(0,W.gO)(e,{topNLabels:0});(0,t.E3)((0,W.ur)(e,n).metric,"adj.p-value"),await(0,W.nj)(e,n,"p-value","significance",1,.05),(0,t.E3)((0,W.ur)(e,n).metric,"p-value"),await(0,W.nj)(e,n,"adj.p-value","significance",1,.05),(0,t.E3)((0,W.ur)(e,n).metric,"adj.p-value")}),(0,t.t6)("volcanoOptionsPreloadColorDim: readVolcanoState reflects current colorColumnName",async()=>{const e=ne(20);e.col("Protein ID").semType=s.iu.PROTEIN_ID;const n=(0,W.gO)(e,{topNLabels:0});(0,t.E3)((0,W.ur)(e,n).colorDim,"significance"),await(0,W.nj)(e,n,"adj.p-value","location",1,.05),(0,t.E3)((0,W.ur)(e,n).colorDim,"location"),await(0,W.nj)(e,n,"adj.p-value","significance",1,.05),(0,t.E3)((0,W.ur)(e,n).colorDim,"significance")})});var ie=n(117);function le(e,t={}){const n=t.status??200,o=new Headers;return null!=t.retryAfter&&o.set("Retry-After",t.retryAfter),new Response(null==e?null:JSON.stringify(e),{status:n,headers:o})}async function ce(e,t){const n=v.dapi,o=Object.getPrototypeOf(n),r=Object.prototype.hasOwnProperty.call(n,"fetchProxy"),s=r?n.fetchProxy:void 0,a=o.fetchProxy;n.fetchProxy=e,o.fetchProxy=e;try{await t()}finally{r?n.fetchProxy=s:delete n.fetchProxy,o.fetchProxy=a}}async function ue(e,t){const n=v.dapi.userDataStorage,o=Object.getPrototypeOf(n),r=o.get,s=o.put;o.get=async t=>e.get(t)??null,o.put=async(t,n)=>{e.set(t,n)};try{await t()}finally{o.get=r,o.put=s}}async function me(e){const t=[],n=v.shell,o=n.warning;n.warning=e=>{t.push(e)};try{await e()}finally{n.warning=o}return t}function pe(e){return{native:e.native??`NS:${e.name}`,name:e.name,source:e.source,p_value:e.p_value,significant:e.significant??!0,term_size:e.term_size??100,query_size:e.query_size??50,intersection_size:e.intersection_size??5,effective_domain_size:e.effective_domain_size??2e4,precision:e.precision??.1,recall:e.recall??.05,intersections:e.intersections??[]}}(0,t.L1)("Proteomics: 14-01",()=>{(0,t.t6)("geneLabelResolverSemTypes: SEMTYPE constants are the locked strings",async()=>{(0,t.E3)(s.iu.DISPLAY_NAME,"Proteomics-DisplayName"),(0,t.E3)(s.iu.SOURCE_ID,"Proteomics-SourceId"),(0,t.E3)(s.iu.NUMERATOR_MEAN,"Proteomics-NumeratorMean"),(0,t.E3)(s.iu.DENOMINATOR_MEAN,"Proteomics-DenominatorMean");const e=new Set([s.iu.DISPLAY_NAME,s.iu.SOURCE_ID,s.iu.NUMERATOR_MEAN,s.iu.DENOMINATOR_MEAN,s.iu.PROTEIN_ID,s.iu.GENE_SYMBOL,s.iu.INTENSITY,s.iu.LOG2FC,s.iu.P_VALUE,s.iu.SUBCELLULAR_LOCATION]);(0,t.E3)(e.size,10)}),(0,t.t6)("geneLabelResolverDetectorMirror: SEMTYPE values are valid Column.semType strings",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Display Name",["Myh7†","Tnnt3"]),e.Column.fromStrings("Source ID",["ENSRNOG0001",""]),e.Column.fromFloat32Array("Numerator Mean",new Float32Array([1,2])),e.Column.fromFloat32Array("Denominator Mean",new Float32Array([1.5,2.5]))]);n.col("Display Name").semType=s.iu.DISPLAY_NAME,n.col("Source ID").semType=s.iu.SOURCE_ID,n.col("Numerator Mean").semType=s.iu.NUMERATOR_MEAN,n.col("Denominator Mean").semType=s.iu.DENOMINATOR_MEAN,(0,t.E3)(n.col("Display Name").semType,"Proteomics-DisplayName"),(0,t.E3)(n.col("Source ID").semType,"Proteomics-SourceId"),(0,t.E3)(n.col("Numerator Mean").semType,"Proteomics-NumeratorMean"),(0,t.E3)(n.col("Denominator Mean").semType,"Proteomics-DenominatorMean")}),(0,t.t6)("detectSpecies: maps prefixes per CK-omics species table",async()=>{(0,t.E3)((0,ie.eA)("ENSG00000123"),"homo_sapiens"),(0,t.E3)((0,ie.eA)("ENSMUSG00000456"),"mus_musculus"),(0,t.E3)((0,ie.eA)("MGP_C57BL6NJ_G0000001"),"mus_musculus"),(0,t.E3)((0,ie.eA)("ENSRNOG00000789"),"rattus_norvegicus"),(0,t.E3)((0,ie.eA)("ENSRNO00000001"),"rattus_norvegicus"),(0,t.E3)((0,ie.eA)("ENSDARG00000222"),"danio_rerio"),(0,t.E3)((0,ie.eA)("LOC123456"),null),(0,t.E3)((0,ie.eA)("RGD7890"),null),(0,t.E3)((0,ie.eA)("AABR07012345"),null)}),(0,t.t6)("isEnsemblEligible: filters LOC/RGD/AABR per CK-omics line 933",async()=>{(0,t.E3)((0,ie.oA)("ENSG00000001"),!0),(0,t.E3)((0,ie.oA)("ENSMUSG00000123"),!0),(0,t.E3)((0,ie.oA)("ENSRNOG00000456"),!0),(0,t.E3)((0,ie.oA)("ENSDARG00000789"),!0),(0,t.E3)((0,ie.oA)("MGP_C57BL6NJ_G0000001"),!0),(0,t.E3)((0,ie.oA)("LOC123456"),!1),(0,t.E3)((0,ie.oA)("RGD789"),!1),(0,t.E3)((0,ie.oA)("AABR07012345"),!1)}),(0,t.t6)("isPredicted: locked CK-omics prefix list",async()=>{(0,t.E3)((0,ie.no)("ENSRNOG00000001"),!0),(0,t.E3)((0,ie.no)("LOC987"),!0),(0,t.E3)((0,ie.no)("AABR07"),!0),(0,t.E3)((0,ie.no)("Myh7"),!1),(0,t.E3)((0,ie.no)("Tnnt3"),!1)}),(0,t.t6)("extractReadableDescription: strips Predicted-to prefixes and species suffixes",async()=>{(0,t.E3)((0,ie.qo)("Predicted to enable actin binding [Rattus norvegicus]"),"Actin binding"),(0,t.E3)((0,ie.qo)("Predicted to be involved in transport. Additional sentence."),"Transport"),(0,t.E3)((0,ie.qo)("Myosin heavy chain_RAT"),"Myosin heavy chain"),(0,t.E3)((0,ie.qo)(""),null),(0,t.E3)((0,ie.qo)(null),null),(0,t.E3)((0,ie.qo)("uncharacterized protein"),null)}),(0,t.t6)("applyMarkerRules: appends * and † per CK-omics line 1011",async()=>{(0,t.E3)((0,ie.KK)("Myh7",!1,!0),"Myh7†"),(0,t.E3)((0,ie.KK)("Myh7",!0,!0),"Myh7*†"),(0,t.E3)((0,ie.KK)("LOC123",!1,!0),"LOC123†"),(0,t.E3)((0,ie.KK)("Tnnt3",!1,!1),"Tnnt3"),(0,t.E3)((0,ie.KK)("Tnnt3",!0,!1),"Tnnt3*")}),(0,t.t6)("lookupEnsemblBatch: POSTs ids and parses response",async()=>{let e,n="";await ce(async(t,o)=>(n=t,e=o,le({ENSRNOG00000001:{external_name:"Myh7",description:"Myosin heavy chain 7"},ENSRNOG00000002:null})),async()=>{const o=await(0,ie.FH)(["ENSRNOG00000001","ENSRNOG00000002"]);(0,t.E3)(n,"https://rest.ensembl.org/lookup/id"),(0,t.E3)(e?.method,"POST");const r=JSON.parse(e?.body??"{}");(0,t.E3)(Array.isArray(r.ids),!0),(0,t.E3)(r.ids.length,2),(0,t.E3)(o.size,1),(0,t.E3)(o.get("ENSRNOG00000001")?.external_name,"Myh7")})}),(0,t.t6)("lookupEnsemblBatch: retries once on 429 with Retry-After",async()=>{let e=0;await ce(async()=>(e++,1===e?le(null,{status:429,retryAfter:"0"}):le({ENSG00000001:{external_name:"TP53"}})),async()=>{const n=await(0,ie.FH)(["ENSG00000001"]);(0,t.E3)(e,2),(0,t.E3)(n.get("ENSG00000001")?.external_name,"TP53")})}),(0,t.t6)("resolveGeneLabels: no-op path still creates Display Name + Source ID columns",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["P12345","Q67890","O11111"]),e.Column.fromStrings("Gene name",["Myh7","Tnnt3","Actb"])]);n.col("Gene name").semType=s.iu.GENE_SYMBOL,n.col("Protein ID").semType=s.iu.PROTEIN_ID,await ce(async()=>{throw new Error("should not fetch")},async()=>{await(0,ie.rv)(n)});const o=n.col("Display Name"),r=n.col("Source ID");(0,t.E3)(null!=o,!0),(0,t.E3)(null!=r,!0),(0,t.E3)(o.semType,"Proteomics-DisplayName"),(0,t.E3)(r.semType,"Proteomics-SourceId"),(0,t.E3)(o.get(0),"Myh7"),(0,t.E3)(o.get(1),"Tnnt3"),(0,t.E3)(r.get(0),"")}),(0,t.t6)("resolveGeneLabels: LOC/RGD/AABR keep raw ID + †, never sent to Ensembl",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Gene name",["LOC123","RGD456","AABR789"])]);n.col("Gene name").semType=s.iu.GENE_SYMBOL;let o=0;await ue(new Map,async()=>{await ce(async()=>(o++,le({})),async()=>{await(0,ie.rv)(n)})}),(0,t.E3)(o,0),(0,t.E3)(n.col("Display Name").get(0),"LOC123†"),(0,t.E3)(n.col("Display Name").get(1),"RGD456†"),(0,t.E3)(n.col("Display Name").get(2),"AABR789†"),(0,t.E3)(n.col("Source ID").get(0),"LOC123"),(0,t.E3)(n.col("Source ID").get(1),"RGD456"),(0,t.E3)(n.col("Source ID").get(2),"AABR789")}),(0,t.t6)("resolveGeneLabels: disambiguates duplicates with (Source ID) suffix and warns",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Gene name",["ENSRNOG00000001","ENSRNOG00000002","Actb"])]);n.col("Gene name").semType=s.iu.GENE_SYMBOL;const o=await me(async()=>{await ue(new Map,async()=>{await ce(async()=>le({ENSRNOG00000001:{external_name:"Myh7"},ENSRNOG00000002:{external_name:"Myh7"}}),async()=>{await(0,ie.rv)(n)})})});(0,t.E3)(n.col("Display Name").get(0),"Myh7† (ENSRNOG00000001)"),(0,t.E3)(n.col("Display Name").get(1),"Myh7† (ENSRNOG00000002)"),(0,t.E3)(n.col("Display Name").get(2),"Actb");const r=o.find(e=>e.includes("duplicate gene names"));(0,t.E3)(null!=r,!0)}),(0,t.t6)("resolveGeneLabels: cache short-circuits second call",async()=>{const n=new Map;let o=0;const r=async()=>(o++,le({ENSRNOG00000001:{external_name:"Myh7"}})),a=e.DataFrame.fromColumns([e.Column.fromStrings("Gene name",["ENSRNOG00000001"])]);a.col("Gene name").semType=s.iu.GENE_SYMBOL;const i=e.DataFrame.fromColumns([e.Column.fromStrings("Gene name",["ENSRNOG00000001"])]);i.col("Gene name").semType=s.iu.GENE_SYMBOL,await ue(n,async()=>{await ce(r,async()=>{await(0,ie.rv)(a);const e=o;await(0,ie.rv)(i),(0,t.E3)(o,e)})}),(0,t.E3)(i.col("Display Name").get(0),"Myh7†");const l=n.get(ie.I5)??{};(0,t.E3)(l.__schema_v,ie.Rw)}),(0,t.t6)("resolveGeneLabels: degrades gracefully on fetchProxy throw",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Gene name",["ENSRNOG00000001","Actb"])]);n.col("Gene name").semType=s.iu.GENE_SYMBOL;const o=await me(async()=>{await ue(new Map,async()=>{await ce(async()=>{throw new Error("network down")},async()=>{await(0,ie.rv)(n)})})});(0,t.E3)(n.col("Display Name").get(0),"ENSRNOG00000001†"),(0,t.E3)(n.col("Display Name").get(1),"Actb"),(0,t.E3)(n.col("Source ID").get(0),"ENSRNOG00000001");const r=o.find(e=>e.includes("Ensembl gene-label resolution unavailable"));(0,t.E3)(null!=r,!0)}),(0,t.t6)("parser integration: every parser produces Display Name + Source ID columns",async()=>{const e=await(0,r.E)(["Protein IDs\tMajority protein IDs\tGene names\tPotential contaminant\tReverse\tOnly identified by site\tLFQ intensity Sample1\tLFQ intensity Sample2\tiBAQ","P12345\tP12345\tBRCA1\t\t\t\t1000\t2000\t500"].join("\n"));(0,t.E3)(e.col("Display Name")?.semType,"Proteomics-DisplayName"),(0,t.E3)(e.col("Source ID")?.semType,"Proteomics-SourceId");const n=await(0,B.p)(["Protein\tGene\tDescription\tMaxLFQ Intensity Sample1\tMaxLFQ Intensity Sample2","P12345\tBRCA1\tProtein BRCA1\t1000\t2000"].join("\n"));(0,t.E3)(n.col("Display Name")?.semType,"Proteomics-DisplayName"),(0,t.E3)(n.col("Source ID")?.semType,"Proteomics-SourceId");const o=await(0,L.R)(["PG.ProteinGroups\tPG.Genes\tComparison (group1/group2)\tAVG Log2 Ratio\tQvalue\tPvalue","P12345\tBRCA1\tA / B\t2.5\t0.001\t0.0005"].join("\n"));(0,t.E3)(o.col("Display Name")?.semType,"Proteomics-DisplayName"),(0,t.E3)(o.col("Source ID")?.semType,"Proteomics-SourceId");const s=await(0,A.parseSpectronautText)(["PG.ProteinGroups\tPG.Genes\tR.Condition\tR.Replicate\tR.FileName\tPG.Qvalue\tPG.Quantity","P12345\tBRCA1\tCtrl\t1\tF1\t0.0001\t1000","P12345\tBRCA1\tCtrl\t2\tF2\t0.0001\t1200","P12345\tBRCA1\tTrt\t1\tF3\t0.0001\t2000","P12345\tBRCA1\tTrt\t2\tF4\t0.0001\t2400"].join("\n"));(0,t.E3)(s.col("Display Name")?.semType,"Proteomics-DisplayName"),(0,t.E3)(s.col("Source ID")?.semType,"Proteomics-SourceId")}),(0,t.t6)("resolveGeneLabels: three-level fallback uses description when external_name missing",async()=>{const n=e.DataFrame.fromColumns([e.Column.fromStrings("Gene name",["ENSRNOG00000099"])]);n.col("Gene name").semType=s.iu.GENE_SYMBOL,await ue(new Map,async()=>{await ce(async()=>le({ENSRNOG00000099:{description:"Predicted to enable kinase activity [Rattus norvegicus]"}}),async()=>{await(0,ie.rv)(n)})}),(0,t.E3)(n.col("Display Name").get(0),"Predicted to enable kinase activity†"),(0,t.E3)(n.col("Source ID").get(0),"ENSRNOG00000099")})}),(0,t.L1)("Proteomics: 14-05",()=>{(0,t.t6)("smartPathwayFilter constants match CK-omics literal lists",async()=>{(0,t.E3)(h.zy.length,6),(0,t.E3)(h.zy.includes("localization"),!0),(0,t.E3)(h.zy.includes("cellular component organization"),!0),(0,t.E3)(h.zy.includes("transport"),!0),(0,t.E3)(h.zy.includes("cellular process"),!0),(0,t.E3)(h.zy.includes("biological process"),!0),(0,t.E3)(h.zy.includes("metabolic process"),!0),(0,t.E3)(h._W.length,4),(0,t.E3)(h._W.includes("actin"),!0),(0,t.E3)(h._W.includes("vesicle"),!0),(0,t.E3)(h._W.includes("endocytosis"),!0),(0,t.E3)(h._W.includes("cytoskeleton"),!0)}),(0,t.t6)("smartFilterDropsGenericParentWhenChildKept",async()=>{const e=[pe({name:"actin cytoskeleton organization",source:"GO:BP",p_value:.001}),pe({name:"cellular component organization",source:"GO:BP",p_value:.002}),pe({name:"vesicle docking",source:"GO:BP",p_value:.003}),pe({name:"transport",source:"GO:BP",p_value:.004}),pe({name:"protein phosphorylation",source:"GO:BP",p_value:.005})],{kept:n,stats:o}=(0,h.AB)(e,15);(0,t.E3)(n.length,3),(0,t.E3)(o.total,5),(0,t.E3)(o.kept,3),(0,t.E3)(o.droppedParents,2),(0,t.E3)(o.cappedAtN,15);const r=n.map(e=>e.name);(0,t.E3)(r.includes("actin cytoskeleton organization"),!0),(0,t.E3)(r.includes("vesicle docking"),!0),(0,t.E3)(r.includes("protein phosphorylation"),!0),(0,t.E3)(r.includes("cellular component organization"),!1),(0,t.E3)(r.includes("transport"),!1)}),(0,t.t6)("smartFilterKeepsGenericParentWhenNoChildFirst",async()=>{const e=[pe({name:"biological process",source:"GO:BP",p_value:.001}),pe({name:"actin filament organization",source:"GO:BP",p_value:.002}),pe({name:"protein folding",source:"GO:BP",p_value:.003})],{kept:n,stats:o}=(0,h.AB)(e,15);(0,t.E3)(n.length,3),(0,t.E3)(o.droppedParents,0)}),(0,t.t6)("smartFilterCapsGoBpAt15",async()=>{const e=[];for(let t=0;t<30;t++)e.push(pe({name:`pathway ${t}`,source:"GO:BP",p_value:.001*(t+1)}));const{kept:n,stats:o}=(0,h.AB)(e,15);(0,t.E3)(n.length,15),(0,t.E3)(o.total,30),(0,t.E3)(o.kept,15),(0,t.E3)(o.droppedParents,0);for(const e of n){const n=parseInt(e.name.replace("pathway ",""));(0,t.E3)(n<15,!0)}}),(0,t.t6)("smartFilterHonorsCustomCap (M3 — configurable max terms per source)",async()=>{const e=[];for(let t=0;t<30;t++)e.push(pe({name:`bp ${t}`,source:"GO:BP",p_value:.001*(t+1)}));for(let t=0;t<30;t++)e.push(pe({name:`kegg ${t}`,source:"KEGG",p_value:.01*(t+1)}));const{kept:n,stats:o}=(0,h.AB)(e,5);(0,t.E3)(n.length,10,"custom cap 5 applied to each partition"),(0,t.E3)(o.cappedAtN,5,"stats echo the custom cap"),(0,t.E3)(n.filter(e=>"GO:BP"===e.source).length,5,"GO:BP capped at 5"),(0,t.E3)(n.filter(e=>"KEGG"===e.source).length,5,"non-GO:BP capped at 5")}),(0,t.t6)("smartFilterCombinedCapForNonGoBp (Assumption A4)",async()=>{const e=[];for(let t=0;t<5;t++)e.push(pe({name:`bp ${t}`,source:"GO:BP",p_value:.001*(t+1)}));const n=["KEGG","REAC","WP"];for(let t=0;t<20;t++)e.push(pe({name:`other ${t}`,source:n[t%3],p_value:.01*(t+1)}));const{kept:o,stats:r}=(0,h.AB)(e,15);(0,t.E3)(o.length,20),(0,t.E3)(r.total,25),(0,t.E3)(r.kept,20);const s=o.filter(e=>"GO:BP"!==e.source);(0,t.E3)(s.length,15)}),(0,t.t6)("smartFilterPreservesPValueSortOrder",async()=>{const e=[pe({name:"a",source:"GO:BP",p_value:.005}),pe({name:"b",source:"KEGG",p_value:.001}),pe({name:"c",source:"GO:BP",p_value:.003}),pe({name:"d",source:"REAC",p_value:.002})],{kept:n}=(0,h.AB)(e,15);for(let e=1;e<n.length;e++)(0,t.E3)(n[e-1].p_value<=n[e].p_value,!0)}),(0,t.t6)("smartFilterEmptyInput",async()=>{const{kept:e,stats:n}=(0,h.AB)([],15);(0,t.E3)(e.length,0),(0,t.E3)(n.total,0),(0,t.E3)(n.kept,0),(0,t.E3)(n.droppedParents,0),(0,t.E3)(n.cappedAtN,15)}),(0,t.t6)("smartFilterStatsCount",async()=>{const e=[pe({name:"actin organization",source:"GO:BP",p_value:.001}),pe({name:"biological process",source:"GO:BP",p_value:.002}),pe({name:"metabolic process",source:"GO:BP",p_value:.003})],{kept:n,stats:o}=(0,h.AB)(e,15);(0,t.E3)(o.total,e.length),(0,t.E3)(o.kept,n.length),(0,t.E3)(o.droppedParents,2),(0,t.E3)(o.cappedAtN,15)}),(0,t.t6)("smartFilter empty GO:BP, only other sources",async()=>{const e=[];for(let t=0;t<25;t++)e.push(pe({name:`kegg ${t}`,source:"KEGG",p_value:.001*(t+1)}));const{kept:n,stats:o}=(0,h.AB)(e,15);(0,t.E3)(n.length,15),(0,t.E3)(o.droppedParents,0)}),(0,t.t6)("smartFilter non-GO:BP path also sorts by p ASC",async()=>{const e=[pe({name:"kegg_high",source:"KEGG",p_value:.1}),pe({name:"kegg_low",source:"KEGG",p_value:.001}),pe({name:"reac_mid",source:"REAC",p_value:.05})],{kept:n}=(0,h.AB)(e,2);(0,t.E3)(n.length,2),(0,t.E3)(n[0].name,"kegg_low"),(0,t.E3)(n[1].name,"reac_mid")})});var de=n(498);function fe(t={}){const{groupColsExist:n=!0,withGroupsTag:o=!0,withProteinId:r=!0,row0AllNan:a=!1}=t,i=[];if(r){const t=e.Column.fromStrings("Primary Protein ID",["P11111","P22222","P33333"]);t.semType=s.iu.PROTEIN_ID,i.push(t)}if(n){const t=a?[NaN,1,1]:[1,1.5,2],n=a?[NaN,3,1]:[3,2.5,2.5],o=a?[NaN,4,4]:[5,4,5],r=a?[NaN,6,4]:[7,6,5.5],s=e.Column.fromList("double","Sample1",t),l=e.Column.fromList("double","Sample2",n),c=e.Column.fromList("double","Sample3",o),u=e.Column.fromList("double","Sample4",r);a&&(s.set(0,null),l.set(0,null),c.set(0,null),u.set(0,null)),i.push(s,l,c,u)}const c=e.DataFrame.fromColumns(i);return o&&n&&(0,l.$Y)(c,{group1:{name:"Control",columns:["Sample1","Sample2"]},group2:{name:"Treatment",columns:["Sample3","Sample4"]}}),c.name=`panel-fixture-${Math.random().toString(36).slice(2,8)}`,c}function ge(e){return{accession:e,proteinDescription:{recommendedName:{fullName:{value:"Mock Protein"}}},genes:[{geneName:{value:"MOCK1"}}],organism:{scientificName:"Homo sapiens"},comments:[],uniProtKBCrossReferences:[]}}(0,t.L1)("Proteomics: 14-04",()=>{(0,t.t6)("uniprotPanelPerGroupBarsRender",async()=>{const e=fe(),n=v.shell.addTableView(e);try{const e=(0,de.A$)(ge("P11111"),"P11111");(0,t.E3)(e.textContent?.includes("Per-Group Quantities"),!0);const n=e.querySelectorAll("rect");(0,t.E3)(n.length,2);const o=Array.from(e.querySelectorAll("text")).map(e=>e.textContent??"").filter(e=>e.includes("(n=2)")).length;(0,t.E3)(o,2);const r=Array.from(e.querySelectorAll("div")).filter(e=>null===e.querySelector(":scope > div")).map(e=>e.textContent??"").filter(e=>/mean=.*SD=/.test(e));(0,t.E3)(r.length,2)}finally{n.close()}}),(0,t.t6)("uniprotPanelPerGroupBarsEmptyState",async()=>{const e=fe({withGroupsTag:!1}),n=v.shell.addTableView(e);try{const e=(0,de.A$)(ge("P11111"),"P11111"),n=e.querySelectorAll("rect");(0,t.E3)(n.length,0),(0,t.E3)(e.textContent?.includes("Per-Group Quantities"),!1)}finally{n.close()}}),(0,t.t6)("uniprotPanelPerGroupBarsColors",async()=>{const e=fe(),n=v.shell.addTableView(e);try{const e=(0,de.A$)(ge("P11111"),"P11111").querySelectorAll("rect");(0,t.E3)(e.length,2),(0,t.E3)(e[0].getAttribute("fill"),"#FF00FF"),(0,t.E3)(e[1].getAttribute("fill"),"#00FFFF")}finally{n.close()}}),(0,t.t6)("uniprotPanelPerGroupMeanSDComputation",async()=>{const n=[],o=e.Column.fromStrings("Primary Protein ID",["P11111"]);o.semType=s.iu.PROTEIN_ID,n.push(o),n.push(e.Column.fromList("double","S1",[1])),n.push(e.Column.fromList("double","S2",[3])),n.push(e.Column.fromList("double","S3",[5])),n.push(e.Column.fromList("double","S4",[7]));const r=e.DataFrame.fromColumns(n);(0,l.$Y)(r,{group1:{name:"Control",columns:["S1","S2"]},group2:{name:"Treatment",columns:["S3","S4"]}}),r.name="mean-sd-fixture";const a=v.shell.addTableView(r);try{const e=(0,de.nT)(r,"P11111");(0,t.E3)(null!==e,!0);const n=Array.from(e.querySelectorAll("div")).map(e=>e.textContent??"").filter(e=>/mean=.*SD=/.test(e));(0,t.E3)(n.length,2);const o=n.find(e=>e.startsWith("Control:")),s=n.find(e=>e.startsWith("Treatment:"));(0,t.E3)(void 0!==o,!0),(0,t.E3)(void 0!==s,!0),(0,t.E3)(o.includes("mean=2.00"),!0),(0,t.E3)(o.includes("SD=1.41"),!0),(0,t.E3)(s.includes("mean=6.00"),!0),(0,t.E3)(s.includes("SD=1.41"),!0)}finally{a.close()}}),(0,t.t6)("uniprotPanelPerGroupBarsAllNanProtein",async()=>{const e=fe({row0AllNan:!0}),n=v.shell.addTableView(e);try{const n=(0,de.nT)(e,"P11111");(0,t.E3)(null!==n,!0),(0,t.E3)(n.tagName.toLowerCase(),"div"),(0,t.E3)((n.textContent??"").includes("No per-group quantities available"),!0),(0,t.E3)(n.querySelectorAll("rect").length,0)}finally{n.close()}}),(0,t.t6)("findHostDataFrameForProteinPrefersActiveTable",async()=>{const e=fe(),n=fe(),o=v.shell.addTableView(e),r=v.shell.addTableView(n);try{const e=(0,de.xh)("P11111");(0,t.E3)(null!==e,!0);const n=v.shell.tv?.dataFrame;(0,t.E3)(e===n,!0)}finally{o.close(),r.close()}})});var he=n(644);function ye(){const t=[],n=e.Column.fromStrings("Primary Protein ID",["P1","P2","P3","P4","P5"]);n.semType=s.iu.PROTEIN_ID,t.push(n);const o=e.Column.fromStrings("Display Name",["Gene1","Gene2","Gene3","Gene4","Gene5"]);o.semType=s.iu.DISPLAY_NAME,t.push(o),t.push(e.Column.fromList("double","S1",[1,2,3,4,5])),t.push(e.Column.fromList("double","S2",[3,4,5,6,7])),t.push(e.Column.fromList("double","S3",[5,6,7,8,9])),t.push(e.Column.fromList("double","S4",[7,8,9,10,11])),t.push(e.Column.fromStrings("direction",["Enriched in Control","Enriched in Treatment","Not significant","Enriched in Control","Enriched in Treatment"]));const r=e.DataFrame.fromColumns(t);return(0,l.$Y)(r,{group1:{name:"Control",columns:["S1","S2"]},group2:{name:"Treatment",columns:["S3","S4"]}}),r.name=`correlation-fixture-${Math.random().toString(36).slice(2,8)}`,r}(0,t.L1)("Proteomics: 14-04",()=>{(0,t.t6)("groupMeanColumnsCreated",async()=>{const e=ye();(0,he.hy)(e,{group1:{name:"Control",columns:["S1","S2"]},group2:{name:"Treatment",columns:["S3","S4"]}});const n=e.col("Numerator Mean"),o=e.col("Denominator Mean");(0,t.E3)(null!==n,!0),(0,t.E3)(null!==o,!0),(0,t.E3)(n.semType,s.iu.NUMERATOR_MEAN),(0,t.E3)(o.semType,s.iu.DENOMINATOR_MEAN),(0,t.E3)(n.length,e.rowCount),(0,t.E3)(o.length,e.rowCount),(0,t.E3)(Math.abs(n.get(0)-2)<1e-6,!0),(0,t.E3)(Math.abs(o.get(0)-6)<1e-6,!0),(0,t.E3)(Math.abs(n.get(4)-6)<1e-6,!0),(0,t.E3)(Math.abs(o.get(4)-10)<1e-6,!0)}),(0,t.t6)("groupMeanColumnsReRunSafe",async()=>{const e=ye(),n={group1:{name:"Control",columns:["S1","S2"]},group2:{name:"Treatment",columns:["S3","S4"]}};(0,he.hy)(e,n),(0,he.hy)(e,n);const o=e.columns.toList().filter(e=>"Numerator Mean"===e.name).length,r=e.columns.toList().filter(e=>"Denominator Mean"===e.name).length;(0,t.E3)(o,1),(0,t.E3)(r,1);const s=e.col("Numerator Mean");(0,t.E3)(Math.abs(s.get(0)-2)<1e-6,!0)}),(0,t.t6)("pearsonPerfectCorrelation",async()=>{const e=(0,he.nc)([1,2,3,4,5],[2,4,6,8,10]);(0,t.E3)(Math.abs(e-1)<1e-9,!0)}),(0,t.t6)("pearsonNoCorrelation",async()=>{const e=(0,he.nc)([1,2,3,4,5],[3,1,4,1,5]);(0,t.E3)(Math.abs(e)<.6,!0)}),(0,t.t6)("spearmanRankTies",async()=>{const e=(0,he.CN)([1,2,2,3,4],[1,2,2,3,4]);(0,t.E3)(Math.abs(e-1)<1e-9,!0)}),(0,t.t6)("createGroupMeanCorrelationFactory",async()=>{const e=ye(),n=(0,he.Z7)(e);(0,t.E3)(null!==n,!0);const o=n.getOptions?.(),r=o?.look?.title??"";(0,t.E3)(r.includes("r="),!0),(0,t.E3)(r.includes("ρ="),!0),(0,t.E3)(n.props.xColumnName,"Numerator Mean"),(0,t.E3)(n.props.yColumnName,"Denominator Mean"),(0,t.E3)(n.props.colorColumnName,"direction")}),(0,t.t6)("correlationDiagonalLine",async()=>{const e=ye();(0,he.Z7)(e);const n=e.meta.formulaLines.items.find(e=>{const t=e.formula??"";return"string"==typeof t&&t.includes("Numerator Mean")&&t.includes("Denominator Mean")});(0,t.E3)(void 0!==n,!0),(0,t.E3)(n.color,"#888888")}),(0,t.t6)("correlationLabelBindsToDisplayName",async()=>{const e=ye(),n=(0,he.Z7)(e);(0,t.E3)(n.props.labelColumnNames?.includes("Display Name"),!0)})});const Ee=["proteomics.source","proteomics.de_method","proteomics.de_complete","proteomics.groups","proteomics.published","proteomics.published_at","proteomics.published_by","proteomics.published_target","proteomics.published_de_method","proteomics.published_fc_threshold","proteomics.published_p_threshold","proteomics.published_version","proteomics.published_id","proteomics.published_includes_enrichment"],we=[["Protein ID",s.iu.PROTEIN_ID],["Gene Name",s.iu.GENE_SYMBOL],["log2FC",s.iu.LOG2FC],["adj.p-value",s.iu.P_VALUE]];function ve(e,t){let n;try{n="string"==typeof t?t:JSON.stringify(t)}catch{n=String(t)}const o=`[publish-spike] ${e}: ${n}`;console.log(o),v.shell.info(o)}async function _e(e,t){try{await t(),ve(`cleanup:${e}`,"ok")}catch(t){ve(`cleanup:${e}:error`,`${t?.message??t}`)}}(0,t.L1)("Publishing-Spike",()=>{(0,t.t6)("save+open roundtrip — enumerate survivors",async()=>{const n=Date.now(),o=`spike-pub-${n}`,r=new Date(n).toISOString(),s=`spike-publish-roundtrip-${n}`;ve("boot",{projectName:s,publishedId:o,nowIso:r});const a=function(t,n){const o=Array.from({length:10},(e,t)=>`P${String(t+1).padStart(5,"0")}`),r=Array.from({length:10},(e,t)=>`GENE${t+1}`),s=new Float32Array([3,2.5,2,1.5,.5,-.4,-1.6,-2.2,-2.8,.1]),a=new Float32Array([1e-4,.001,.005,.02,.04,.1,.001,5e-4,1e-4,.3]),i=new Float32Array([.001,.005,.01,.04,.08,.2,.005,.001,5e-4,.5]),l=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",o),e.Column.fromStrings("Gene Name",r),e.Column.fromFloat32Array("log2FC",s),e.Column.fromFloat32Array("p-value",a),e.Column.fromFloat32Array("adj.p-value",i),e.Column.fromStrings("significant",["up","up","up","up","ns","ns","down","down","down","ns"]),e.Column.fromStrings("direction",["Enriched in Treatment","Enriched in Treatment","Enriched in Treatment","Enriched in Treatment","Not significant","Not significant","Enriched in Control","Enriched in Control","Enriched in Control","Not significant"])]);for(const[e,t]of we)l.col(e).semType=t;l.name="spike-source";const c={"proteomics.source":"generic","proteomics.de_method":"limma","proteomics.de_complete":"true","proteomics.groups":JSON.stringify({group1:{name:"Control",columns:[]},group2:{name:"Treatment",columns:[]}}),"proteomics.published":"true","proteomics.published_at":n,"proteomics.published_by":"spike-operator","proteomics.published_target":"SPIKE-TARGET-A","proteomics.published_de_method":"limma","proteomics.published_fc_threshold":"1.0","proteomics.published_p_threshold":"0.05","proteomics.published_version":"1","proteomics.published_id":t,"proteomics.published_includes_enrichment":"false"};for(const[e,t]of Object.entries(c))l.setTag(e,t);return l}(o,r),i=v.shell.addTableView(a);await(0,t.cb)(100);let l=null;try{const t=i;if("function"==typeof t.scatterPlot)l=t.scatterPlot({x:"log2FC",y:"adj.p-value"});else{l=e.Viewer.scatterPlot(a,{x:"log2FC",y:"adj.p-value"});let t=!1;try{t=Array.from(i.viewers).includes(l)}catch{}l&&!t&&i.addViewer(l)}}catch(e){ve("scatter-add-error",`${e?.message??e}`)}await(0,t.cb)(100);const c=e.Project.create();c.name=s;try{c.options["proteomics.superseded_by"]="dummy-id-A",c.options.custom_option="hello"}catch(e){ve("project-options-set-error",`${e?.message??e}`)}const u=i.dataFrame.getTableInfo(),m=i.getInfo();c.addChild(u),c.addChild(m);let p=null,d=null,f=!1;try{await v.dapi.tables.uploadDataFrame(i.dataFrame),await v.dapi.tables.save(u),p=u.id,await v.dapi.views.save(m),await v.dapi.projects.save(c),d=c.id,f=!0,ve("save:ok",{projectId:d,tableInfoId:p})}catch(e){ve("save:error",`${e?.message??e}`)}if(!f||!d){ve("halt","save sequence failed — skipping reopen and downstream probes");try{v.shell.closeAll()}catch{}return}try{v.shell.closeAll()}catch(e){ve("closeAll-error",`${e?.message??e}`)}await(0,t.cb)(100);let g=null;try{g=await v.dapi.projects.find(d),await g.open()}catch(e){ve("reopen:error",`${e?.message??e}`)}if(!g)return void ve("halt","reopen failed — skipping enumeration");try{await(0,t.bk)(()=>!!v.shell.tv&&!!v.shell.tv.dataFrame,"TableView did not materialize after Project.open()",5e3)}catch(e){ve("await-tv-error",`${e?.message??e}`)}const h=v.shell.tv,y=h?.dataFrame??null;if(ve("df.name survived",y?.name??"(no dataFrame)"),y){const e={};for(const t of Ee)e[t]=y.getTag(t)??null;ve("proteomics.* tags survived",e);const t={};for(const[e]of we){const n=y.col(e);t[e]=n?n.semType??null:"(column missing)"}ve("Proteomics-* semTypes survived",t),ve("reopened columns shape",y.columns.toList().map(e=>({name:e.name,type:e.type,semType:e.semType??null})))}try{const e=g.options??{},t=e["proteomics.superseded_by"],n=e.custom_option;let o=[];try{o=Object.keys(e)}catch{}ve("project.options",{"proteomics.superseded_by":t??null,custom_option:n??null,keys:o,rawJson:(()=>{try{return JSON.stringify(e)}catch{return"(unstringifiable)"}})()})}catch(e){ve("project.options:error",`${e?.message??e}`)}ve("viewers after reopen",function(){const e=[],t=v.shell.tv;if(!t)return e;for(const n of t.viewers){let t,o,r,s=null;try{s=n.getOptions?n.getOptions()?.look??n.getOptions():null}catch(e){s=`getOptions-threw:${e?.message??e}`}try{t=n.props?.xColumnName}catch{}try{o=n.props?.yColumnName}catch{}try{r=n.props?.colorColumnName}catch{}e.push({type:n.type,xColumnName:t,yColumnName:o,colorColumnName:r,props:s})}return e}());try{const e=await v.dapi.permissions.get(g);let t=[];try{t=Object.keys(e)}catch{}let n="(unstringifiable)";try{n=JSON.stringify(e)}catch{}ve("permissions.get keys",t),ve("permissions.get json",n)}catch(e){ve("permissions.get:error",`${e?.message??e}`)}let E=null,w=null;try{E=await v.dapi.spaces.createRootSpace(`Spike-Reviews-${n}`),ve("umbrella-space",{id:E.id,friendlyName:E.friendlyName});const e=v.dapi.spaces.id(E.id);w=await e.addSubspace(`Spike-Review-Inherit-${n}`),ve("inherited-child-space",{id:w.id,friendlyName:w.friendlyName});const t=v.dapi.spaces.id(w.id);try{await t.addEntity(g.id),ve("inherited-child:addEntity","ok")}catch(e){ve("inherited-child:addEntity:error",`${e?.message??e}`)}try{const e=(await v.dapi.users.current()).group??null;e?(await v.dapi.permissions.grant(E,e,!1),ve("umbrella-space:grant-view",{group:e.friendlyName??e.name??"(unnamed)"})):ve("umbrella-space:grant-skipped","no user.group found")}catch(e){ve("umbrella-space:grant:error",`${e?.message??e}`)}try{const e=await v.dapi.permissions.get(g);let t=[];try{t=Object.keys(e)}catch{}ve("permissions.get(childProject) after umbrella-grant",{keys:t,json:(()=>{try{return JSON.stringify(e)}catch{return"(unstringifiable)"}})()})}catch(e){ve("childProject:permissions.get:error",`${e?.message??e}`)}}catch(e){ve("space-probe:error",`${e?.message??e}`)}try{const e=await v.dapi.projects.filter('name like "spike-publish-roundtrip-%"').list();ve('filter "like" result',{count:Array.isArray(e)?e.length:"(non-array)",firstName:Array.isArray(e)&&e.length>0?e[0].name??null:null})}catch(e){ve("filter:like:error",`${e?.message??e}`)}try{const e=await v.dapi.projects.filter('name contains "spike-publish-roundtrip"').list();ve('filter "contains" result',{count:Array.isArray(e)?e.length:"(non-array)",firstName:Array.isArray(e)&&e.length>0?e[0].name??null:null})}catch(e){ve("filter:contains:error",`${e?.message??e}`)}const _=p;try{await v.dapi.projects.delete(g),ve("projects.delete","ok")}catch(e){ve("projects.delete:error",`${e?.message??e}`)}if(_)try{const e=await v.dapi.tables.find(_);ve("tables.find(tableInfoId) after project.delete",{resolved:!!e,name:e?e.name??null:null})}catch(e){ve("tables.find:after-delete:error",`${e?.message??e}`)}w&&await _e("inherited-child-space",()=>v.dapi.spaces.delete(w)),E&&await _e("umbrella-space",()=>v.dapi.spaces.delete(E)),await _e("project (idempotent)",async()=>{try{const e=await v.dapi.projects.find(d);e&&await v.dapi.projects.delete(e)}catch{}}),ve("done","spike enumeration complete — read output above")})});var Ce=n(771),be=n(807),Te=n(691),Pe=n(649);const Se="pub-roundtrip-",Ne=.05;function Ae(){const t=new Float32Array([3.2,2.6,2.1,1.7,1.3,.2,-1.7,-2.3,-2.9,-3.4]),n=new Float32Array([1e-4,5e-4,.001,.005,.02,.5,.005,.001,5e-4,1e-4]),o=new Float32Array([5e-4,.0015,.005,.01,.04,.6,.01,.005,.0015,5e-4]),r=e.DataFrame.fromColumns([e.Column.fromStrings("Protein ID",["P10001","P10002","P10003","P10004","P10005","P10006","P10007","P10008","P10009","P10010"]),e.Column.fromStrings("Gene Name",["ALPHA","BETA","GAMMA","DELTA","EPSILON","ZETA","ETA","THETA","IOTA","KAPPA"]),e.Column.fromFloat32Array("log2FC",t),e.Column.fromFloat32Array("p-value",n),e.Column.fromFloat32Array("adj.p-value",o),e.Column.fromStrings("significant",["yes","yes","yes","yes","yes","no","yes","yes","yes","yes"]),e.Column.fromStrings("direction",["Up","Up","Up","Up","Up","NS","Down","Down","Down","Down"])]);return r.col("Protein ID").semType=s.iu.PROTEIN_ID,r.col("Gene Name").semType=s.iu.GENE_SYMBOL,r.col("log2FC").semType=s.iu.LOG2FC,r.col("adj.p-value").semType=s.iu.P_VALUE,r.setTag("proteomics.source","generic"),r.setTag("proteomics.de_method","limma"),r.setTag("proteomics.de_complete","true"),r.setTag("proteomics.groups",JSON.stringify({group1:{name:"Control",columns:["s1","s2","s3"]},group2:{name:"Treatment",columns:["s4","s5","s6"]}})),r.name="fixture-no-enrichment",r}function xe(){const t=Ae();t.setTag("proteomics.source","spectronaut-candidates"),t.setTag("proteomics.de_method","spectronaut"),t.name="fixture-with-enrichment";const n=new Float32Array([.005,.01,.015,.02,.03,.05]),o=e.DataFrame.fromColumns([e.Column.fromStrings("Term Name",["Term A","Term B","Term C","Term D","Term E","Term F"]),e.Column.fromStrings("Source",["GO:BP","KEGG","GO:BP","GO:BP","KEGG","REAC"]),e.Column.fromFloat32Array("FDR",n),e.Column.fromStrings("Intersection",["ALPHA,BETA,GAMMA","DELTA,EPSILON","ETA,THETA","IOTA,KAPPA","ALPHA,DELTA","BETA,GAMMA,ETA"])]);return o.setTag("proteomics.enrichment","true"),o.name="enrichment-fixture",{protein:t,enrichment:o}}async function De(){const t=e.Group.defaultGroupsIds?.Test;if(t)try{const e=await v.dapi.groups.find(t);if(e)return e}catch{}const n=v.shell.user?.group?.id,o=await v.dapi.groups.list();return(o??[]).find(e=>e&&!e.hidden&&!e.personal&&e.id!==n)||(o??[])[0]}function Le(e,t,n,o,r){return{expectedName:e,expectedProjectName:t,expectedAllowlist:n,expectedMeta:{...o},expectVolcano:!0,expectEnrichment:r,expectFormulaLines:!0}}async function Fe(e){if(e)try{await v.dapi.projects.delete(e)}catch(t){console.warn(`[publish-roundtrip] project cleanup failed (${e?.name}): ${t}`)}}async function Ie(e){const t=v.dapi,n=`Proteomics-Review-${(0,Ce.fz)(e)}`;try{const e=(await t.spaces.list()??[]).find(e=>"Proteomics-Reviews"===e?.name||"Proteomics-Reviews"===e?.friendlyName);if(!e)return;const o=(await t.spaces.id(e.id).children.filter("Project",!1).list()??[]).find(e=>e?.friendlyName===n||e?.name===n);o&&await t.spaces.delete(o)}catch(e){console.warn(`[publish-roundtrip] child-space cleanup failed (${n}): ${e}`)}}function Me(){const e=v.shell.tv;return e?e.dataFrame.columns.toList().map(e=>e.name).filter(e=>!e.startsWith("_meta_")&&!e.startsWith("~")):[]}function Oe(e,t,n,o){const r=e.options?.[Ce.L6.PUBLISHED_ID]??"",s=t.getTag("proteomics.de_method")??"t-test";return{target:n,publishedAt:new Date,publishedBy:v.shell.user?.friendlyName??"",publishedByEmail:v.shell.user?.email??null,deMethod:s,fcThreshold:1,pThreshold:Ne,version:1,publishId:r,includesEnrichment:o,supersedes:null,supersededBy:null}}function Re(){const t=Date.UTC(2026,5,1),n=[];for(let e=0;e<5;e++)n.push(t+864e5*e);const o=e.Column.fromList(e.COLUMN_TYPE.DATE_TIME,"acquisition_datetime",n),r=e.Column.fromFloat32Array("metric",new Float32Array([4.8,5.1,4.9,5.2,5]));return e.DataFrame.fromColumns([o,r])}function Ge(e){try{v.dapi.files.writeAsText("System:AppData/Proteomics/spike/spike-result.md",e)}catch(e){}try{v.shell.info(e.split("\n")[0])}catch(e){}console.log("[SPC spike] outcome\n"+e)}function ke(e,t,n){let o=0,r=0;for(;0===o;)o=e();for(;0===r;)r=e();return t+n*Math.sqrt(-2*Math.log(o))*Math.cos(2*Math.PI*r)}function $e(e,t,n,o){const r=function(e){let t=e>>>0;return()=>(t=Math.imul(t,1664525)+1013904223>>>0,t/4294967295)}(e),s=[];for(let e=0;e<t;e++)s.push(ke(r,n,o));return s}function Be(){const e="undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"test-"+Math.random().toString(16).slice(2);return`System:AppData/Proteomics/spc-test/${String(e).replace(/[^A-Za-z0-9._-]/g,"-")}`}async function Ue(e){try{await v.dapi.files.delete(e)}catch(e){}}(0,t.L1)("Publishing",()=>{(0,t.t6)("assertPublishedShape round-trip on synthetic fixture (no-enrichment) — formula lines survive reopen",async()=>{const n=Ae(),o=v.shell.addTableView(n);await(0,t.cb)(100);try{o.scatterPlot?.({x:"log2FC",y:"adj.p-value"})}catch{}await(0,t.cb)(100);const r=`${Se}t1-${Date.now()}`,s={target:r,reviewerGroup:await De(),note:"Phase 15 roundtrip Test 1",priorVersion:null};let a=null;try{a=await(0,be.M)(n,s),(0,t.E3)(!!a,!0);const o=a.name,i=Oe(a,n,r,!1),l=Me(),c=Le(`${n.name}_published_${(new Date).toISOString().slice(0,10)}`,o,l,i,!1);await(0,Te.F)(a,c);const u=v.shell.tv;(0,t.E3)(!!u,!0);const m=u?Array.from(u.viewers).find(t=>t.type===e.VIEWER.SCATTER_PLOT):null;(0,t.E3)(!!m,!0);const p=[];try{const e=u.dataFrame.meta?.formulaLines?.items??[];for(const t of e)"string"==typeof t?.formula&&p.push(t.formula)}catch{}try{const e=m.getOptions?.(),t=e?.look?.formulaLines,n="string"==typeof t?JSON.parse(t):t;if(Array.isArray(n))for(const e of n)"string"==typeof e?.formula&&p.push(e.formula)}catch{}const d=p.some(e=>e.includes(String(1))||e.includes("-1")),f=p.some(e=>e.includes(String(Ne))||e.includes(String(-Math.log10(Ne)))||e.includes("log10"));(0,t.E3)(d,!0),(0,t.E3)(f,!0)}finally{await Fe(a),await Ie(r)}}),(0,t.t6)("assertPublishedShape round-trip on Spectronaut Candidates fixture (with-enrichment); cross-DF subscription re-established on reopen",async()=>{const{protein:e,enrichment:n}=xe(),o=v.shell.addTableView(e);await(0,t.cb)(50),v.shell.addTableView(n),await(0,t.cb)(100);try{v.shell.v=o}catch{}try{o.scatterPlot?.({x:"log2FC",y:"adj.p-value"})}catch{}await(0,t.cb)(100);const r=`${Se}t2-${Date.now()}`,s={target:r,reviewerGroup:await De(),note:"Phase 15 roundtrip Test 2",priorVersion:null};let a=null;try{a=await(0,be.M)(e,s),(0,t.E3)(!!a,!0);const n=a.name,o=Oe(a,e,r,!0),i=Me(),l=Le(`${e.name}_published_${(new Date).toISOString().slice(0,10)}`,n,i,o,!0);await(0,Te.F)(a,l);const c=v.shell.tables;(0,t.E3)(Array.isArray(c),!0);const u=(c??[]).find(e=>"true"===e.getTag(Ce.L6.PUBLISHED)&&"true"!==e.getTag("proteomics.enrichment")),m=(c??[]).find(e=>"true"===e.getTag("proteomics.enrichment"));if((0,t.E3)(!!u,!0),(0,t.E3)(!!m,!0),await(0,t.cb)(300),"true"!==m.getTag("proteomics.enrichment_wired"))try{await(0,Pe.I)(u)}catch{}(0,t.E3)(m.getTag("proteomics.enrichment_wired"),"true"),u.selection.setAll(!1,!1);const p=u.selection.trueCount;m.currentRowIdx=0,await(0,t.cb)(150);const d=u.selection.trueCount;(0,t.E3)(d>p,!0)}finally{await Fe(a),await Ie(r)}}),(0,t.t6)("workspace restore (Step 10) brings back BOTH the protein and enrichment views",async()=>{const{protein:e,enrichment:n}=xe(),o=v.shell.addTableView(e);await(0,t.cb)(50),v.shell.addTableView(n),await(0,t.cb)(100);try{v.shell.v=o}catch{}await(0,t.cb)(50);const r=`${Se}restore-${Date.now()}`,s={target:r,reviewerGroup:await De(),note:"restore test",priorVersion:null,verify:!1};let a=null;try{a=await(0,be.M)(e,s),(0,t.E3)(!!a,!0),await(0,t.cb)(200);const o=e.dart,r=n.dart;let i=!1,l=!1;for(const e of v.shell.tableViews){const t=e.dataFrame?.dart;t===o&&(i=!0),t===r&&(l=!0)}(0,t.E3)(i,!0),(0,t.E3)(l,!0),(0,t.E3)(v.shell.tv?.dataFrame?.dart,o)}finally{await Fe(a),await Ie(r)}}),(0,t.t6)("source mutation after publish leaves clone unchanged (Pitfall 1)",async()=>{const e=Ae(),n=e.col("log2FC").get(0),o=`${Se}t3-${Date.now()}`;v.shell.addTableView(e),await(0,t.cb)(100);const r={target:o,reviewerGroup:await De(),note:"",priorVersion:null};let s=null;try{s=await(0,be.M)(e,r),(0,t.E3)(!!s,!0);const a=s.id;v.shell.closeAll(),await(0,t.cb)(100);const i=await v.dapi.projects.find(a);await i.open(),await(0,t.bk)(()=>!!v.shell.tv&&!!v.shell.tv.dataFrame,"reopened1 TableView never materialized",5e3);const l=v.shell.tv.dataFrame.col("log2FC").get(0);(0,t.E3)(l,n),e.col("log2FC").set(0,999.999);try{e.columns.remove("Gene Name")}catch{}e.setTag(Ce.L6.PUBLISHED_TARGET,"CHANGED-TARGET"),v.shell.closeAll(),await(0,t.cb)(100);const c=await v.dapi.projects.find(a);await c.open(),await(0,t.bk)(()=>!!v.shell.tv&&!!v.shell.tv.dataFrame,"reopened2 TableView never materialized",5e3);const u=v.shell.tv.dataFrame,m=u.col("log2FC").get(0);(0,t.E3)(m,n),(0,t.E3)(!!u.col("Gene Name"),!0);const p=u.getTag(Ce.L6.PUBLISHED_TARGET);(0,t.E3)("CHANGED-TARGET"===p,!1),(0,t.E3)(p===o,!0)}finally{await Fe(s),await Ie(o)}}),(0,t.t6)("republish creates v2 with bidirectional superseded_by + supersedes pointers (W-8 dual-write)",async()=>{const e=Ae(),n=`${Se}t4-${Date.now()}`;v.shell.addTableView(e),await(0,t.cb)(100);const o=await De(),r={target:n,reviewerGroup:o,note:"v1",priorVersion:null};let s=null,a=null;try{s=await(0,be.M)(e,r),(0,t.E3)(!!s,!0);const i=s.id,l=s.name;(0,t.E3)(/-v1-\d{4}-\d{2}-\d{2}$/.test(l),!0),await(0,t.cb)(200);const c={target:n,reviewerGroup:o,note:"v2",priorVersion:s};a=await(0,be.M)(e,c),(0,t.E3)(!!a,!0);const u=a.id,m=a.name;(0,t.E3)(/-v2-\d{4}-\d{2}-\d{2}$/.test(m),!0),v.shell.closeAll(),await(0,t.cb)(100);const p=await v.dapi.projects.find(u);await p.open(),await(0,t.bk)(()=>!!v.shell.tv&&!!v.shell.tv.dataFrame,"v2 reopen",5e3);const d=p.options??{};(0,t.E3)(d[Ce.L6.SUPERSEDES],i),v.shell.closeAll(),await(0,t.cb)(100);const f=await v.dapi.projects.find(i);await f.open(),await(0,t.bk)(()=>!!v.shell.tv&&!!v.shell.tv.dataFrame,"v1 reopen",5e3);const g=f.options??{};(0,t.E3)(g[Ce.L6.SUPERSEDED_BY],u);const h=v.shell.tv.dataFrame;(0,t.E3)(h.getTag(Ce.L6.SUPERSEDED_BY),u);const y=h.col(Ce.MD.SUPERSEDED_BY);if(y){const e=y.get(0);""!==e&&null!=e&&(0,t.E3)(String(e),u)}const E=await v.dapi.projects.find(i);(0,t.E3)(!!E,!0)}finally{await Fe(a),await Fe(s),await Ie(n)}}),(0,t.t6)("verify-and-rollback rejects Edit-inherited grant with exact D-03 error string",async()=>{const e=v.dapi,n=`Test-Proteomics-Reviews-${Date.now()}`,o=await e.spaces.createRootSpace(n),r=v.shell.user?.group;try{await v.dapi.permissions.grant(o,r,!0);const s=Ae();v.shell.addTableView(s),await(0,t.cb)(100);const a=`${Se}t5-${Date.now()}`,i={target:a,reviewerGroup:r,note:"negative test",priorVersion:null,umbrellaName:n};let l="",c=null;try{c=await(0,be.M)(s,i)}catch(e){l=String(e?.message??e??"")}(0,t.E3)(l.length>0,!0);const u=l.includes("Reviewer group already has elevated access via Space inheritance");(0,t.E3)(u,!0);try{const n="Proteomics-Review-%",o=(await e.projects.filter(`name like "${n}"`).list()??[]).filter(e=>"string"==typeof e?.name&&e.name.includes(a));(0,t.E3)(o.length,0)}catch{}c&&await Fe(c)}finally{await async function(){try{await(async()=>{await e.spaces.delete(o)})()}catch{}}()}})}),(0,t.L1)("SPC",()=>{(0,t.t6)("SPC:spike_formula_line_dashed_on_datetime",async()=>{const n=Re(),o=e.Viewer.lineChart(n,{xColumnName:"acquisition_datetime",yColumnNames:["metric"]});let r="FAIL",s="",a="";try{const e=o.meta?.formulaLines;if(e&&"function"==typeof e.addLine){e.addLine({formula:"${metric} = 5",style:"dashed",color:"#666666",width:1,visible:!0,title:"UCL"});const t=e.items,n=t&&t[0]?t[0].style:void 0;s="items[0].style="+String(n),"dashed"===n?r="PASS":a='style honored !== "dashed" (observed: '+String(n)+")"}else a="viewer.meta.formulaLines.addLine not addressable on lineChart"}catch(e){a=e&&e.message?e.message:String(e)}Ge(`OUTCOME: ${r}\nObservation: ${s}\n`+(a?`PlatformError: ${a}\n`:"")+"Test: SPC:spike_formula_line_dashed_on_datetime\n"+`Timestamp: ${(new Date).toISOString()}\n`),(0,t.E3)(!0,!0)}),(0,t.t6)("SPC:spike_three_lines_ucl_cl_lcl",async()=>{const n=Re(),o=e.Viewer.lineChart(n,{xColumnName:"acquisition_datetime",yColumnNames:["metric"]}),r=[{formula:"${metric} = 5.4",style:"dashed",color:"#666666",width:1,visible:!0,title:"UCL"},{formula:"${metric} = 5.0",style:"solid",color:"#666666",width:1,visible:!0,title:"CL"},{formula:"${metric} = 4.6",style:"dashed",color:"#666666",width:1,visible:!0,title:"LCL"}];let s=0,a="",i=0;try{const e=o.meta?.formulaLines;if(e&&"function"==typeof e.addLine){for(const t of r)try{e.addLine(t),s++}catch(e){a=e&&e.message?e.message:String(e)}const t=e.items??[];for(const e of t)e&&"dashed"===e.style&&i++}else a="viewer.meta.formulaLines.addLine not addressable on lineChart"}catch(e){a=e&&e.message?e.message:String(e)}Ge(`## Secondary observation: three-lines UCL/CL/LCL\nAdded: ${s}/3\nDashedHonored: ${i}\n`+(a?`PlatformError: ${a}\n`:"")+"Test: SPC:spike_three_lines_ucl_cl_lcl\n"+`Timestamp: ${(new Date).toISOString()}\n`),(0,t.E3)(!0,!0)})}),(0,t.L1)("SPC",()=>{(0,t.t6)("SPC:median_intensity",async()=>{const o=await Promise.resolve().then(n.bind(n,655)),r=e.DataFrame.fromColumns([e.Column.fromFloat32Array("log2(s1)",new Float32Array([10,11,12,13,14])),e.Column.fromFloat32Array("log2(s2)",new Float32Array([11,12,13,14,15]))]);r.col("log2(s1)").semType="Proteomics-Intensity",r.col("log2(s2)").semType="Proteomics-Intensity";const s=o.computeSpcMetrics(r,{group1:{name:"Control",columns:["log2(s1)"]},group2:{name:"Treatment",columns:["log2(s2)"]}},{instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z"});(0,t.E3)(typeof s.median_intensity,"number"),(0,t.E3)(Math.abs(s.median_intensity-12.5)<.6,!0)}),(0,t.t6)("SPC:missing_pct",async()=>{const o=await Promise.resolve().then(n.bind(n,655)),r=e.Column.fromFloat32Array("log2(s1)",new Float32Array([10,NaN,12,NaN])),s=e.Column.fromFloat32Array("log2(s2)",new Float32Array([NaN,11,NaN,14])),a=e.DataFrame.fromColumns([r,s]);a.col("log2(s1)").semType="Proteomics-Intensity",a.col("log2(s2)").semType="Proteomics-Intensity";const i=o.computeSpcMetrics(a,{group1:{name:"Control",columns:["log2(s1)"]},group2:{name:"Treatment",columns:["log2(s2)"]}},{instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z"});(0,t.E3)(Math.abs(i.missing_pct-50)<.001,!0)}),(0,t.t6)("SPC:control_corr",async()=>{const o=await Promise.resolve().then(n.bind(n,655)),r=e.Column.fromFloat32Array("log2(c1)",new Float32Array([1,2,3,4,5])),s=e.Column.fromFloat32Array("log2(c2)",new Float32Array([2,4,6,8,10])),a=e.Column.fromFloat32Array("log2(c3)",new Float32Array([3,6,9,12,15])),i=e.Column.fromFloat32Array("log2(t1)",new Float32Array([5,4,3,2,1])),l=e.DataFrame.fromColumns([r,s,a,i]);[r,s,a,i].forEach(e=>e.semType="Proteomics-Intensity");const c=o.computeSpcMetrics(l,{group1:{name:"Control",columns:["log2(c1)","log2(c2)","log2(c3)"]},group2:{name:"Treatment",columns:["log2(t1)"]}},{instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z"});(0,t.E3)(Math.abs(c.control_corr-1)<.001,!0)}),(0,t.t6)("SPC:protein_count",async()=>{const o=await Promise.resolve().then(n.bind(n,655)),r=e.Column.fromFloat32Array("log2(s1)",new Float32Array([10,NaN,12,NaN,14])),s=e.Column.fromFloat32Array("log2(s2)",new Float32Array([NaN,NaN,13,99,15])),a=e.DataFrame.fromColumns([r,s]);a.col("log2(s1)").semType="Proteomics-Intensity",a.col("log2(s2)").semType="Proteomics-Intensity";const i=o.computeSpcMetrics(a,{group1:{name:"Control",columns:["log2(s1)"]},group2:{name:"Treatment",columns:["log2(s2)"]}},{instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z"});(0,t.E3)(i.protein_count,4)}),(0,t.t6)("SPC:nelson_default",async()=>{const e=await Promise.resolve().then(n.bind(n,655)),o=e.defaultRulesEnabled();(0,t.E3)(o.nelson_1,!0),(0,t.E3)(o.nelson_5,!0),(0,t.E3)(o.nelson_2,!1),(0,t.E3)(o.nelson_3,!1),(0,t.E3)(o.nelson_4,!1),(0,t.E3)(o.nelson_6,!1),(0,t.E3)(o.nelson_7,!1),(0,t.E3)(o.nelson_8,!1);const r=e.evaluateNelsonRules([9.5,10.2,9.8,10.4,10.1],10,1,o);(0,t.E3)(r.status,"pass"),(0,t.E3)(Array.isArray(r.rulesTripped),!0),(0,t.E3)(r.rulesTripped.length,0)}),(0,t.t6)("SPC:nelson_rule_1_3sigma",async()=>{const e=await Promise.resolve().then(n.bind(n,655)),o=e.defaultRulesEnabled(),r=e.evaluateNelsonRules([9.5,10.2,9.8,10.4,15],10,1,o);(0,t.E3)(r.status,"out_of_control"),(0,t.E3)(r.rulesTripped.includes("nelson_1"),!0)}),(0,t.t6)("SPC:nelson_rule_5_2of3",async()=>{const e=await Promise.resolve().then(n.bind(n,655)),o=e.defaultRulesEnabled(),r=e.evaluateNelsonRules([10,9.9,12.4,10,12.3],10,1,o);(0,t.E3)(r.rulesTripped.includes("nelson_5"),!0),(0,t.E3)(r.status,"flagged")}),(0,t.t6)("SPC:false_alarm_rate",async()=>{const e=await Promise.resolve().then(n.bind(n,655)),o=e.defaultRulesEnabled();let r=0;for(let t=1;t<=200;t++){const n=$e(t,8,10,1);e.evaluateNelsonRules(n,10,1,o).rulesTripped.length>0&&r++}const s=r/200;(0,t.E3)(s<.05,!0)}),(0,t.t6)("SPC:status_tags",async()=>{const o=await Promise.resolve().then(n.bind(n,655)),r=e.DataFrame.create(1),s={median_intensity:22.31,missing_pct:12.6,control_corr:.94,protein_count:4820,sample_count:3,computed_at:(new Date).toISOString()};o.setSpcStatus(r,s,{status:"flagged",rulesTripped:["nelson_5@control_corr"]}),(0,t.E3)(r.getTag("proteomics.spc_status"),"flagged"),(0,t.E3)(JSON.parse(r.getTag("proteomics.spc_metrics")).protein_count,4820),(0,t.E3)(JSON.parse(r.getTag("proteomics.spc_rules_tripped"))[0],"nelson_5@control_corr")}),(0,t.t6)("SPC:classification",async()=>{const e=await Promise.resolve().then(n.bind(n,655));(0,t.E3)(e.classifyStatus([]),"pass"),(0,t.E3)(e.classifyStatus(["nelson_1@median_intensity"]),"out_of_control"),(0,t.E3)(e.classifyStatus(["nelson_5@control_corr"]),"flagged"),(0,t.E3)(e.classifyStatus(["nelson_5@control_corr","nelson_1@protein_count"]),"out_of_control")}),(0,t.t6)("SPC:baseline_outlier_removal",async()=>{const e=(await Promise.resolve().then(n.bind(n,655))).computeIterativeBaseline([10.1,9.9,10.2,10,9.95,10.05,10.1,9.9,10.2,10,10.05,100],!0);(0,t.E3)(e.includedCount,11),(0,t.E3)(e.excludedIndices.includes(11),!0),(0,t.E3)(e.iterationTrace.length>=1,!0)}),(0,t.t6)("SPC:baseline_iteration_cap",async()=>{const e=(await Promise.resolve().then(n.bind(n,655))).computeIterativeBaseline([10,10.1,9.9,25,25.1,24.9,30,30.5,29.7],!0);(0,t.E3)(e.iterationTrace.length<=2,!0)}),(0,t.t6)("SPC:baseline_roundtrip",async()=>{const e=await Promise.resolve().then(n.bind(n,883)),o=Be();try{const n={instrument_id:"Q-rt",locked_at:(new Date).toISOString(),included_run_ids:["uuid-a","uuid-b"],excluded_run_ids:[],iteration_trace:[],metrics:{median_intensity:{mean:22.31,sd:.42},missing_pct:{mean:12.6,sd:1.1},control_corr:{mean:.94,sd:.018},protein_count:{mean:4820,sd:145}},rules_enabled:{median_intensity:{nelson_1:!0,nelson_5:!0},missing_pct:{nelson_1:!0,nelson_5:!0},control_corr:{nelson_1:!0,nelson_5:!0},protein_count:{nelson_1:!0,nelson_5:!0}}};await e.saveBaseline("Q-rt",n,{root:o});const r=await e.loadBaseline("Q-rt",{root:o});(0,t.E3)(r.metrics.median_intensity.mean,22.31),(0,t.E3)(r.included_run_ids[0],"uuid-a")}finally{await Ue(o)}}),(0,t.t6)("SPC:baseline_rebuild_overwrites",async()=>{const e=await Promise.resolve().then(n.bind(n,883)),o=Be();try{const n={instrument_id:"Q-X",locked_at:"A",included_run_ids:["1"],excluded_run_ids:[],iteration_trace:[],metrics:{},rules_enabled:{}},r={instrument_id:"Q-X",locked_at:"B",included_run_ids:["2"],excluded_run_ids:[],iteration_trace:[],metrics:{},rules_enabled:{}};await e.saveBaseline("Q-X",n,{root:o}),await e.saveBaseline("Q-X",r,{root:o});const s=await e.loadBaseline("Q-X",{root:o});(0,t.E3)(s.locked_at,"B"),(0,t.E3)(s.included_run_ids[0],"2")}finally{await Ue(o)}}),(0,t.t6)("SPC:rule_toggle_per_instrument",async()=>{const e=await Promise.resolve().then(n.bind(n,883)),o=Be();try{const n={instrument_id:"Q-rt",locked_at:"X",included_run_ids:[],excluded_run_ids:[],iteration_trace:[],metrics:{},rules_enabled:{median_intensity:{nelson_1:!0,nelson_5:!1,nelson_2:!0},missing_pct:{nelson_1:!0,nelson_5:!0},control_corr:{nelson_1:!0,nelson_5:!0},protein_count:{nelson_1:!0,nelson_5:!0}}};await e.saveBaseline("Q-rt",n,{root:o});const r=await e.loadBaseline("Q-rt",{root:o});(0,t.E3)(r.rules_enabled.median_intensity.nelson_5,!1),(0,t.E3)(r.rules_enabled.median_intensity.nelson_2,!0)}finally{await Ue(o)}}),(0,t.t6)("SPC:run_meta_helpers",async()=>{const{setRunMeta:o,getRunMeta:r}=await Promise.resolve().then(n.bind(n,655)),s=e.DataFrame.create(),a={instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z"};o(s,a),(0,t.E3)(JSON.stringify(r(s)),JSON.stringify(a))}),(0,t.t6)("SPC:annotation_dialog_persists_run_meta",async()=>{const o=await Promise.resolve().then(n.bind(n,252)),r=e.DataFrame.fromColumns([e.Column.fromFloat32Array("log2(c1)",new Float32Array([1,2,3])),e.Column.fromFloat32Array("log2(t1)",new Float32Array([4,5,6]))]);r.col("log2(c1)").semType="Proteomics-Intensity",r.col("log2(t1)").semType="Proteomics-Intensity",(0,t.E3)(typeof o.applyAnnotation,"function"),o.applyAnnotation(r,{group1:{name:"Control",columns:["log2(c1)"]},group2:{name:"Treatment",columns:["log2(t1)"]},runMeta:{instrument_id:"Q-99",acquisition_datetime:"2026-08-01T00:00:00.000Z"}});const s=r.getTag("proteomics.spc_run_meta");(0,t.E3)(typeof s,"string");const a=JSON.parse(s);(0,t.E3)(a.instrument_id,"Q-99"),(0,t.E3)(a.acquisition_datetime,"2026-08-01T00:00:00.000Z")}),(0,t.t6)("SPC:spectronaut_seed",async()=>{const e=await Promise.resolve().then(n.bind(n,53)),o={headerCsv:["PG.ProteinGroups\tR.Condition\tR.Replicate\tPG.Quantity\tEG.Qvalue\tR.FileName\tPG.Organisms\tR.RunDate\tR.InstrumentMethod",`P00001\tCtrl\t1\t1000\t0.001\trun1.raw\tHuman\t${r="2026-07-10T00:00:00.000Z"}\t${s="QExactive-01"}`,`P00002\tCtrl\t1\t2000\t0.002\trun1.raw\tHuman\t${r}\t${s}`].join("\n"),expectedSeed:{instrument_id:s,acquisition_datetime:r}};var r,s;const a=(await e.parseSpectronautText(o.headerCsv)).getTag("proteomics.spc_run_meta_seed");(0,t.E3)(typeof a,"string");const i=JSON.parse(a);(0,t.E3)(i.instrument_id,o.expectedSeed.instrument_id),(0,t.E3)(i.acquisition_datetime,o.expectedSeed.acquisition_datetime)}),(0,t.t6)("SPC:backfill_ordering",async()=>{const e=await Promise.resolve().then(n.bind(n,883)),o=Be();try{await e.upsertRun({run_id:"a",instrument_id:"Q-01",acquisition_datetime:"2026-07-20T00:00:00.000Z",run_label:"r-20",median_intensity:1,missing_pct:1,control_corr:1,protein_count:1,status:"pass",rules_tripped:[],source_project_id:null,source_df_name:"a",computed_at:(new Date).toISOString()},{root:o}),await e.upsertRun({run_id:"b",instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z",run_label:"r-10",median_intensity:1,missing_pct:1,control_corr:1,protein_count:1,status:"pass",rules_tripped:[],source_project_id:null,source_df_name:"b",computed_at:(new Date).toISOString()},{root:o}),await e.upsertRun({run_id:"c",instrument_id:"Q-01",acquisition_datetime:"2026-07-15T00:00:00.000Z",run_label:"r-15",median_intensity:1,missing_pct:1,control_corr:1,protein_count:1,status:"pass",rules_tripped:[],source_project_id:null,source_df_name:"c",computed_at:(new Date).toISOString()},{root:o});const n=await e.loadRuns("Q-01",{root:o});(0,t.E3)(n.length,3),(0,t.E3)(n[0].acquisition_datetime,"2026-07-10T00:00:00.000Z"),(0,t.E3)(n[1].acquisition_datetime,"2026-07-15T00:00:00.000Z"),(0,t.E3)(n[2].acquisition_datetime,"2026-07-20T00:00:00.000Z")}finally{await Ue(o)}},{skipReason:"Quarantined: userDataStorage write/read consistency — 3 sequential upserts read back 2 on newer Datagrok runtime — see BACKLOG"}),(0,t.t6)("SPC:candidates_refuse",async()=>{const o=await Promise.resolve().then(n.bind(n,655)),r=e.DataFrame.create(1);r.setTag("proteomics.source","spectronaut-candidates"),(0,t.E3)(typeof o.assertSpcEligible,"function");let s=!1,a="";try{o.assertSpcEligible(r)}catch(e){s=!0,a=String(e&&e.message?e.message:e)}(0,t.E3)(s,!0),(0,t.E3)(a.indexOf("SPC requires per-sample intensities")>=0,!0)}),(0,t.t6)("SPC:idempotent_upsert",async()=>{const e=await Promise.resolve().then(n.bind(n,883)),o=Be();try{const n={run_id:"r1",instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z",run_label:"first-call",median_intensity:22.31,missing_pct:12.6,control_corr:.94,protein_count:4820,status:"pass",rules_tripped:[],source_project_id:null,source_df_name:"first-call",computed_at:(new Date).toISOString()};await e.upsertRun(n,{root:o}),await e.upsertRun({...n,run_label:"second-call",median_intensity:23},{root:o});const r=await e.loadRuns("Q-01",{root:o});(0,t.E3)(r.length,1),(0,t.E3)(r[0].run_label,"second-call"),(0,t.E3)(r[0].median_intensity,23)}finally{await Ue(o)}}),(0,t.t6)("SPC:storage_bounded",async()=>{const e=await Promise.resolve().then(n.bind(n,883)),o=Be();try{for(let t=1;t<=2;t++)for(let n=0;n<52;n++){const r=String(1+n%28).padStart(2,"0"),s=String(1+Math.floor(n/4)%12).padStart(2,"0");await e.upsertRun({run_id:`i${t}-w${n}`,instrument_id:`Q-0${t}`,acquisition_datetime:`2026-${s}-${r}T00:00:00.000Z`,run_label:`wk${n}`,median_intensity:22,missing_pct:12,control_corr:.9,protein_count:4e3,status:"pass",rules_tripped:[],source_project_id:null,source_df_name:`wk${n}`,computed_at:(new Date).toISOString()},{root:o})}const n=await e.loadRuns("Q-01",{root:o}),r=await e.loadRuns("Q-02",{root:o});(0,t.E3)(n.length<=52,!0),(0,t.E3)(r.length<=52,!0)}finally{await Ue(o)}}),(0,t.t6)("SPC:schema_version",async()=>{const e=await Promise.resolve().then(n.bind(n,883)),o=Be();try{await e.upsertRun({run_id:"r1",instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z",run_label:"r",median_intensity:1,missing_pct:1,control_corr:1,protein_count:1,status:"pass",rules_tripped:[],source_project_id:null,source_df_name:"r",computed_at:(new Date).toISOString()},{root:o});const n=await e.readRunsMeta({root:o});(0,t.E3)(n["spc.runs.schema_version"],"1")}finally{await Ue(o)}}),(0,t.t6)("SPC:column_idempotent",async()=>{const o=await Promise.resolve().then(n.bind(n,655)),r=e.DataFrame.fromColumns([e.Column.fromFloat32Array("log2(s1)",new Float32Array([10,11,12])),e.Column.fromFloat32Array("log2(s2)",new Float32Array([11,12,13]))]);r.col("log2(s1)").semType="Proteomics-Intensity",r.col("log2(s2)").semType="Proteomics-Intensity";const s={group1:{name:"Control",columns:["log2(s1)"]},group2:{name:"Treatment",columns:["log2(s2)"]}},a={instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z"},i=o.computeSpcMetrics(r,s,a);o.setSpcStatus(r,i,{status:"pass",rulesTripped:[]});const l=r.columns.length,c=o.computeSpcMetrics(r,s,a);o.setSpcStatus(r,c,{status:"pass",rulesTripped:[]}),(0,t.E3)(r.columns.length,l)}),(0,t.t6)("SPC:belt_and_braces",async()=>{const o=await Promise.resolve().then(n.bind(n,655)),r=e.DataFrame.fromColumns([e.Column.fromFloat32Array("log2(s1)",new Float32Array([10,11,12])),e.Column.fromFloat32Array("log2(s2)",new Float32Array([11,12,13]))]);r.col("log2(s1)").semType="Proteomics-Intensity",r.col("log2(s2)").semType="Proteomics-Intensity";const s=o.computeSpcMetrics(r,{group1:{name:"Control",columns:["log2(s1)"]},group2:{name:"Treatment",columns:["log2(s2)"]}},{instrument_id:"Q-01",acquisition_datetime:"2026-07-10T00:00:00.000Z"});o.setSpcStatus(r,s,{status:"pass",rulesTripped:[]});const a=r.col("~spc_metrics_meta");(0,t.E3)(null!==a,!0),r.setTag("proteomics.spc_metrics",""),(0,t.E3)(typeof o.recoverSpcMetricsFromColumn(r),"object")}),(0,t.t6)("SPC:drilldown_resolved",async()=>{const e=await Promise.resolve().then(n.bind(n,589)),o=await e.resolveDrillDown({run_id:"r1",instrument_id:"Q-01",source_project_id:"proj-abc",run_label:"r-abc"},{projectsFind:async e=>({id:e,open:()=>"opened:"+e})});(0,t.E3)(o.kind,"opened"),(0,t.E3)(o.id,"proj-abc")}),(0,t.t6)("SPC:drilldown_missing",async()=>{const e=await Promise.resolve().then(n.bind(n,589)),o=await e.resolveDrillDown({run_id:"r2",instrument_id:"Q-01",source_project_id:null,run_label:"r-zzz"},{projectsFind:async e=>null});(0,t.E3)(o.kind,"toast"),(0,t.E3)(o.message.indexOf("Source for")>=0,!0),(0,t.E3)(o.message.indexOf("r-zzz")>=0,!0)}),(0,t.t6)("SPC:dashboard_renders",async()=>{const o=await Promise.resolve().then(n.bind(n,589)),r=function(t){if(0===t.length)return e.DataFrame.create(0);const n=Object.keys(t[0]),o=[];for(const r of n){const n=t.map(e=>e[r]);"number"==typeof n.find(e=>null!=e)?o.push(e.Column.fromList(e.COLUMN_TYPE.FLOAT,r,n.map(e=>e??null))):o.push(e.Column.fromStrings(r,n.map(e=>null==e?"":String(e))))}return e.DataFrame.fromColumns(o)}([{run_id:"1",instrument_id:"Q-01",acquisition_datetime:"2026-07-01T00:00:00.000Z",run_label:"r1",median_intensity:22,missing_pct:12,control_corr:.9,protein_count:4800,status:"pass",source_project_id:null,source_df_name:"r1",computed_at:"X"},{run_id:"2",instrument_id:"Q-01",acquisition_datetime:"2026-07-08T00:00:00.000Z",run_label:"r2",median_intensity:22.5,missing_pct:12.2,control_corr:.93,protein_count:4810,status:"pass",source_project_id:null,source_df_name:"r2",computed_at:"X"}]),s=o.createSpcChartPanel(r,{metrics:{median_intensity:{mean:22.3,sd:.5},missing_pct:{mean:12,sd:1},control_corr:{mean:.92,sd:.02},protein_count:{mean:4800,sd:100}}},"median_intensity");(0,t.E3)(null!=s,!0)}),(0,t.t6)("SPC:formula_lines",async()=>{const e=(await Promise.resolve().then(n.bind(n,589))).computeControlLines({metrics:{median_intensity:{mean:22.3,sd:.5}}},"median_intensity");(0,t.E3)(e.ucl,23.8),(0,t.E3)(e.cl,22.3),(0,t.E3)(e.lcl,20.8)}),(0,t.t6)("SPC:pareto_descending",async()=>{const e=(await Promise.resolve().then(n.bind(n,589))).aggregateParetoCounts([{rules_tripped:["nelson_1@median_intensity","nelson_5@control_corr"]},{rules_tripped:["nelson_1@median_intensity"]},{rules_tripped:["nelson_1@median_intensity","nelson_5@control_corr"]},{rules_tripped:[]}]);(0,t.E3)(e.length>=2,!0);for(let n=1;n<e.length;n++)(0,t.E3)(e[n-1].count>=e[n].count,!0);(0,t.E3)(e[0].rule+"@"+e[0].metric,"nelson_1@median_intensity"),(0,t.E3)(e[0].count,3)}),t.bk,t.cb});const je=new e.Package;async function Ve(n,o,r){const s=await(0,t.N$)({category:n,test:o,testContext:r});return e.DataFrame.fromObjects(s)}async function qe(){await(0,t.Xb)(je,je.getModule("package-test.js"))}})(),proteomics_test=o})();
|
|
2
2
|
//# sourceMappingURL=package-test.js.map
|