Spaces:
Running
Running
Download index.html from fightglory/FilmingNemo: direct link, hf CLI and curl.
- Browser
- Download file 74.3 kB
-
https://huggingface.co/spaces/fightglory/FilmingNemo/resolve/main/index.html
- Command line
-
hf download hf://spaces/fightglory/FilmingNemo/index.html
-
curl -L -o index.html https://huggingface.co/spaces/fightglory/FilmingNemo/resolve/main/index.html
74.3 kB
| <html lang="en"> | |
| <head> | |
| <meta charset="utf-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1"> | |
| <title>From a video to a decision you can explain</title> | |
| <link rel="preconnect" href="https://fonts.googleapis.com"> | |
| <link href="https://fonts.googleapis.com/css2?family=Atkinson+Hyperlegible:wght@400;700&display=swap" rel="stylesheet"> | |
| <style> | |
| :root{--bg:#EDF0EF;--surface:#FFFFFF;--ink:#14202B;--muted:#586672;--line:#D3DAD9;--a:#0F8087;--b:#D2700A;--act:#3B3FB5;--act-ink:#FFFFFF;--stage:#0E1620;--stage-ink:#DCE6EA;--soft:#E3E8E7;color-scheme:light} | |
| @media (prefers-color-scheme:dark){:root{--bg:#0B1117;--surface:#131C25;--ink:#E4EBEE;--muted:#93A1AB;--line:#27333E;--a:#3BB8BF;--b:#F0A03C;--act:#9A9DF7;--act-ink:#0B1117;--stage:#060A0F;--stage-ink:#DCE6EA;--soft:#1B2630;color-scheme:dark}} | |
| *{box-sizing:border-box} | |
| html{-webkit-text-size-adjust:100%} | |
| body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.5 "Atkinson Hyperlegible","Segoe UI",system-ui,-apple-system,Roboto,Helvetica,Arial,sans-serif} | |
| h1,h2,h3,p{margin:0} | |
| button,select,input{font:inherit;color:inherit} | |
| :focus-visible{outline:3px solid var(--act);outline-offset:2px} | |
| .top{padding:20px clamp(14px,4vw,40px) 0;max-width:1240px;margin:0 auto} | |
| .top h1{font-size:clamp(1.5rem,3.4vw,2.3rem);line-height:1.1;letter-spacing:-.02em;font-weight:700} | |
| .top .sub{color:var(--muted);margin-top:6px;max-width:62ch} | |
| .tabs{display:grid;grid-template-columns:repeat(4,minmax(150px,1fr));gap:0;margin-top:18px;overflow-x:auto;border-bottom:2px solid var(--ink)} | |
| .tabs button{appearance:none;border:0;background:none;text-align:left;padding:10px 14px 12px;cursor:pointer;border-radius:8px 8px 0 0;display:grid;grid-template-columns:auto 1fr;column-gap:10px;align-items:baseline;min-width:150px} | |
| .tabs button .n{font-weight:700;font-size:1.5rem;line-height:1;color:var(--muted);font-variant-numeric:tabular-nums} | |
| .tabs button .t{font-weight:700} | |
| .tabs button .q{grid-column:2;font-size:.85rem;color:var(--muted);line-height:1.25} | |
| .tabs button[aria-selected=true]{background:var(--ink);color:var(--bg)} | |
| .tabs button[aria-selected=true] .n,.tabs button[aria-selected=true] .q{color:inherit;opacity:.8} | |
| main{max-width:1240px;margin:0 auto;padding:22px clamp(14px,4vw,40px) 60px} | |
| .panel[hidden]{display:none} | |
| .lead{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:18px 40px;align-items:start;margin-bottom:20px} | |
| .lead h2{font-size:clamp(1.25rem,2.4vw,1.7rem);line-height:1.15;letter-spacing:-.01em;margin-bottom:10px} | |
| .lead p{max-width:68ch} | |
| .lead p+p{margin-top:6px} | |
| .lead b{font-weight:700} | |
| .pipe{list-style:none;margin:4px 0 0;padding:0;display:flex;flex-wrap:wrap;gap:4px;font-size:.82rem;color:var(--muted);max-width:330px} | |
| .pipe li{padding:3px 9px;border:1px solid var(--line);border-radius:99px;white-space:nowrap} | |
| .pipe li.on{background:var(--act);border-color:var(--act);color:var(--act-ink);font-weight:700} | |
| .pipe-cap{font-size:.82rem;color:var(--muted);margin-bottom:4px} | |
| .grid2{display:grid;grid-template-columns:minmax(0,1.35fr) minmax(0,1fr);gap:16px} | |
| .grid2.even{grid-template-columns:minmax(0,1fr) minmax(0,1fr)} | |
| .box{background:var(--surface);border:1px solid var(--line);border-radius:10px;padding:14px} | |
| .box h3{font-size:1rem;margin-bottom:8px} | |
| .stage{background:var(--stage);border-radius:10px;overflow:hidden;position:relative;color:var(--stage-ink)} | |
| .stage canvas{display:block;width:100%} | |
| .stage .tag{position:absolute;left:10px;top:8px;font-size:.85rem;font-weight:700;padding:2px 8px;border-radius:99px;background:rgba(255,255,255,.12)} | |
| canvas{display:block;width:100%} | |
| .controls{display:flex;flex-wrap:wrap;gap:12px 20px;align-items:end;margin:14px 0} | |
| .ctl{display:grid;gap:3px;font-size:.88rem;min-width:150px} | |
| .ctl span{color:var(--muted)} | |
| .ctl output{color:var(--ink);font-weight:700;font-variant-numeric:tabular-nums} | |
| input[type=range]{width:100%;accent-color:var(--act)} | |
| select{background:var(--surface);border:1px solid var(--line);border-radius:7px;padding:7px 9px;max-width:100%} | |
| .btn{appearance:none;border:1.5px solid var(--ink);background:var(--surface);border-radius:8px;padding:8px 14px;font-weight:700;cursor:pointer} | |
| .btn:hover{background:var(--soft)} | |
| .btn.go{background:var(--act);border-color:var(--act);color:var(--act-ink);font-size:1.05rem;padding:9px 20px;letter-spacing:.02em} | |
| .btn.go:hover{filter:brightness(1.1)} | |
| .btn:disabled{opacity:.5;cursor:default} | |
| .btn.file{position:relative;overflow:hidden;display:inline-block} | |
| .btn.file input{position:absolute;inset:0;opacity:0;cursor:pointer} | |
| .row{display:flex;flex-wrap:wrap;gap:8px;align-items:center} | |
| .check{display:inline-flex;gap:6px;align-items:center;font-size:.9rem} | |
| .stat{font-variant-numeric:tabular-nums;font-size:.95rem} | |
| .stat b{font-size:1.15rem} | |
| .note{font-size:.88rem;color:var(--muted);max-width:75ch} | |
| .legend{display:flex;gap:14px;font-size:.85rem;color:var(--muted);flex-wrap:wrap;margin-top:8px} | |
| .dot{display:inline-block;width:10px;height:10px;border-radius:50%;vertical-align:-1px;margin-right:5px} | |
| .dot.a{background:var(--a)}.dot.b{background:var(--b)} | |
| .forest{display:flex;flex-wrap:wrap;gap:4px;align-items:center;min-height:46px;margin-top:6px} | |
| .forest button{appearance:none;border:1.5px solid transparent;background:var(--soft);border-radius:7px;padding:2px;cursor:pointer;width:44px;height:40px;animation:pop .35s cubic-bezier(.2,1.6,.4,1)} | |
| .forest button[aria-pressed=true]{border-color:var(--act)} | |
| .forest svg{display:block;width:100%;height:100%} | |
| .forest .plus{color:var(--muted);font-weight:700} | |
| @keyframes pop{from{transform:scale(.2) translateY(-14px);opacity:0}to{transform:none;opacity:1}} | |
| table{border-collapse:collapse;width:100%;font-size:.9rem} | |
| th,td{text-align:left;padding:6px 8px;border-bottom:1px solid var(--line);vertical-align:middle} | |
| th{font-weight:700;color:var(--muted);font-size:.82rem} | |
| td.num{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap} | |
| tr.grp td{font-weight:700;background:var(--soft);border-bottom:0} | |
| tbody tr.f{cursor:pointer} | |
| tbody tr.f:hover{background:var(--soft)} | |
| tbody tr.f[aria-selected=true]{background:var(--act);color:var(--act-ink)} | |
| .bars{display:grid;gap:2px;width:70px} | |
| .bars i{display:block;height:5px;border-radius:3px;min-width:2px} | |
| .bars i.a{background:var(--a)}.bars i.b{background:var(--b)} | |
| .tablewrap{max-height:520px;overflow:auto} | |
| .tiles{display:grid;gap:3px} | |
| .tilerow{display:grid;grid-template-columns:minmax(90px,170px) 1fr;gap:8px;align-items:center;font-size:.8rem;color:var(--muted)} | |
| .tilerow .cells{display:grid;gap:3px} | |
| .tile{appearance:none;border:0;padding:0;aspect-ratio:1;min-width:14px;border-radius:4px;background:var(--soft);cursor:pointer;position:relative;font-size:.72rem;font-weight:700;color:var(--act-ink);overflow:hidden} | |
| .tile::before{content:"";position:absolute;inset:0;background:var(--act);opacity:var(--heat,0);transition:opacity .35s} | |
| .tile span{position:relative} | |
| .tile.cand{outline:2px solid var(--ink);outline-offset:1px;animation:pulse .5s 2} | |
| .tile.sel{background:var(--b)} | |
| .tile.sel::before{opacity:0} | |
| .tile.rej{outline:2px dashed var(--muted);outline-offset:1px} | |
| @keyframes pulse{50%{transform:scale(1.25)}} | |
| .cases{display:flex;flex-wrap:wrap;gap:3px;align-items:center;min-height:22px} | |
| .cases i{display:block;width:10px;height:10px;border-radius:50%;transition:transform .4s} | |
| .cases i.a{background:var(--a)}.cases i.b{background:var(--b)} | |
| .sellist{margin:0;padding-left:1.3em} | |
| .sellist li{margin-bottom:6px} | |
| .sellist small{display:block;color:var(--muted)} | |
| details.try{margin-top:18px;border-top:1px solid var(--line);padding-top:10px} | |
| details.try summary{font-weight:700;cursor:pointer} | |
| details.try ul{margin:8px 0 0;padding-left:1.2em;max-width:75ch} | |
| details.try li{margin-bottom:4px} | |
| footer{max-width:1240px;margin:0 auto;padding:0 clamp(14px,4vw,40px) 40px;color:var(--muted);font-size:.85rem} | |
| @media (max-width:860px){.grid2,.grid2.even,.lead{grid-template-columns:minmax(0,1fr)}.tabs{grid-template-columns:repeat(4,minmax(170px,1fr))}.pipe{max-width:none}} | |
| @media (prefers-reduced-motion:reduce){.forest button,.tile.cand{animation:none}.tile::before,.cases i{transition:none}} | |
| </style> | |
| </head> | |
| <body> | |
| <header class="top"> | |
| <h1>FilmingNEMO</h1> | |
| <p class="sub">This is a collection of interactive examples of each part of my project. Theoretically, you're following along my explanation. In practice, feel free to press Things (tm).</p> | |
| <nav class="tabs" role="tablist" aria-label="Exhibits"> | |
| <button role="tab" id="t-xgboost" data-tab="xgboost"><span class="n">1</span><span class="t">XGBoost</span><span class="q">The Power of 2</span></button> | |
| <button role="tab" id="t-mediapipe" data-tab="mediapipe"><span class="n">2</span><span class="t">MediaPipe</span><span class="q">I hate video</span></button> | |
| <button role="tab" id="t-features" data-tab="features"><span class="n">3</span><span class="t">TSFresh / PySPI</span><span class="q">Explainability not included</span></button> | |
| <button role="tab" id="t-featboost" data-tab="featboost"><span class="n">4</span><span class="t">FeatBoost</span><span class="q">I'm not reading all that</span></button> | |
| </nav> | |
| </header> | |
| <main> | |
| <!-- ===================== 1 XGBOOST ===================== --> | |
| <section class="panel" id="p-xgboost" role="tabpanel" aria-labelledby="t-xgboost"> | |
| <div class="lead"> | |
| <div> | |
| <h2>The Power of 2 (but many times)</h2> | |
| <p><b>Decide this.</b> By combining many different yes/no questions, chosen based on some metric, we can classify really complex entries.</p> | |
| <p><b>Problem.</b> Data is complex and messy. Rarely does a single metric capture the interplay of different deciding factors, which can lead to a model generalizing poorly. To help with this, we can use multiple trees! | |
| By making the trees vote, then we have a much more robust solution. Additionally, we can BOOST.</p> | |
| </div> | |
| <div><p class="pipe-cap">You are here</p> | |
| <ol class="pipe"><li>Video</li><li>MediaPipe</li><li>TSFresh / PySPI</li><li>FeatBoost</li><li class="on">XGBoost</li></ol></div> | |
| </div> | |
| <div class="grid2"> | |
| <div class="box"> | |
| <h3 id="xgTreeTitle">Tree 1</h3> | |
| <canvas id="xgTree" style="height:440px" aria-label="Decision tree with one ball per case falling to a leaf"></canvas> | |
| <div class="legend"><span><i class="dot a"></i>Group A</span><span><i class="dot b"></i>Group B</span><span>Bigger ball = the trees so far are more wrong about this case</span></div> | |
| </div> | |
| <div class="box"> | |
| <h3>What all trees together say</h3> | |
| <canvas id="xgMap" style="aspect-ratio:1" aria-label="Map of the two measurements with the model's decision shaded"></canvas> | |
| <p class="stat" style="margin-top:8px" id="xgStats"></p> | |
| </div> | |
| </div> | |
| <div class="controls"> | |
| <button class="btn go" id="xgBoost">BOOST</button> | |
| <button class="btn" id="xgBoost10">Boost × 10</button> | |
| <button class="btn" id="xgDrop">Drop the cases again</button> | |
| <button class="btn" id="xgReset">Start over</button> | |
| <label class="ctl"><span>Pattern in the data</span> | |
| <select id="xgData"><option value="cut">Easy</option><option value="diag" selected>Medium</option><option value="spot">Hard</option></select></label> | |
| <label class="ctl"><span>Randomness <output id="xgNoiseO"></output></span><input type="range" id="xgNoise" min="0" max="0.3" step="0.01" value="0.05"></label> | |
| <label class="ctl"><span>Questions per tree <output id="xgDepthO"></output></span><input type="range" id="xgDepth" min="1" max="3" step="1" value="2"></label> | |
| <label class="ctl"><span>Regularization <output id="xgLrO"></output></span><input type="range" id="xgLr" min="0.1" max="1" step="0.1" value="0.5"></label> | |
| </div> | |
| <div class="box"> | |
| <h3>The forest so far <span class="note">(click a tree to look inside it)</span></h3> | |
| <div class="forest" id="xgForest"></div> | |
| </div> | |
| <details class="try" open><summary>Try this</summary><ul> | |
| <li>Pressing BOOST (this means create a tree that tries to get right what the previous got wrong).</li> | |
| <li>Make a more complex (more questions) tree, and make a lot of them. Can you think of any problems with this? We call this overfitting.</li> | |
| <li>Even in difficult cases, notice that you can get pretty good results very quickly.</li> | |
| </ul></details> | |
| </section> | |
| <!-- ===================== 2 MEDIAPIPE ===================== --> | |
| <section class="panel" id="p-mediapipe" role="tabpanel" aria-labelledby="t-mediapipe" hidden> | |
| <div class="lead"> | |
| <div> | |
| <h2>I HATE VIDEO</h2> | |
| <p><b>Problem.</b> Video sucks. It's large, and messy, and requires a lot of data. Instead, how about we use deep learning to not have to deal with it?</p> | |
| <p><b>Answer.</b> A pose model that was already trained on a very large number of people finds the body's keypoints in every frame. What is left is a set of keypoints over time that describe movement and nothing else.</p> | |
| </div> | |
| <div><p class="pipe-cap">You are here</p> | |
| <ol class="pipe"><li>Video</li><li class="on">MediaPipe</li><li>TSFresh / PySPI</li><li>FeatBoost</li><li>XGBoost</li></ol></div> | |
| </div> | |
| <div class="row" style="margin-bottom:12px"> | |
| <button class="btn" id="mpCam">Use my camera</button> | |
| <label class="btn file">Upload a video<input type="file" id="mpVidFile" accept="video/*"></label> | |
| <label class="btn file">Upload a picture<input type="file" id="mpImgFile" accept="image/*"></label> | |
| <button class="btn" id="mpDemo">Synthetic figure</button> | |
| <span class="note" id="mpStatus" role="status"></span> | |
| </div> | |
| <div class="grid2"> | |
| <div> | |
| <div class="stage"><canvas id="mpStage" width="640" height="480"></canvas><span class="tag" id="mpTag">Synthetic figure</span></div> | |
| <div class="row" style="margin-top:10px"> | |
| <label class="check"><input type="checkbox" id="mpShowVideo" checked> Show the picture behind the skeleton</label> | |
| <label class="check"><input type="checkbox" id="mpTrails" checked> Leave trails</label> | |
| </div> | |
| <p class="note" style="margin-top:8px">This is a real MediaPipe model running on your device!</p> | |
| </div> | |
| <div class="box"> | |
| <h3>One keypoint over the last 8 seconds</h3> | |
| <label class="ctl" style="margin-bottom:8px"><span>Keypoint</span><select id="mpKp"></select></label> | |
| <canvas id="mpChart" style="height:230px"></canvas> | |
| <div class="legend"><span><i class="dot a"></i>side to side (x)</span><span><i class="dot b"></i>up–down (y)</span></div> | |
| <p class="stat" id="mpCount" style="margin-top:12px"></p> | |
| <div id="mpDemoCtl" class="controls" style="margin-bottom:0"> | |
| <label class="ctl"><span>Tremor<output id="mpTremO"></output></span><input type="range" id="mpTrem" min="0" max="0.2" step="0.01" value="0.04"></label> | |
| <label class="ctl"><span>Irregularity <output id="mpIrrO"></output></span><input type="range" id="mpIrr" min="0" max="1" step="0.05" value="0.2"></label> | |
| </div> | |
| <div class="row" style="margin-top:12px"><button class="btn go" id="mpRec">Record a clip</button><span class="note" id="mpRecStatus" role="status"></span></div> | |
| </div> | |
| </div> | |
| <details class="try" open><summary>Try this</summary><ul> | |
| <li>Try coming close and far from the camera. MediaPipe does better and worse in some scenarios.</li> | |
| <li>Get multiple people in the frame and watch chaos ensue.</li> | |
| <li>Try an oscillatory movement, and try to identify it in the chart.</li> | |
| </ul></details> | |
| </section> | |
| <!-- ===================== 3 FEATURES ===================== --> | |
| <section class="panel" id="p-features" role="tabpanel" aria-labelledby="t-features" hidden> | |
| <div class="lead"> | |
| <div> | |
| <h2>Raw movement sucks, actually</h2> | |
| <p><b>The Black Box.</b> If you feed this data directly into XGBoost, what you will learn is coordinates: In a certain second, the hand is moving here. Imagine hundreds of questions asking this. | |
| This doesn't actually tell you anything about the movement. </p> | |
| <p><b>Feature Generators.</b> Instead, we can pre-process this data by transforming it into mathematical measurements with inherent meaning. We use two: TSFresh describes one keypoint at a time. PySPI describes how two keypoints relate. Every clip becomes one row of numbers, each with a meaning you can look up.</p> | |
| </div> | |
| <div><p class="pipe-cap">You are here</p> | |
| <ol class="pipe"><li>Video</li><li>MediaPipe</li><li class="on">TSFresh / PySPI</li><li>FeatBoost</li><li>XGBoost</li></ol></div> | |
| </div> | |
| <div class="grid2 even"> | |
| <div><div class="stage"><canvas id="tsA" style="aspect-ratio:4/3"></canvas><span class="tag" style="background:var(--a);color:#fff">Clip A</span></div> | |
| <label class="ctl" style="margin-top:8px"><span>Clip A shows</span><select id="tsSelA"></select></label></div> | |
| <div><div class="stage"><canvas id="tsB" style="aspect-ratio:4/3"></canvas><span class="tag" style="background:var(--b);color:#fff">Clip B</span></div> | |
| <label class="ctl" style="margin-top:8px"><span>Clip B shows</span><select id="tsSelB"></select></label></div> | |
| </div> | |
| <div class="controls"> | |
| <label class="ctl"><span>Tremor size (irregular clip) <output id="tsTremO"></output></span><input type="range" id="tsTrem" min="0" max="0.2" step="0.01" value="0.08"></label> | |
| <label class="ctl"><span>Tremor speed <output id="tsFreqO"></output></span><input type="range" id="tsFreq" min="3" max="9" step="0.5" value="5"></label> | |
| <label class="ctl"><span>Irregularity <output id="tsIrrO"></output></span><input type="range" id="tsIrr" min="0" max="1" step="0.05" value="0.55"></label> | |
| <label class="ctl"><span>One keypoint (TSFresh)</span><select id="tsSignal"></select></label> | |
| <label class="ctl"><span>Two keypoints (PySPI)</span><select id="tsPair"></select></label> | |
| </div> | |
| <div class="grid2 even"> | |
| <div class="box"><div class="tablewrap"><table> | |
| <thead><tr><th>Measure</th><th style="text-align:right">Clip A</th><th style="text-align:right">Clip B</th><th></th></tr></thead> | |
| <tbody id="tsTable"></tbody></table></div> | |
| <p class="note" style="margin-top:8px">This is a small subset of measures. In reality, I use ~1000 per keypoint, per task.</p></div> | |
| <div class="box"> | |
| <h3 id="tsDetailTitle"></h3> | |
| <p id="tsDetailText" style="margin-bottom:10px"></p> | |
| <canvas id="tsDetail" style="height:340px"></canvas> | |
| </div> | |
| </div> | |
| </section> | |
| <!-- ===================== 4 FEATBOOST ===================== --> | |
| <section class="panel" id="p-featboost" role="tabpanel" aria-labelledby="t-featboost" hidden> | |
| <div class="lead"> | |
| <div> | |
| <h2>Okay, now read 100,000 entries bozo</h2> | |
| <p><b>Explainable isn't actually explainable.</b> Silly you, you've now generated several hundreds of thousands of decision points that XGBoost has used happily. This, while technically explainable, is a pain for you and the model to decide through.</p> | |
| <p><b>BOOST IT.</b> We can make use of the same principle that XGBoost uses to select features: We train, then we pick the best feature. Then, we train again but increasing the weight of the things we got wrong before. We do this until we stop improving, and then we have a set of features we can use. This cuts about 99% of features!</p> | |
| </div> | |
| <div><p class="pipe-cap">You are here</p> | |
| <ol class="pipe"><li>Video</li><li>MediaPipe</li><li>TSFresh / PySPI</li><li class="on">FeatBoost</li><li>XGBoost</li></ol></div> | |
| </div> | |
| <div class="controls" style="margin-top:0"> | |
| <button class="btn go" id="fbBoost">BOOST</button> | |
| <button class="btn" id="fbNew">Regenerate data</button> | |
| <label class="ctl"><span>Data points <output id="fbNO"></output></span><input type="range" id="fbN" min="15" max="60" step="5" value="40"></label> | |
| <label class="ctl"><span>Difference magnitude <output id="fbEffO"></output></span><input type="range" id="fbEff" min="0" max="1" step="0.05" value="0.5"></label> | |
| <span class="note" id="fbStatus" role="status"></span> | |
| </div> | |
| <div class="grid2"> | |
| <div class="box"> | |
| <h3>Feature list <span class="note" id="fbHover"></span></h3> | |
| <div class="tiles" id="fbGrid"></div> | |
| <div class="legend"><span><i class="dot" style="background:var(--act)"></i>Darker = the model leans on it more this round</span><span><i class="dot b"></i>Kept, in order</span></div> | |
| <h3 style="margin-top:16px">The clips <span class="note">(bigger = gets more attention next round)</span></h3> | |
| <div class="cases" id="fbCases"></div> | |
| </div> | |
| <div class="box"> | |
| <h3>Accuracy on data the model has not seen</h3> | |
| <canvas id="fbAcc" style="height:190px"></canvas> | |
| <h3 style="margin-top:14px">Best performers</h3> | |
| <ol class="sellist" id="fbList"><li class="note" style="list-style:none;margin-left:-1.3em">Nothing yet. Press BOOST.</li></ol> | |
| <canvas id="fbScatter" style="height:240px;margin-top:10px"></canvas> | |
| <p class="note" id="fbScatterNote"></p> | |
| </div> | |
| </div> | |
| <details class="try" open><summary>Try this</summary><ul> | |
| <li>Regenerate the data and BOOST. Does the same short list come back? A stable list points to some pattern in the data rather than chance.</li> | |
| <li>What happens when the data is very similar?</li> | |
| <li>Look at the star. That's you!</li> | |
| </ul></details> | |
| </section> | |
| </main> | |
| <video id="mpVideo" playsinline muted loop style="display:none"></video> | |
| <script> | |
| ; | |
| /* ================= core: data, features, boosting (no DOM) ================= */ | |
| function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296}} | |
| function randn(rng){let u=0;while(u===0)u=rng();return Math.sqrt(-2*Math.log(u))*Math.cos(6.283185307*rng())} | |
| function makeSmooth(rng,fLo,fHi,k){k=k||5;const c=[];for(let i=0;i<k;i++)c.push([fLo+(fHi-fLo)*rng(),rng()*6.283185307]);const s=Math.sqrt(2/k);return t=>{let v=0;for(let i=0;i<k;i++)v+=Math.sin(6.283185307*c[i][0]*t+c[i][1]);return v*s}} | |
| function sigmoid(z){return 1/(1+Math.exp(-z))} | |
| /* ---------- synthetic skeleton clips ---------- */ | |
| const KP=['nose','lsh','rsh','lel','rel','lwr','rwr','lhip','rhip','lkn','rkn','lank','rank']; | |
| const BONES=[['lsh','rsh'],['lsh','lel'],['lel','lwr'],['rsh','rel'],['rel','rwr'],['lsh','lhip'],['rsh','rhip'],['lhip','rhip'],['lhip','lkn'],['lkn','lank'],['rhip','rkn'],['rkn','rank']]; | |
| const BASE={nose:[.5,.17],lsh:[.6,.31],rsh:[.4,.31],lhip:[.565,.6],rhip:[.435,.6],lkn:[.57,.78],rkn:[.43,.78],lank:[.57,.95],rank:[.43,.95]}; | |
| function synthClip(p,seed,seconds,fps){ | |
| seconds=seconds||6;fps=fps||30; | |
| const P=Object.assign({amp:1.05,freq:.5,tremorAmp:0,tremorFreq:5,irregularity:0,asym:0,coupling:0,noise:.002},p||{}); | |
| const rng=mulberry32(seed||1),n=Math.round(seconds*fps); | |
| const phN=makeSmooth(rng,.1,.6),ampN=makeSmooth(rng,.1,.5),drvR=makeSmooth(rng,1,3,6),drvL=makeSmooth(rng,1,3,6),sway=makeSmooth(rng,.1,.4); | |
| const ph0=rng()*6.283,trPh=rng()*6.283; | |
| const kp={};for(const k of KP)kp[k]={x:new Float64Array(n),y:new Float64Array(n)}; | |
| const L1=.14,L2=.13,irr=P.irregularity; | |
| for(let i=0;i<n;i++){ | |
| const t=i/fps; | |
| const phase=6.283185*P.freq*t+ph0+irr*1.6*phN(t); | |
| const A=P.amp*(1+irr*.35*ampN(t)); | |
| const thR=.25+A*(.5-.5*Math.cos(phase)); | |
| const thL=.25+A*(1-.5*P.asym)*(.5-.5*Math.cos(phase-.6*P.asym)); | |
| const dR=irr*.14*drvR(t); | |
| const dL=irr*.14*(P.coupling*drvR(t-.1)+(1-P.coupling)*drvL(t)); | |
| const trR=P.tremorAmp*Math.sin(6.283185*P.tremorFreq*t+trPh); | |
| const trL=P.tremorAmp*(1-.7*P.asym)*Math.sin(6.283185*P.tremorFreq*t+trPh+.5); | |
| const phiR=.3+trR+dR,phiL=.3+trL+dL; | |
| const sw=.008*sway(t); | |
| const pos={}; | |
| for(const k in BASE)pos[k]=[BASE[k][0],BASE[k][1]]; | |
| pos.nose[0]+=sw*1.4;pos.lsh[0]+=sw;pos.rsh[0]+=sw; | |
| pos.lel=[pos.lsh[0]+L1*Math.sin(thL),pos.lsh[1]+L1*Math.cos(thL)]; | |
| pos.lwr=[pos.lel[0]+L2*Math.sin(thL+phiL),pos.lel[1]+L2*Math.cos(thL+phiL)]; | |
| pos.rel=[pos.rsh[0]-L1*Math.sin(thR),pos.rsh[1]+L1*Math.cos(thR)]; | |
| pos.rwr=[pos.rel[0]-L2*Math.sin(thR+phiR),pos.rel[1]+L2*Math.cos(thR+phiR)]; | |
| for(const k of KP){kp[k].x[i]=pos[k][0]+P.noise*randn(rng);kp[k].y[i]=pos[k][1]+P.noise*randn(rng)} | |
| } | |
| return {fps,n,kp,params:P}; | |
| } | |
| /* ---------- time-series features (tsfresh-style, re-implemented) ---------- */ | |
| function mean(x){let s=0;for(let i=0;i<x.length;i++)s+=x[i];return s/x.length} | |
| function std(x,m){if(m===undefined)m=mean(x);let s=0;for(let i=0;i<x.length;i++){const d=x[i]-m;s+=d*d}return Math.sqrt(s/x.length)} | |
| function zscore(x){const m=mean(x),s=std(x,m)||1,o=new Float64Array(x.length);for(let i=0;i<x.length;i++)o[i]=(x[i]-m)/s;return o} | |
| function diff(x){const o=new Float64Array(x.length-1);for(let i=0;i<o.length;i++)o[i]=x[i+1]-x[i];return o} | |
| function spectrum(x,fps){const n=x.length,m=mean(x),K=Math.floor(n/2),freq=[],pow=[]; | |
| for(let k=1;k<=K;k++){let re=0,im=0;const w=6.283185307*k/n;for(let i=0;i<n;i++){const v=x[i]-m;re+=v*Math.cos(w*i);im-=v*Math.sin(w*i)}freq.push(k*fps/n);pow.push((re*re+im*im)/(n*n))} | |
| return {freq,pow}} | |
| function findPeaks(x,sup){const out=[];for(let i=sup;i<x.length-sup;i++){let ok=true;for(let j=1;j<=sup&&ok;j++)if(!(x[i]>x[i-j]&&x[i]>x[i+j]))ok=false;if(ok)out.push(i)}return out} | |
| function longestAbove(x,m){let best=0,cur=0,end=0;for(let i=0;i<x.length;i++){if(x[i]>m){cur++;if(cur>best){best=cur;end=i}}else cur=0}return {len:best,i0:end-best+1,i1:end}} | |
| function sampleEntropy(x){const n=x.length,s=std(x);if(!s)return 0;const r=.2*s,m=2;let A=0,B=0; | |
| for(let i=0;i<n-m;i++)for(let j=i+1;j<n-m;j++){ | |
| if(Math.abs(x[i]-x[j])<=r&&Math.abs(x[i+1]-x[j+1])<=r){B++;if(Math.abs(x[i+2]-x[j+2])<=r)A++}} | |
| if(!A||!B)return Math.log(n);return -Math.log(A/B)} | |
| function prep(x,fps){const m=mean(x);const o={x,fps,m,s:std(x,m)};let sp=null;Object.defineProperty(o,'spec',{get(){return sp||(sp=spectrum(x,fps))}});return o} | |
| const TREMOR_BAND=[3,8],ACF_LAG=5,PEAK_SUPPORT=3; | |
| const UNI=[ | |
| {id:'mean',label:'Mean',plain:'Where is this point on average?',viz:'mean',fn:s=>s.m}, | |
| {id:'standard_deviation',label:'Standard deviation',plain:'How far does it wander from its average?',viz:'std',fn:s=>s.s}, | |
| {id:'range',label:'Range',plain:'Distance between its two extremes.',viz:'range',fn:s=>{let a=Infinity,b=-Infinity;for(const v of s.x){if(v<a)a=v;if(v>b)b=v}return b-a}}, | |
| {id:'skewness',label:'Skewness',plain:'Does it spend more time at one end than the other?',viz:'mean',fn:s=>{if(!s.s)return 0;let k=0;for(const v of s.x)k+=Math.pow((v-s.m)/s.s,3);return k/s.x.length}}, | |
| {id:'mean_abs_change',label:'Mean absolute change',plain:'How much does it move from one frame to the next?',viz:'change',fn:s=>{let k=0;for(let i=1;i<s.x.length;i++)k+=Math.abs(s.x[i]-s.x[i-1]);return k/(s.x.length-1)}}, | |
| {id:'number_peaks',label:'Number of peaks',plain:'How many times does it reach a local high point?',viz:'peaks',fn:s=>findPeaks(s.x,PEAK_SUPPORT).length}, | |
| {id:'autocorrelation',label:'Autocorrelation (lag 5)',plain:'Does it resemble itself a sixth of a second later?',viz:'acf',fn:s=>{if(!s.s)return 0;const n=s.x.length;let k=0;for(let i=0;i<n-ACF_LAG;i++)k+=(s.x[i]-s.m)*(s.x[i+ACF_LAG]-s.m);return k/((n-ACF_LAG)*s.s*s.s)}}, | |
| {id:'cid_ce',label:'Complexity (CID)',plain:'How jagged is the trace once size is ignored?',viz:'change',fn:s=>{if(!s.s)return 0;let k=0;for(let i=1;i<s.x.length;i++){const d=(s.x[i]-s.x[i-1])/s.s;k+=d*d}return Math.sqrt(k)}}, | |
| {id:'dominant_frequency',label:'Dominant frequency (Hz)',plain:'Which rhythm is strongest?',viz:'spectrum',fn:s=>{const {freq,pow}=s.spec;let b=0;for(let i=1;i<pow.length;i++)if(pow[i]>pow[b])b=i;return freq[b]}}, | |
| {id:'band_power_3_8',label:'Power in 3–8 Hz',plain:'What share of the movement is fast, tremor-like oscillation?',viz:'spectrum',fn:s=>{const {freq,pow}=s.spec;let a=0,t=0;for(let i=0;i<pow.length;i++){t+=pow[i];if(freq[i]>=TREMOR_BAND[0]&&freq[i]<=TREMOR_BAND[1])a+=pow[i]}return t?a/t:0}}, | |
| {id:'sample_entropy',label:'Sample entropy',plain:'How unpredictable is it? Low means it repeats itself.',viz:'plain',fn:s=>sampleEntropy(s.x)}, | |
| {id:'longest_strike_above_mean',label:'Longest run above mean',plain:'Longest stretch (in frames) held on one side of its average.',viz:'strike',fn:s=>longestAbove(s.x,s.m).len} | |
| ]; | |
| const SIGNALS=[ | |
| {kp:'rwr',ax:'y',label:'Right wrist, up–down'},{kp:'lwr',ax:'y',label:'Left wrist, up–down'}, | |
| {kp:'rwr',ax:'x',label:'Right wrist, side to side'},{kp:'lwr',ax:'x',label:'Left wrist, side to side'}, | |
| {kp:'rel',ax:'y',label:'Right elbow, up–down'},{kp:'lel',ax:'y',label:'Left elbow, up–down'}, | |
| {kp:'nose',ax:'x',label:'Head, side to side'},{kp:'rkn',ax:'y',label:'Right knee, up–down'} | |
| ]; | |
| /* ---------- pairwise statistics (pyspi-style, re-implemented) ---------- */ | |
| function pearson(a,b){const ma=mean(a),mb=mean(b),sa=std(a,ma),sb=std(b,mb);if(!sa||!sb)return 0;let k=0;for(let i=0;i<a.length;i++)k+=(a[i]-ma)*(b[i]-mb);return k/(a.length*sa*sb)} | |
| function xcorrLag(a,b,maxLag){maxLag=maxLag||10;const za=zscore(a),zb=zscore(b),n=a.length;let best=-Infinity,bl=0; | |
| for(let l=-maxLag;l<=maxLag;l++){let k=0,c=0;for(let i=0;i<n;i++){const j=i+l;if(j<0||j>=n)continue;k+=za[i]*zb[j];c++}k/=c;if(k>best){best=k;bl=l}} | |
| return {lag:bl,value:best}} | |
| function solve(A,b){const n=b.length;for(let i=0;i<n;i++){let p=i;for(let r=i+1;r<n;r++)if(Math.abs(A[r][i])>Math.abs(A[p][i]))p=r;[A[i],A[p]]=[A[p],A[i]];[b[i],b[p]]=[b[p],b[i]];const d=A[i][i]||1e-12;for(let r=i+1;r<n;r++){const f=A[r][i]/d;if(!f)continue;for(let c=i;c<n;c++)A[r][c]-=f*A[i][c];b[r]-=f*b[i]}} | |
| const x=new Array(n);for(let i=n-1;i>=0;i--){let s=b[i];for(let c=i+1;c<n;c++)s-=A[i][c]*x[c];x[i]=s/(A[i][i]||1e-12)}return x} | |
| function olsRss(rows,y){const p=rows[0].length,A=[],b=new Array(p).fill(0);for(let i=0;i<p;i++)A.push(new Array(p).fill(0)); | |
| for(let r=0;r<rows.length;r++){const x=rows[r];for(let i=0;i<p;i++){b[i]+=x[i]*y[r];for(let j=0;j<p;j++)A[i][j]+=x[i]*x[j]}} | |
| for(let i=0;i<p;i++)A[i][i]+=1e-6;const w=solve(A,b);let rss=0;for(let r=0;r<rows.length;r++){let f=0;for(let i=0;i<p;i++)f+=w[i]*rows[r][i];const e=y[r]-f;rss+=e*e}return rss} | |
| function granger(src,dst,order){order=order||3;const a=zscore(diff(src)),b=zscore(diff(dst)),n=a.length,R=[],F=[],y=[]; | |
| for(let t=order;t<n;t++){const r=[1];for(let k=1;k<=order;k++)r.push(b[t-k]);const f=r.slice();for(let k=1;k<=order;k++)f.push(a[t-k]);R.push(r);F.push(f);y.push(b[t])} | |
| const rr=olsRss(R,y),rf=olsRss(F,y);return Math.max(0,Math.log((rr+1e-12)/(rf+1e-12)))} | |
| const PAIRS=[ | |
| {a:{kp:'rwr',ax:'y'},b:{kp:'lwr',ax:'y'},label:'Right wrist ↔ left wrist',an:'right wrist',bn:'left wrist'}, | |
| {a:{kp:'rel',ax:'y'},b:{kp:'rwr',ax:'y'},label:'Right elbow ↔ right wrist',an:'right elbow',bn:'right wrist'}, | |
| {a:{kp:'lel',ax:'y'},b:{kp:'lwr',ax:'y'},label:'Left elbow ↔ left wrist',an:'left elbow',bn:'left wrist'}, | |
| {a:{kp:'nose',ax:'x'},b:{kp:'rwr',ax:'y'},label:'Head ↔ right wrist',an:'head',bn:'right wrist'} | |
| ]; | |
| const PAIRSTATS=[ | |
| {id:'pearson',label:'Correlation',plain:(a,b)=>`Do the ${a} and ${b} move together at the same instant?`,fn:(a,b)=>pearson(a,b)}, | |
| {id:'xcorr_lag',label:'Lag of best match (frames)',plain:(a,b)=>`By how many frames does the ${b} trail the ${a}? Negative means it leads.`,fn:(a,b)=>xcorrLag(a,b).lag}, | |
| {id:'granger_ab',label:'Granger causality, first → second',plain:(a,b)=>`Does knowing the ${a}'s recent past help predict the ${b}'s next move?`,fn:(a,b)=>granger(a,b)}, | |
| {id:'granger_ba',label:'Granger causality, second → first',plain:(a,b)=>`Does knowing the ${b}'s recent past help predict the ${a}'s next move?`,fn:(a,b)=>granger(b,a)} | |
| ]; | |
| const FEATURES=[]; | |
| SIGNALS.forEach((s,si)=>UNI.forEach((u,ui)=>FEATURES.push({kind:'uni',si,ui,name:`${s.label}: ${u.label}`,plain:u.plain}))); | |
| PAIRS.forEach((p,pi)=>PAIRSTATS.forEach((st,ti)=>FEATURES.push({kind:'pair',pi,ti,name:`${p.label}: ${st.label.replace('first',p.an).replace('second',p.bn)}`,plain:st.plain(p.an,p.bn)}))); | |
| /* 'up-down' signals are returned as height (1 - image y) so that up is up */ | |
| function sig(clip,s){if(s.ax==='x')return clip.kp[s.kp].x;const c=clip._h||(clip._h={});if(!c[s.kp]){const y=clip.kp[s.kp].y,o=new Float64Array(y.length);for(let i=0;i<y.length;i++)o[i]=1-y[i];c[s.kp]=o}return c[s.kp]} | |
| function uniFeatures(clip,s){const pr=prep(sig(clip,s),clip.fps);return UNI.map(u=>u.fn(pr))} | |
| function pairFeatures(clip,p){const a=sig(clip,p.a),b=sig(clip,p.b);return PAIRSTATS.map(st=>st.fn(a,b))} | |
| function featureVector(clip){const v=[];for(const s of SIGNALS)for(const f of uniFeatures(clip,s))v.push(f);for(const p of PAIRS)for(const f of pairFeatures(clip,p))v.push(f);return v} | |
| /* ---------- gradient-boosted trees (XGBoost-style second-order splits) ---------- */ | |
| function buildTree(X,g,h,idx,depth,o){ | |
| let G=0,H=0;for(const i of idx){G+=g[i];H+=h[i]} | |
| const node={n:idx.length,value:-G/(H+o.lambda),leaf:true,depth}; | |
| if(depth>=o.depth||idx.length<2*o.minChild)return node; | |
| const parent=G*G/(H+o.lambda);let best={gain:1e-7}; | |
| for(const f of o.feats){ | |
| const s=idx.slice().sort((a,b)=>X[a][f]-X[b][f]);let GL=0,HL=0; | |
| for(let k=0;k<s.length-1;k++){const i=s[k];GL+=g[i];HL+=h[i]; | |
| if(X[i][f]===X[s[k+1]][f]||k+1<o.minChild||s.length-k-1<o.minChild)continue; | |
| const GR=G-GL,HR=H-HL,gain=GL*GL/(HL+o.lambda)+GR*GR/(HR+o.lambda)-parent; | |
| if(gain>best.gain)best={gain,f,thr:(X[i][f]+X[s[k+1]][f])/2}} | |
| } | |
| if(best.f===undefined)return node; | |
| const L=[],R=[];for(const i of idx)(X[i][best.f]<best.thr?L:R).push(i); | |
| node.leaf=false;node.f=best.f;node.thr=best.thr;node.gain=best.gain; | |
| node.left=buildTree(X,g,h,L,depth+1,o);node.right=buildTree(X,g,h,R,depth+1,o);return node} | |
| function predictTree(node,x){while(!node.leaf)node=x[node.f]<node.thr?node.left:node.right;return node.value} | |
| function addGain(node,imp){if(node.leaf)return;imp[node.f]+=node.gain;addGain(node.left,imp);addGain(node.right,imp)} | |
| function fitGBM(X,y,w,feats,o){ | |
| o=Object.assign({rounds:20,depth:2,lr:.3,lambda:1,minChild:2},o||{},{feats}); | |
| const n=X.length,F=new Float64Array(n),g=new Float64Array(n),h=new Float64Array(n),idx=[...Array(n).keys()],trees=[],imp=new Float64Array(X[0].length); | |
| for(let r=0;r<o.rounds;r++){ | |
| for(let i=0;i<n;i++){const p=sigmoid(F[i]),wi=w?w[i]:1;g[i]=wi*(p-y[i]);h[i]=wi*p*(1-p)} | |
| const t=buildTree(X,g,h,idx,0,o);if(t.leaf)break;trees.push(t);addGain(t,imp); | |
| for(let i=0;i<n;i++)F[i]+=o.lr*predictTree(t,X[i])} | |
| return {trees,imp,lr:o.lr,margin:x=>{let s=0;for(const t of trees)s+=o.lr*predictTree(t,x);return s}}} | |
| function makeFolds(y,k,seed){const rng=mulberry32(seed),f=new Array(y.length);for(const c of [0,1]){const ids=[];y.forEach((v,i)=>{if(v===c)ids.push(i)});for(let i=ids.length-1;i>0;i--){const j=Math.floor(rng()*(i+1));[ids[i],ids[j]]=[ids[j],ids[i]]}ids.forEach((id,q)=>f[id]=q%k)}return f} | |
| function cvAccuracy(X,y,feats,folds,k,o){let ok=0;for(let f=0;f<k;f++){const tr=[],te=[];folds.forEach((v,i)=>(v===f?te:tr).push(i)); | |
| const m=fitGBM(tr.map(i=>X[i]),tr.map(i=>y[i]),null,feats,o);for(const i of te)if((m.margin(X[i])>0?1:0)===y[i])ok++}return ok/y.length} | |
| /* Simplified FeatBoost: rank with a boosted model on re-weighted cases, keep the top feature | |
| only if cross-validated accuracy improves, then re-weight towards cases still misjudged. */ | |
| function* featBoost(X,y,opts){ | |
| const o=Object.assign({maxFeatures:8,folds:5,seed:7,tol:.005,patience:2},opts||{}),n=X.length,p=X[0].length,all=[...Array(p).keys()]; | |
| const folds=makeFolds(y,o.folds,o.seed);let w=new Float64Array(n).fill(1),selected=[],best=.5,misses=0,skip=[]; | |
| for(let it=0;selected.length<o.maxFeatures&&it<o.maxFeatures+o.patience;it++){ | |
| const m=fitGBM(X,y,w,all,{rounds:25,depth:2});const imp=Array.from(m.imp);for(const s of selected)imp[s]=0;for(const s of skip)imp[s]=0; | |
| let cand=0;for(let j=1;j<p;j++)if(imp[j]>imp[cand])cand=j; | |
| if(!(imp[cand]>0)){yield {type:'stop',reason:'nothing left to rank',selected:selected.slice(),acc:best};return} | |
| yield {type:'rank',it,imp,cand,weights:Array.from(w)}; | |
| const acc=cvAccuracy(X,y,selected.concat(cand),folds,o.folds); | |
| if(acc>best+o.tol){selected.push(cand);best=acc;misses=0;skip=[];yield {type:'accept',it,cand,acc,selected:selected.slice()}} | |
| else{skip.push(cand);misses++;yield {type:'reject',it,cand,acc,selected:selected.slice(),best}; | |
| if(misses>=o.patience){yield {type:'stop',reason:'the last '+o.patience+' candidates added nothing',selected:selected.slice(),acc:best};return} | |
| continue} | |
| const ms=fitGBM(X,y,null,selected,{rounds:25,depth:2});let sum=0;const loss=new Float64Array(n); | |
| for(let i=0;i<n;i++){const pr=sigmoid(ms.margin(X[i]));loss[i]=-Math.log(Math.max(1e-6,y[i]?pr:1-pr))+.02;sum+=loss[i]} | |
| w=loss.map(v=>v*n/sum); | |
| } | |
| yield {type:'stop',reason:'reached the cap',selected:selected.slice(),acc:best}} | |
| /* ---------- cohorts and toy data ---------- */ | |
| function cohortParams(cls,effect,rng){const u=(a,b)=>a+(b-a)*rng(); | |
| const p={amp:u(.75,1.3),freq:u(.35,.65),tremorAmp:Math.abs(randn(rng))*.012,tremorFreq:u(4,6.5),irregularity:u(.05,.3),asym:u(0,.2),coupling:u(0,.3)}; | |
| if(cls){p.tremorAmp+=effect*u(0,.11);p.irregularity+=effect*u(.05,.55);p.asym+=effect*u(0,.45);p.coupling=Math.min(1,p.coupling+effect*u(.2,.9))} | |
| return p} | |
| function makeCohort(nPer,effect,seed){const rng=mulberry32(seed),X=[],y=[],clips=[]; | |
| for(let i=0;i<2*nPer;i++){const c=i%2,clip=synthClip(cohortParams(c,effect,rng),Math.floor(rng()*1e9));X.push(featureVector(clip));y.push(c)} | |
| return {X,y}} | |
| function makeToy(kind,n,noise,seed){const rng=mulberry32(seed),X=[],y=[]; | |
| for(let i=0;i<n;i++){const a=.04+.92*rng(),b=.04+.92*rng();let c; | |
| if(kind==='cut')c=a>.5;else if(kind==='diag')c=a+b>1;else c=Math.hypot(a-.5,b-.5)<.3; | |
| if(rng()<noise)c=!c;X.push([a,b]);y.push(c?1:0)} | |
| return {X,y}} | |
| /* ================= interface ================= */ | |
| (function(){ | |
| ; | |
| const $=id=>document.getElementById(id); | |
| const C={}; | |
| function readColors(){const s=getComputedStyle(document.documentElement);['bg','surface','ink','muted','line','a','b','act','stage','stage-ink','soft'].forEach(k=>C[k]=s.getPropertyValue('--'+k).trim())} | |
| readColors(); | |
| const FONT='"Atkinson Hyperlegible","Segoe UI",system-ui,sans-serif'; | |
| const reduce=matchMedia('(prefers-reduced-motion: reduce)').matches; | |
| const sleep=ms=>new Promise(r=>setTimeout(r,ms)); | |
| const lerp=(a,b,f)=>a+(b-a)*f; | |
| const pct=v=>Math.round(v*100)+'%'; | |
| function fmt(v){if(!isFinite(v))return '–';const a=Math.abs(v);if(a===0)return '0';if(Number.isInteger(v)&&a<1e4)return String(v);if(a>=100)return v.toFixed(0);if(a>=1)return v.toFixed(2);if(a>=.01)return v.toFixed(3);return v.toExponential(1)} | |
| function fit(c){const r=c.getBoundingClientRect(),d=window.devicePixelRatio||1,w=Math.max(1,Math.round(r.width*d)),h=Math.max(1,Math.round(r.height*d));if(c.width!==w||c.height!==h){c.width=w;c.height=h}const ctx=c.getContext('2d');ctx.setTransform(d,0,0,d,0,0);return {ctx,w:r.width,h:r.height}} | |
| function bind(id,f,show){const el=$(id),o=$(id+'O'),up=()=>{if(o)o.textContent=show?show(+el.value):el.value};el.addEventListener('input',()=>{up();f(+el.value)});up();return el} | |
| function rrect(ctx,x,y,w,h,r){ctx.beginPath();ctx.moveTo(x+r,y);ctx.arcTo(x+w,y,x+w,y+h,r);ctx.arcTo(x+w,y+h,x,y+h,r);ctx.arcTo(x,y+h,x,y,r);ctx.arcTo(x,y,x+w,y,r);ctx.closePath()} | |
| const App={myClip:null,active:'xgboost'}; | |
| /* generic line plot */ | |
| function plot(ctx,r,series,o){o=o||{};let lo=o.ymin,hi=o.ymax; | |
| if(lo===undefined||hi===undefined){let a=Infinity,b=-Infinity;for(const s of series)for(const v of s.y){if(v<a)a=v;if(v>b)b=v}if(!isFinite(a)){a=0;b=1}if(a===b){a-=1;b+=1}const pad=(b-a)*.08;if(lo===undefined)lo=a-pad;if(hi===undefined)hi=b+pad} | |
| const n=o.n||Math.max(2,...series.map(s=>s.y.length)); | |
| const X=i=>r.x+(i/(n-1))*r.w,Y=v=>r.y+r.h-(v-lo)/(hi-lo)*r.h; | |
| ctx.save();ctx.lineWidth=1;ctx.strokeStyle=C.line;ctx.strokeRect(r.x+.5,r.y+.5,r.w,r.h); | |
| ctx.beginPath();ctx.rect(r.x,r.y,r.w,r.h);ctx.clip(); | |
| for(const sp of o.xspans||[]){ctx.fillStyle=sp.color;ctx.globalAlpha=sp.alpha||.2;ctx.fillRect(X(sp.i0),r.y,X(sp.i1)-X(sp.i0),r.h)} | |
| for(const b of o.bands||[]){ctx.fillStyle=b.color;ctx.globalAlpha=b.alpha||.16;ctx.fillRect(r.x,Y(b.y1),r.w,Y(b.y0)-Y(b.y1))} | |
| ctx.globalAlpha=1; | |
| for(const h of o.hlines||[]){ctx.strokeStyle=h.color||C.muted;ctx.lineWidth=1.3;ctx.setLineDash(h.dash||[5,4]);ctx.beginPath();ctx.moveTo(r.x,Y(h.y));ctx.lineTo(r.x+r.w,Y(h.y));ctx.stroke()} | |
| ctx.setLineDash([]);ctx.lineJoin='round'; | |
| for(const s of series){ctx.strokeStyle=s.color;ctx.lineWidth=s.width||1.8;ctx.globalAlpha=s.alpha||1;ctx.beginPath();const off=s.offset||0;for(let i=0;i<s.y.length;i++){const x=X(i+off),y=Y(s.y[i]);i?ctx.lineTo(x,y):ctx.moveTo(x,y)}ctx.stroke()} | |
| ctx.globalAlpha=1; | |
| for(const m of o.marks||[]){ctx.fillStyle=m.color;ctx.beginPath();ctx.arc(X(m.i),Y(m.y),m.r||4,0,7);ctx.fill()} | |
| ctx.restore(); | |
| if(o.title){ctx.fillStyle=C.ink;ctx.font='13px '+FONT;ctx.textAlign='left';ctx.textBaseline='bottom';ctx.fillText(o.title,r.x,r.y-4)} | |
| return {X,Y}} | |
| /* 13-point stick figure */ | |
| function drawSkel(ctx,get,r,o){o=o||{};const P=k=>{const p=get(k);return [r.x+p[0]*r.w,r.y+p[1]*r.h]}; | |
| ctx.save();ctx.globalAlpha=o.alpha||1;ctx.lineCap='round';ctx.strokeStyle=o.color||C['stage-ink'];ctx.lineWidth=o.lw||3; | |
| for(const [a,b] of BONES){const p=P(a),q=P(b);ctx.beginPath();ctx.moveTo(p[0],p[1]);ctx.lineTo(q[0],q[1]);ctx.stroke()} | |
| const n=P('nose'),ls=P('lsh'),rs=P('rsh');ctx.beginPath();ctx.moveTo((ls[0]+rs[0])/2,(ls[1]+rs[1])/2);ctx.lineTo(n[0],n[1]+r.h*.045);ctx.stroke(); | |
| ctx.beginPath();ctx.arc(n[0],n[1],r.h*.045,0,7);ctx.stroke(); | |
| if(!o.noJoints){ctx.fillStyle='#fff';for(const k of KP){if(k==='nose')continue;const p=P(k);ctx.beginPath();ctx.arc(p[0],p[1],o.jr||3.2,0,7);ctx.fill()}} | |
| for(const h of o.highlight||[]){const p=P(h.kp);ctx.fillStyle=h.color;ctx.strokeStyle='#fff';ctx.lineWidth=2;ctx.beginPath();ctx.arc(p[0],p[1],7,0,7);ctx.fill();ctx.stroke()} | |
| ctx.restore()} | |
| const KPLABEL={nose:'Head (nose)',lsh:'Left shoulder',rsh:'Right shoulder',lel:'Left elbow',rel:'Right elbow',lwr:'Left wrist',rwr:'Right wrist',lhip:'Left hip',rhip:'Right hip',lkn:'Left knee',rkn:'Right knee',lank:'Left ankle',rank:'Right ankle'}; | |
| /* ============================ 1. XGBoost ============================ */ | |
| const XG=(()=>{ | |
| const names=['Tremor power','Movement range'],short=['Tremor','Range'],N=120; | |
| let data=null,F,trees=[],view=0,animStart=0,speed=1,mapDirty=true,busy=false; | |
| const opts=()=>({depth:+$('xgDepth').value,lambda:1,minChild:3,feats:[0,1]}); | |
| function reset(newData){if(newData||!data)data=makeToy($('xgData').value,N,+$('xgNoise').value,3);F=new Float64Array(N);trees=[];$('xgForest').innerHTML='';boost()} | |
| function boost(fast){ | |
| const {X,y}=data,g=new Float64Array(N),h=new Float64Array(N),resid=new Float32Array(N); | |
| for(let i=0;i<N;i++){const p=sigmoid(F[i]);g[i]=p-y[i];h[i]=p*(1-p);resid[i]=Math.abs(p-y[i])} | |
| const root=buildTree(X,g,h,[...Array(N).keys()],0,opts()),lr=+$('xgLr').value,nodes=[],leaves=[]; | |
| (function walk(nd){nodes.push(nd);if(nd.leaf){nd.slot=leaves.length;nd.items=0;leaves.push(nd)}else{walk(nd.left);walk(nd.right)}})(root); | |
| (function pos(nd){if(nd.leaf)nd.px=(nd.slot+.5)/leaves.length;else{pos(nd.left);pos(nd.right);nd.px=(nd.left.px+nd.right.px)/2}})(root); | |
| const paths=[]; | |
| for(let i=0;i<N;i++){const path=[root];let nd=root;while(!nd.leaf){nd=X[i][nd.f]<nd.thr?nd.left:nd.right;path.push(nd)}paths.push({path,slot:nd.items++});F[i]+=lr*nd.value} | |
| trees.push({root,nodes,leaves,paths,resid,lr,maxDepth:Math.max(...nodes.map(n=>n.depth))}); | |
| addThumb(trees.length-1);select(trees.length-1,fast);mapDirty=true;stats()} | |
| function thumb(t){const W=40,H=34,X=nd=>4+nd.px*(W-8),Y=nd=>5+(t.maxDepth?nd.depth/t.maxDepth:0)*(H-11);let s=''; | |
| for(const nd of t.nodes)if(!nd.leaf)for(const ch of [nd.left,nd.right])s+=`<line x1="${X(nd)}" y1="${Y(nd)}" x2="${X(ch)}" y2="${Y(ch)}" style="stroke:var(--muted)" stroke-width="1.2"/>`; | |
| for(const nd of t.nodes)s+=`<circle cx="${X(nd)}" cy="${Y(nd)}" r="${nd.leaf?3.2:2}" style="fill:var(--${nd.leaf?(nd.value>0?'b':'a'):'muted'})"/>`; | |
| return `<svg viewBox="0 0 ${W} ${H}" aria-hidden="true">${s}</svg>`} | |
| function addThumb(k){const b=document.createElement('button');b.innerHTML=thumb(trees[k]);b.title='Tree '+(k+1);b.setAttribute('aria-label','Show tree '+(k+1));b.addEventListener('click',()=>select(k));$('xgForest').appendChild(b)} | |
| function select(k,fast){view=k;speed=fast?.3:1;animStart=performance.now();[...$('xgForest').children].forEach((b,i)=>b.setAttribute('aria-pressed',i===k)); | |
| $('xgTreeTitle').textContent=`Tree ${k+1} of ${trees.length}`+(k?`, grown to fix what ${k===1?'tree 1 still gets':'trees 1–'+k+' still get'} wrong`:', looking at the raw cases')} | |
| function stats(){let ok=0;for(let i=0;i<N;i++)if((F[i]>0?1:0)===data.y[i])ok++; | |
| $('xgStats').innerHTML=`<b>${trees.length}</b> ${trees.length===1?'tree':'trees'}. Correct on <b>${ok}</b> of ${N} cases (${pct(ok/N)}).`} | |
| function drawTree(now){const {ctx,w,h}=fit($('xgTree'));ctx.clearRect(0,0,w,h);const t=trees[view];if(!t||w<10)return; | |
| const m=22,top=30,D=9,pileH=Math.min(170,h*.4),lvl=t.maxDepth?Math.min(105,(h-top-pileH-34)/t.maxDepth):0; | |
| const PX=nd=>m+nd.px*(w-2*m),PY=nd=>top+nd.depth*lvl,slotW=(w-2*m)/t.leaves.length,narrow=slotW<120; | |
| ctx.font='12px '+FONT;ctx.textAlign='center';ctx.textBaseline='middle'; | |
| for(const nd of t.nodes)if(!nd.leaf)[nd.left,nd.right].forEach((ch,j)=>{ctx.strokeStyle=C.line;ctx.lineWidth=2;ctx.beginPath();ctx.moveTo(PX(nd),PY(nd));ctx.lineTo(PX(ch),PY(ch));ctx.stroke(); | |
| if(!narrow||nd.depth===0){ctx.fillStyle=C.muted;ctx.fillText(j?'no':'yes',lerp(PX(nd),PX(ch),.55)+(j?14:-14),lerp(PY(nd),PY(ch),.5))}}); | |
| const seg=reduce?1:430*speed,stag=reduce?0:11*speed,el=now-animStart,perRow=Math.max(3,Math.min(13,Math.floor((slotW-8)/D))); | |
| for(let i=0;i<N;i++){const {path,slot}=t.paths[i],leaf=path[path.length-1],pts=[[PX(t.root),-12]]; | |
| for(const nd of path)pts.push([PX(nd),PY(nd)]); | |
| pts.push([PX(leaf)+((slot%perRow)-(perRow-1)/2)*D,PY(leaf)+36+Math.floor(slot/perRow)*D]); | |
| const u=(el-i*stag)/seg;if(u<=0)continue;let x,y; | |
| if(u>=pts.length-1)[x,y]=pts[pts.length-1];else{const k=Math.floor(u),f=u-k,e=f*f*(3-2*f);x=lerp(pts[k][0],pts[k+1][0],e);y=lerp(pts[k][1],pts[k+1][1],f*f*.6+f*.4)} | |
| ctx.fillStyle=data.y[i]?C.b:C.a;ctx.beginPath();ctx.arc(x,y,1.9+2.6*t.resid[i],0,7);ctx.fill()} | |
| for(const nd of t.nodes){const x=PX(nd),y=PY(nd); | |
| if(nd.leaf){const v=t.lr*nd.value,txt=(narrow?'':'votes ')+(v>0?'B ':'A ')+(v>0?'+':'−')+Math.abs(v).toFixed(2),tw=ctx.measureText(txt).width+14; | |
| ctx.fillStyle=v>0?C.b:C.a;rrect(ctx,x-tw/2,y+2,tw,20,10);ctx.fill();ctx.fillStyle='#fff';ctx.fillText(txt,x,y+12.5)} | |
| else{const txt=(narrow?short:names)[nd.f]+' < '+nd.thr.toFixed(2)+(narrow?'':' ?'),tw=ctx.measureText(txt).width+14; | |
| ctx.fillStyle=C.surface;ctx.strokeStyle=C.ink;ctx.lineWidth=1.5;rrect(ctx,x-tw/2,y-12,tw,24,6);ctx.fill();ctx.stroke();ctx.fillStyle=C.ink;ctx.fillText(txt,x,y+.5)}}} | |
| function drawMap(){const {ctx,w,h}=fit($('xgMap'));ctx.clearRect(0,0,w,h);if(w<10)return;const L=24,B=22,pw=w-L-4,ph=h-B-4,G=44; | |
| for(let gx=0;gx<G;gx++)for(let gy=0;gy<G;gy++){const x=[(gx+.5)/G,(gy+.5)/G];let mg=0;for(const t of trees)mg+=t.lr*predictTree(t.root,x);const p=sigmoid(mg); | |
| ctx.fillStyle=p>.5?C.b:C.a;ctx.globalAlpha=Math.min(.55,Math.abs(p-.5)*1.15);ctx.fillRect(L+gx*pw/G,4+(G-1-gy)*ph/G,pw/G+.6,ph/G+.6)} | |
| ctx.globalAlpha=1;ctx.strokeStyle=C.line;ctx.strokeRect(L+.5,4.5,pw,ph); | |
| for(let i=0;i<N;i++){const x=L+data.X[i][0]*pw,y=4+(1-data.X[i][1])*ph,wrong=(F[i]>0?1:0)!==data.y[i]; | |
| ctx.fillStyle=data.y[i]?C.b:C.a;ctx.beginPath();ctx.arc(x,y,4,0,7);ctx.fill();ctx.strokeStyle=wrong?C.ink:C.surface;ctx.lineWidth=wrong?2:1;ctx.stroke()} | |
| ctx.fillStyle=C.muted;ctx.font='12px '+FONT;ctx.textAlign='center';ctx.textBaseline='bottom';ctx.fillText(names[0]+' →',L+pw/2,h-2); | |
| ctx.save();ctx.translate(13,4+ph/2);ctx.rotate(-Math.PI/2);ctx.textBaseline='middle';ctx.fillText(names[1]+' →',0,0);ctx.restore()} | |
| function setBusy(b){busy=b;['xgBoost','xgBoost10','xgReset'].forEach(id=>$(id).disabled=b)} | |
| function init(){ | |
| $('xgBoost').addEventListener('click',()=>boost()); | |
| $('xgBoost10').addEventListener('click',async()=>{if(busy)return;setBusy(true);for(let i=0;i<10;i++){boost(true);await sleep(reduce?60:420)}setBusy(false)}); | |
| $('xgDrop').addEventListener('click',()=>{speed=1;animStart=performance.now()}); | |
| $('xgReset').addEventListener('click',()=>reset(false)); | |
| $('xgData').addEventListener('change',()=>reset(true)); | |
| bind('xgNoise',()=>reset(true),v=>pct(v));bind('xgDepth',()=>reset(false));bind('xgLr',()=>reset(false),v=>v.toFixed(1)); | |
| reset(true)} | |
| return {init,enter(){mapDirty=true;animStart=performance.now();speed=1},tick(now){drawTree(now);if(mapDirty){drawMap();mapDirty=false}},dirty(){mapDirty=true}}})(); | |
| /* ============================ 2. MediaPipe ============================ */ | |
| const MP=(()=>{ | |
| const MAP={nose:0,lsh:11,rsh:12,lel:13,rel:14,lwr:15,rwr:16,lhip:23,rhip:24,lkn:25,rkn:26,lank:27,rank:28}; | |
| const CONN=[[11,12],[11,13],[13,15],[12,14],[14,16],[11,23],[12,24],[23,24],[23,25],[25,27],[24,26],[26,28],[27,29],[29,31],[27,31],[28,30],[30,32],[28,32],[15,17],[15,19],[15,21],[17,19],[16,18],[16,20],[16,22],[18,20],[0,1],[1,2],[2,3],[3,7],[0,4],[4,5],[5,6],[6,8],[9,10]]; | |
| const VER='0.10.14',BASE='https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@'+VER,MODEL='https://storage.googleapis.com/mediapipe-models/pose_landmarker/pose_landmarker_lite/float16/1/pose_landmarker_lite.task'; | |
| const video=$('mpVideo'),stage=$('mpStage'); | |
| let mode='demo',lm=null,loading=null,img=null,imgLm=null,stream=null,buf=[],demo=null,rec=null,lastVT=-1,lastFull=null,countKey=''; | |
| const status=s=>$('mpStatus').textContent=s; | |
| async function load(){if(lm)return lm;if(!loading)loading=(async()=>{const mod=await import(BASE+'/vision_bundle.mjs'),fs=await mod.FilesetResolver.forVisionTasks(BASE+'/wasm'); | |
| const mk=d=>mod.PoseLandmarker.createFromOptions(fs,{baseOptions:{modelAssetPath:MODEL,delegate:d},runningMode:'VIDEO',numPoses:1}); | |
| let obj;try{obj=await mk('GPU')}catch(e){obj=await mk('CPU')}lm={obj,mode:'VIDEO'};return lm})(); | |
| try{return await loading}catch(e){loading=null;throw e}} | |
| async function running(m){if(lm.mode!==m){await lm.obj.setOptions({runningMode:m});lm.mode=m}} | |
| function stop(){if(stream){stream.getTracks().forEach(t=>t.stop());stream=null}video.pause();video.srcObject=null;video.removeAttribute('src');img=null;imgLm=null;lastFull=null;lastVT=-1;buf=[]} | |
| function setMode(m,tag){mode=m;$('mpTag').textContent=tag;$('mpDemoCtl').style.display=m==='demo'?'':'none'} | |
| function toDemo(msg){stop();setMode('demo','Synthetic figure');status(msg||'')} | |
| async function withModel(fn){status('Loading the pose model (about 6 MB)…'); | |
| try{await load()}catch(e){console.error(e);toDemo('The pose model could not be downloaded here. Open this page from its own web address with an internet connection. The synthetic figure still works.');return} | |
| try{await fn();}catch(e){console.error(e);toDemo((e&&e.userMsg)||'That source could not be opened. The synthetic figure still works.')}} | |
| const useCam=()=>withModel(async()=>{stop(); | |
| try{stream=await navigator.mediaDevices.getUserMedia({video:{facingMode:'user',width:{ideal:640},height:{ideal:480}},audio:false})}catch(e){e.userMsg='The camera is blocked or missing. Allow camera access for this page, or upload a video instead.';throw e} | |
| video.srcObject=stream;await video.play();await running('VIDEO');setMode('cam','Your camera');status('')}); | |
| const useVideo=f=>withModel(async()=>{stop();video.src=URL.createObjectURL(f);await video.play();await running('VIDEO');setMode('video','Your video');status('')}); | |
| const useImage=f=>withModel(async()=>{stop();const im=new Image();im.src=URL.createObjectURL(f);await im.decode();await running('IMAGE');const res=lm.obj.detect(im);img=im;imgLm=res.landmarks&&res.landmarks[0]||null;setMode('image','Your picture'); | |
| status(imgLm?'A picture is a single moment, so every trace is flat. Try a video or the camera to see movement.':'No person was found in this picture. Try one where the whole upper body is visible.')}); | |
| function makeDemo(){demo=synthClip({tremorAmp:+$('mpTrem').value,irregularity:+$('mpIrr').value,asym:.25,coupling:.6},5,12)} | |
| function size(w,h){const s=Math.min(640/w,640/h,1),W=Math.round(w*s),H=Math.round(h*s);if(stage.width!==W||stage.height!==H){stage.width=W;stage.height=H} | |
| const key=w+'x'+h;if(key!==countKey){countKey=key;$('mpCount').innerHTML=`One video frame: ${w} × ${h} pixels × 3 colours = <b>${(w*h*3).toLocaleString('en')}</b> numbers.<br>The same frame as a skeleton: 33 points × 2 = <b>66</b> numbers.`}} | |
| function finishRec(){const fr=rec.frames;rec=null;$('mpRec').disabled=false; | |
| if(fr.length<20){$('mpRecStatus').textContent='No person was visible for long enough, so nothing was saved. Try again.';return} | |
| const n=180,kp={};for(const k of KP)kp[k]={x:new Float64Array(n),y:new Float64Array(n)};let j=0; | |
| for(let i=0;i<n;i++){const t=i/30*1000;while(j<fr.length-2&&fr[j+1].t<t)j++;const a=fr[j],b=fr[Math.min(j+1,fr.length-1)],f=b.t>a.t?Math.min(1,Math.max(0,(t-a.t)/(b.t-a.t))):0; | |
| for(const k of KP){kp[k].x[i]=lerp(a.kp[k][0],b.kp[k][0],f);kp[k].y[i]=lerp(a.kp[k][1],b.kp[k][1],f)}} | |
| App.myClip={fps:30,n,kp,aspect:mode==='demo'?1:stage.width/stage.height}; | |
| $('mpRecStatus').textContent='Saved. “My clip” is now available in exhibits 3 and 4.';TS.refresh();FB.refresh()} | |
| function tick(now){ | |
| let full=null,kp=null,src=null,mirror=false; | |
| if(mode==='demo'){size(1280,720);stage.width=640;stage.height=480;const i=Math.floor(now/1000*demo.fps)%demo.n;kp={};for(const k of KP)kp[k]=[demo.kp[k].x[i],demo.kp[k].y[i]]} | |
| else if(mode==='image'){if(img){size(img.naturalWidth,img.naturalHeight);src=img}full=imgLm} | |
| else if(video.readyState>=2&&video.videoWidth){size(video.videoWidth,video.videoHeight);src=video;mirror=mode==='cam'; | |
| if(video.currentTime!==lastVT){lastVT=video.currentTime;try{const res=lm.obj.detectForVideo(video,now);lastFull=res.landmarks&&res.landmarks[0]||null}catch(e){lastFull=null} | |
| if(lastFull&&mirror)lastFull=lastFull.map(p=>({x:1-p.x,y:p.y}))} | |
| full=lastFull} | |
| if(full){kp={};for(const k of KP){const p=full[MAP[k]];kp[k]=[p.x,p.y]}} | |
| if(kp){buf.push({t:now,kp});if(rec)rec.frames.push({t:now-rec.t0,kp})} | |
| while(buf.length&&buf[0].t<now-9000)buf.shift(); | |
| if(rec){const s=(now-rec.t0)/1000;if(s>=6)finishRec();else $('mpRecStatus').textContent=`Recording… ${s.toFixed(1)} of 6 seconds`} | |
| const ctx=stage.getContext('2d'),W=stage.width,H=stage.height;ctx.setTransform(1,0,0,1,0,0);ctx.fillStyle=C.stage;ctx.fillRect(0,0,W,H); | |
| if(src&&$('mpShowVideo').checked){ctx.save();if(mirror){ctx.translate(W,0);ctx.scale(-1,1)}ctx.drawImage(src,0,0,W,H);ctx.restore()} | |
| const R=mode==='demo'?{x:(W-H)/2,y:0,w:H,h:H}:{x:0,y:0,w:W,h:H},selKp=$('mpKp').value; | |
| if($('mpTrails').checked&&mode!=='image'){ | |
| for(let a=1;a<=5;a++){const f=buf[buf.length-1-a*5];if(f)drawSkel(ctx,k=>f.kp[k],R,{alpha:.26-a*.04,noJoints:true,lw:2})} | |
| for(const [k,col] of [['lwr','#F272B0'],['rwr','#F272B0']]){ctx.strokeStyle=col;ctx.lineWidth=2.5;ctx.lineCap='round';const st=Math.max(0,buf.length-45); | |
| for(let i=st+1;i<buf.length;i++){ctx.globalAlpha=(i-st)/45;ctx.beginPath();ctx.moveTo(R.x+buf[i-1].kp[k][0]*R.w,R.y+buf[i-1].kp[k][1]*R.h);ctx.lineTo(R.x+buf[i].kp[k][0]*R.w,R.y+buf[i].kp[k][1]*R.h);ctx.stroke()}ctx.globalAlpha=1}} | |
| if(full){ctx.strokeStyle='#fff';ctx.lineWidth=Math.max(2,W/260);ctx.lineCap='round';for(const [a,b] of CONN){ctx.beginPath();ctx.moveTo(full[a].x*W,full[a].y*H);ctx.lineTo(full[b].x*W,full[b].y*H);ctx.stroke()} | |
| ctx.fillStyle=C.b;for(const p of full){ctx.beginPath();ctx.arc(p.x*W,p.y*H,Math.max(3,W/200),0,7);ctx.fill()} | |
| const p=full[MAP[selKp]];ctx.strokeStyle=C.act;ctx.lineWidth=3;ctx.beginPath();ctx.arc(p.x*W,p.y*H,11,0,7);ctx.stroke()} | |
| else if(kp)drawSkel(ctx,k=>kp[k],R,{highlight:[{kp:selKp,color:C.act}]}); | |
| else if(mode!=='demo'){ctx.fillStyle=C['stage-ink'];ctx.font='16px '+FONT;ctx.textAlign='center';ctx.fillText(mode==='image'?'No person found':'Looking for a person…',W/2,H/2)} | |
| /* trace of the selected keypoint */ | |
| const c=fit($('mpChart')),g=c.ctx,r={x:1,y:6,w:c.w-2,h:c.h-12};g.clearRect(0,0,c.w,c.h);g.strokeStyle=C.line;g.strokeRect(r.x+.5,r.y+.5,r.w,r.h); | |
| for(const [ax,col] of [[0,C.a],[1,C.b]]){g.strokeStyle=col;g.lineWidth=2;g.lineJoin='round';g.beginPath();let first=true; | |
| for(const f of buf){const x=r.x+(1-(now-f.t)/8000)*r.w;if(x<r.x)continue;const v=ax?1-f.kp[selKp][1]:f.kp[selKp][0],y=r.y+r.h-Math.min(1,Math.max(0,v))*r.h;first?g.moveTo(x,y):g.lineTo(x,y);first=false}g.stroke()}} | |
| function init(){ | |
| for(const k of KP){const o=document.createElement('option');o.value=k;o.textContent=KPLABEL[k];$('mpKp').appendChild(o)}$('mpKp').value='rwr'; | |
| $('mpCam').addEventListener('click',useCam);$('mpDemo').addEventListener('click',()=>toDemo('')); | |
| $('mpVidFile').addEventListener('change',e=>{const f=e.target.files[0];if(f)useVideo(f);e.target.value=''}); | |
| $('mpImgFile').addEventListener('change',e=>{const f=e.target.files[0];if(f)useImage(f);e.target.value=''}); | |
| bind('mpTrem',makeDemo,v=>v.toFixed(2));bind('mpIrr',makeDemo,v=>v.toFixed(2));makeDemo(); | |
| $('mpRec').addEventListener('click',()=>{if(mode==='image'){$('mpRecStatus').textContent='A picture has no movement to record. Use the camera, a video or the synthetic figure.';return}rec={t0:performance.now(),frames:[]};$('mpRec').disabled=true})} | |
| return {init,tick,enter(){},leave(){if(mode==='cam'||mode==='video')video.pause()},resume(){if((mode==='cam'||mode==='video')&&video.paused)video.play().catch(()=>{})}}})(); | |
| /* ============================ 3. TSFresh / PySPI ============================ */ | |
| function clipRect(clip,w,h){const a=clip.aspect||1;let rh=h,rw=h*a;if(rw>w){rw=w;rh=w/a}return {x:(w-rw)/2,y:(h-rh)/2,w:rw,h:rh}} | |
| function drawClip(canvas,clip,i,hl,color){const {ctx,w,h}=fit(canvas);ctx.clearRect(0,0,w,h);if(w<10)return;const r=clipRect(clip,w,h); | |
| for(const k of hl){ctx.strokeStyle=color;ctx.lineWidth=2.5;ctx.lineCap='round';for(let a=1;a<26;a++){const j=(i-a+clip.n)%clip.n,q=(j+1)%clip.n;if(q===0)continue;ctx.globalAlpha=1-a/26;ctx.beginPath();ctx.moveTo(r.x+clip.kp[k].x[j]*r.w,r.y+clip.kp[k].y[j]*r.h);ctx.lineTo(r.x+clip.kp[k].x[q]*r.w,r.y+clip.kp[k].y[q]*r.h);ctx.stroke()}ctx.globalAlpha=1} | |
| drawSkel(ctx,k=>[clip.kp[k].x[i],clip.kp[k].y[i]],r,{highlight:hl.map(k=>({kp:k,color}))})} | |
| const TS=(()=>{ | |
| const smooth=synthClip({irregularity:.06,tremorAmp:0,asym:0,coupling:.1},21); | |
| const OPT=[['smooth','Synthetic: smooth and regular'],['irregular','Synthetic: irregular, with tremor'],['mine','My clip']]; | |
| let irr,A,B,rows=[],sel=9,si=0,pi=0; | |
| const get=k=>k==='smooth'?smooth:k==='irregular'?irr:(App.myClip||smooth); | |
| function fillSel(el,val){el.innerHTML='';for(const [v,t] of OPT){const o=document.createElement('option');o.value=v;o.textContent=v==='mine'&&!App.myClip?'My clip (record it in exhibit 2 first)':t;o.disabled=v==='mine'&&!App.myClip;el.appendChild(o)}el.value=val} | |
| function recompute(){irr=synthClip({irregularity:+$('tsIrr').value,tremorAmp:+$('tsTrem').value,tremorFreq:+$('tsFreq').value,asym:.35,coupling:.85},22); | |
| A=get($('tsSelA').value);B=get($('tsSelB').value);const s=SIGNALS[si],p=PAIRS[pi],ua=uniFeatures(A,s),ub=uniFeatures(B,s),pa=pairFeatures(A,p),pb=pairFeatures(B,p); | |
| rows=UNI.map((u,i)=>({kind:'uni',label:u.label,plain:u.plain,viz:u.viz,a:ua[i],b:ub[i]})).concat(PAIRSTATS.map((st,i)=>({kind:'pair',label:st.label.replace('first',p.an).replace('second',p.bn),plain:st.plain(p.an,p.bn),viz:'pair',a:pa[i],b:pb[i]}))); | |
| table();detail()} | |
| function table(){let h='';rows.forEach((r,i)=>{ | |
| if(i===0)h+=`<tr class="grp"><td colspan="4">One keypoint at a time (TSFresh style): ${SIGNALS[si].label}</td></tr>`; | |
| if(i===UNI.length)h+=`<tr class="grp"><td colspan="4">Two keypoints together (PySPI style): ${PAIRS[pi].label}</td></tr>`; | |
| const m=Math.max(Math.abs(r.a),Math.abs(r.b))||1; | |
| h+=`<tr class="f" data-i="${i}" tabindex="0" aria-selected="${i===sel}"><td>${r.label}</td><td class="num">${fmt(r.a)}</td><td class="num">${fmt(r.b)}</td><td><span class="bars"><i class="a" style="width:${Math.abs(r.a)/m*100}%"></i><i class="b" style="width:${Math.abs(r.b)/m*100}%"></i></span></td></tr>`}); | |
| $('tsTable').innerHTML=h} | |
| function hl(){const r=rows[sel];return r&&r.kind==='pair'?[PAIRS[pi].a.kp,PAIRS[pi].b.kp]:[SIGNALS[si].kp]} | |
| function detail(){const row=rows[sel];if(!row)return;$('tsDetailTitle').textContent=row.label;$('tsDetailText').textContent=row.plain; | |
| const {ctx,w,h}=fit($('tsDetail'));ctx.clearRect(0,0,w,h);if(w<10)return;const ph=(h-56)/2,rs=[{x:1,y:22,w:w-2,h:ph},{x:1,y:22+ph+30,w:w-2,h:ph}]; | |
| [[A,row.a,C.a,'Clip A'],[B,row.b,C.b,'Clip B']].forEach(([clip,val,col,name],q)=>{const r=rs[q],title=`${name}: ${fmt(val)}`; | |
| if(row.kind==='pair'){const p=PAIRS[pi];plot(ctx,r,[{y:zscore(sig(clip,p.a)),color:col,width:2.6},{y:zscore(sig(clip,p.b)),color:C.ink,width:1.2}],{ymin:-3,ymax:3,title:title+` (thick: ${p.an}, thin: ${p.bn})`});return} | |
| const x=sig(clip,SIGNALS[si]),xo=sig(q?A:B,SIGNALS[si]),m=mean(x),s=std(x,m),o={title};let lo=Infinity,hi=-Infinity;for(const v of x){if(v<lo)lo=v;if(v>hi)hi=v}for(const v of xo){if(v<lo)lo=v;if(v>hi)hi=v} | |
| const pad=(hi-lo)*.1||.01;o.ymin=lo-pad;o.ymax=hi+pad;let ser=[{y:x,color:col,width:2}]; | |
| if(row.viz==='mean')o.hlines=[{y:m,color:C.ink}]; | |
| else if(row.viz==='std'){o.hlines=[{y:m,color:C.ink}];o.bands=[{y0:m-s,y1:m+s,color:col}]} | |
| else if(row.viz==='range'){let a=Infinity,b=-Infinity;for(const v of x){if(v<a)a=v;if(v>b)b=v}o.hlines=[{y:a,color:C.ink},{y:b,color:C.ink}]} | |
| else if(row.viz==='peaks')o.marks=findPeaks(x,PEAK_SUPPORT).map(i=>({i,y:x[i],color:C.ink,r:4})); | |
| else if(row.viz==='acf')ser.push({y:x,color:C.ink,width:1.2,alpha:.6,offset:ACF_LAG*4}),o.title=title+' (thin: the same trace, shifted)'; | |
| else if(row.viz==='strike'){const st=longestAbove(x,m);o.hlines=[{y:m,color:C.ink}];o.xspans=[{i0:st.i0,i1:st.i1,color:col,alpha:.25}]} | |
| else if(row.viz==='change'){const d=Array.from(diff(x),Math.abs),d2=Array.from(diff(xo),Math.abs);ser=[{y:d,color:col,width:1.6}];o.ymin=0;o.ymax=Math.max(...d,...d2)*1.1||1;o.title=title+' (size of each frame-to-frame step)'} | |
| else if(row.viz==='spectrum'){const sp=spectrum(x,clip.fps),so=spectrum(xo,clip.fps),K=sp.freq.filter(f=>f<=12).length,y=sp.pow.slice(0,K).map(Math.sqrt),y2=so.pow.slice(0,K).map(Math.sqrt); | |
| ser=[{y,color:col,width:2}];o.ymin=0;o.ymax=Math.max(...y,...y2)*.5||1;o.n=K;const idx=f=>f*x.length/clip.fps-1;o.xspans=[{i0:idx(TREMOR_BAND[0]),i1:idx(TREMOR_BAND[1]),color:C.act,alpha:.14}]; | |
| let b=0;for(let i=1;i<K;i++)if(y[i]>y[b])b=i;o.marks=[{i:b,y:Math.min(y[b],o.ymax*.97),color:C.ink,r:4}];o.title=title+' (rhythm strength from 0 to 12 Hz; shaded: 3–8 Hz)'} | |
| plot(ctx,r,ser,o)})} | |
| function init(){fillSel($('tsSelA'),'smooth');fillSel($('tsSelB'),'irregular'); | |
| SIGNALS.forEach((s,i)=>{const o=document.createElement('option');o.value=i;o.textContent=s.label;$('tsSignal').appendChild(o)}); | |
| PAIRS.forEach((p,i)=>{const o=document.createElement('option');o.value=i;o.textContent=p.label;$('tsPair').appendChild(o)}); | |
| $('tsSignal').addEventListener('change',e=>{si=+e.target.value;if(rows[sel]&&rows[sel].kind==='pair')sel=9;recompute()}); | |
| $('tsPair').addEventListener('change',e=>{pi=+e.target.value;if(rows[sel]&&rows[sel].kind==='uni')sel=UNI.length+2;recompute()}); | |
| $('tsSelA').addEventListener('change',recompute);$('tsSelB').addEventListener('change',recompute); | |
| bind('tsTrem',recompute,v=>v.toFixed(2));bind('tsFreq',recompute,v=>v.toFixed(1)+' Hz');bind('tsIrr',recompute,v=>v.toFixed(2)); | |
| const pick=e=>{const tr=e.target.closest('tr.f');if(!tr)return;sel=+tr.dataset.i;table();detail()}; | |
| $('tsTable').addEventListener('click',pick);$('tsTable').addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();pick(e);const t=$('tsTable').querySelector(`tr[data-i="${sel}"]`);if(t)t.focus()}}); | |
| recompute()} | |
| return {init,enter(){detail()},refresh(){const a=$('tsSelA').value,b=$('tsSelB').value;fillSel($('tsSelA'),a);fillSel($('tsSelB'),b);recompute()}, | |
| tick(now){const i=Math.floor(now/1000*30),h=hl();drawClip($('tsA'),A,i%A.n,h,C.a);drawClip($('tsB'),B,i%B.n,h,C.b)},dirty(){detail()}}})(); | |
| /* ============================ 4. FeatBoost ============================ */ | |
| const FB=(()=>{ | |
| let cohort=null,seed=2,runId=0,running=false,tiles=[],accs=[],baseline=null,selected=[]; | |
| const status=s=>$('fbStatus').textContent=s; | |
| function grid(){const g=$('fbGrid');g.innerHTML='';tiles=[];let k=0; | |
| const row=(label,n)=>{const r=document.createElement('div');r.className='tilerow';const l=document.createElement('span');l.textContent=label;const c=document.createElement('div');c.className='cells';c.style.gridTemplateColumns='repeat(12,minmax(0,1fr))'; | |
| for(let i=0;i<n;i++){const b=document.createElement('button');b.className='tile';const f=FEATURES[k++];b.title=f.name;b.setAttribute('aria-label',f.name);b.innerHTML='<span></span>'; | |
| const show=()=>$('fbHover').textContent=f.name;b.addEventListener('mouseenter',show);b.addEventListener('focus',show);b.addEventListener('click',show);c.appendChild(b);tiles.push(b)} | |
| r.appendChild(l);r.appendChild(c);g.appendChild(r)}; | |
| SIGNALS.forEach(s=>row(s.label,UNI.length));PAIRS.forEach(p=>row(p.label,PAIRSTATS.length))} | |
| function cases(w){const el=$('fbCases');if(!cohort){el.innerHTML='';return} | |
| if(el.children.length!==cohort.y.length){el.innerHTML='';const order=cohort.y.map((c,i)=>i).sort((a,b)=>cohort.y[a]-cohort.y[b]);for(const i of order){const d=document.createElement('i');d.className=cohort.y[i]?'b':'a';d.dataset.i=i;el.appendChild(d)}} | |
| for(const d of el.children){const v=w?w[+d.dataset.i]:1;d.style.transform=`scale(${Math.min(1.9,Math.max(.55,Math.sqrt(v)))})`}} | |
| function clear(){accs=[];baseline=null;selected=[];for(const t of tiles){t.className='tile';t.style.setProperty('--heat',0);t.firstChild.textContent=''} | |
| $('fbList').innerHTML='<li class="note" style="list-style:none;margin-left:-1.3em">Nothing yet. Press BOOST.</li>';$('fbScatterNote').textContent='';cases(null);charts()} | |
| function charts(){drawAcc();drawScatter()} | |
| function drawAcc(){const {ctx,w,h}=fit($('fbAcc'));ctx.clearRect(0,0,w,h);if(w<10)return;const r={x:38,y:8,w:w-48,h:h-44},n=Math.max(4,accs.length),X=i=>r.x+(i+.5)/n*r.w,Y=v=>r.y+r.h-(v-.4)/.62*r.h; | |
| ctx.font='12px '+FONT;ctx.strokeStyle=C.line;ctx.strokeRect(r.x+.5,r.y+.5,r.w,r.h);ctx.fillStyle=C.muted;ctx.textAlign='right';ctx.textBaseline='middle'; | |
| for(const v of [.5,.75,1]){ctx.fillText(pct(v),r.x-5,Y(v));ctx.strokeStyle=C.line;ctx.setLineDash(v===.5?[4,4]:[1,5]);ctx.beginPath();ctx.moveTo(r.x,Y(v));ctx.lineTo(r.x+r.w,Y(v));ctx.stroke()} | |
| ctx.setLineDash([]);ctx.textAlign='left';ctx.fillText('coin flip',r.x+5,Y(.5)-8); | |
| if(baseline!==null){ctx.strokeStyle=C.muted;ctx.setLineDash([7,4]);ctx.lineWidth=1.5;ctx.beginPath();ctx.moveTo(r.x,Y(baseline));ctx.lineTo(r.x+r.w,Y(baseline));ctx.stroke();ctx.setLineDash([]);ctx.textAlign='right';ctx.fillText(`all ${FEATURES.length} measures: ${pct(baseline)}`,r.x+r.w-5,Y(baseline)+(baseline>.9?10:-9))} | |
| ctx.textAlign='center';ctx.textBaseline='top';ctx.fillStyle=C.muted;for(let i=0;i<n;i++)ctx.fillText(i+1,X(i),r.y+r.h+4);ctx.fillText('measures kept',r.x+r.w/2,r.y+r.h+18); | |
| if(accs.length){ctx.strokeStyle=C.b;ctx.lineWidth=2.5;ctx.beginPath();accs.forEach((a,i)=>i?ctx.lineTo(X(i),Y(a)):ctx.moveTo(X(i),Y(a)));ctx.stroke(); | |
| ctx.textBaseline='bottom';accs.forEach((a,i)=>{ctx.fillStyle=C.b;ctx.beginPath();ctx.arc(X(i),Y(a),5,0,7);ctx.fill();ctx.fillStyle=C.ink;ctx.font='bold 12px '+FONT;ctx.fillText(pct(a),X(i),Y(a)-8)})}} | |
| function drawScatter(){const el=$('fbScatter'),{ctx,w,h}=fit(el);ctx.clearRect(0,0,w,h);if(w<10||!cohort||!selected.length||running)return; | |
| const f1=selected[0],f2=selected.length>1?selected[1]:-1,rng=mulberry32(4),{X,y}=cohort,mine=App.myClip?featureVector(App.myClip):null; | |
| const xs=X.map(v=>v[f1]),ys=X.map(v=>f2<0?rng():v[f2]),ext=a=>{let lo=Math.min(...a),hi=Math.max(...a);const p=(hi-lo)*.08||1;return [lo-p,hi+p]},[x0,x1]=ext(xs),[y0,y1]=f2<0?[-.5,1.5]:ext(ys); | |
| const r={x:8,y:8,w:w-16,h:h-48},PX=v=>r.x+Math.min(1,Math.max(0,(v-x0)/(x1-x0)))*r.w,PY=v=>r.y+r.h-Math.min(1,Math.max(0,(v-y0)/(y1-y0)))*r.h; | |
| ctx.strokeStyle=C.line;ctx.strokeRect(r.x+.5,r.y+.5,r.w,r.h); | |
| for(let i=0;i<y.length;i++){ctx.fillStyle=y[i]?C.b:C.a;ctx.globalAlpha=.8;ctx.beginPath();ctx.arc(PX(xs[i]),PY(ys[i]),4.5,0,7);ctx.fill()}ctx.globalAlpha=1; | |
| if(mine){const x=PX(mine[f1]),yy=PY(f2<0?.5:mine[f2]);ctx.fillStyle=C.ink;ctx.strokeStyle=C.surface;ctx.lineWidth=2;ctx.beginPath();for(let k=0;k<10;k++){const a=-Math.PI/2+k*Math.PI/5,R=k%2?5:12;ctx.lineTo(x+R*Math.cos(a),yy+R*Math.sin(a))}ctx.closePath();ctx.fill();ctx.stroke()} | |
| ctx.fillStyle=C.muted;ctx.font='12px '+FONT;ctx.textAlign='left';ctx.textBaseline='top';const cut=s=>{while(ctx.measureText(s).width>w-40&&s.length>8)s=s.slice(0,-2);return s}; | |
| ctx.fillText(cut('→ '+FEATURES[f1].name),r.x,r.y+r.h+5);if(f2>=0)ctx.fillText(cut('↑ '+FEATURES[f2].name),r.x,r.y+r.h+21); | |
| $('fbScatterNote').textContent=mine?'The star is your clip. It was not filmed like the synthetic cohort, so read its position as an illustration only.':'Each dot is one clip, placed by the first two kept measures. Record “My clip” in exhibit 2 to see where you land.'} | |
| function newCohort(){runId++;running=false;$('fbBoost').disabled=true;seed++;const n=+$('fbN').value,eff=+$('fbEff').value;cohort=null;clear();status('Generating clips and measuring them…'); | |
| setTimeout(()=>{cohort=makeCohort(n,eff,seed*101);clear();$('fbBoost').disabled=false;status(`${2*n} synthetic clips, ${FEATURES.length} measures each.`)},40)} | |
| async function boost(){if(!cohort||running)return;const my=++runId;running=true;$('fbBoost').disabled=true;clear();status('First, the baseline: a model that uses every measure…');await sleep(60); | |
| const {X,y}=cohort;baseline=cvAccuracy(X,y,[...Array(FEATURES.length).keys()],makeFolds(y,5,7),5);drawAcc();await sleep(reduce?50:500); | |
| const T=reduce?.15:1; | |
| for(const s of featBoost(X,y,{seed:7})){if(my!==runId)return; | |
| if(s.type==='rank'){tiles.forEach(t=>t.classList.remove('rej'));const mx=Math.max(...s.imp)||1;tiles.forEach((t,i)=>{t.style.setProperty('--heat',(Math.sqrt(s.imp[i]/mx)*.9).toFixed(2));t.classList.remove('cand')});tiles[s.cand].classList.add('cand');cases(s.weights); | |
| status(`Round ${s.it+1}. The model nominates “${FEATURES[s.cand].name}”. Checking it on unseen clips…`);await sleep(1300*T)} | |
| else if(s.type==='accept'){selected=s.selected;accs.push(s.acc);const t=tiles[s.cand];t.classList.remove('cand');t.classList.add('sel');t.firstChild.textContent=selected.length; | |
| if(selected.length===1)$('fbList').innerHTML='';const li=document.createElement('li'),f=FEATURES[s.cand];li.innerHTML=`${f.name}<small>${f.plain}</small>`;$('fbList').appendChild(li);drawAcc(); | |
| status(`Kept. Accuracy on unseen clips is now ${pct(s.acc)}.`);await sleep(1000*T)} | |
| else if(s.type==='reject'){tiles[s.cand].classList.remove('cand');tiles[s.cand].classList.add('rej');status(`Not kept: with it, accuracy would be ${pct(s.acc)}, no better than ${pct(s.best)}.`);await sleep(1200*T)} | |
| else{tiles.forEach(t=>t.style.setProperty('--heat',0));running=false;$('fbBoost').disabled=false;drawScatter(); | |
| status(selected.length?`Stopped: ${s.reason}. ${selected.length} of ${FEATURES.length} measures kept, ${pct(s.acc)} against ${pct(baseline)} with all of them.`:'Stopped without keeping anything: no single measure beat a coin flip by enough.')} | |
| await sleep(0)} | |
| running=false;$('fbBoost').disabled=false} | |
| function init(){grid();$('fbBoost').addEventListener('click',boost);$('fbNew').addEventListener('click',newCohort); | |
| bind('fbN',()=>{});bind('fbEff',()=>{},v=>v.toFixed(2));$('fbN').addEventListener('change',newCohort);$('fbEff').addEventListener('change',newCohort)} | |
| return {init,enter(){if(!cohort&&!$('fbBoost').disabled)newCohort();else charts()},refresh(){drawScatter()},tick(){},dirty(){charts()}}})(); | |
| /* ============================ tabs and main loop ============================ */ | |
| const MODS={xgboost:XG,mediapipe:MP,features:TS,featboost:FB}; | |
| function show(name,push){if(!MODS[name])name='xgboost';if(MODS[App.active].leave)MODS[App.active].leave();App.active=name; | |
| for(const b of document.querySelectorAll('.tabs button')){const on=b.dataset.tab===name;b.setAttribute('aria-selected',on);b.tabIndex=on?0:-1;$('p-'+b.dataset.tab).hidden=!on} | |
| if(push&&location.hash!=='#'+name)history.replaceState(null,'','#'+name); | |
| if(MODS[name].resume)MODS[name].resume();MODS[name].enter()} | |
| for(const b of document.querySelectorAll('.tabs button'))b.addEventListener('click',()=>show(b.dataset.tab,true)); | |
| document.querySelector('.tabs').addEventListener('keydown',e=>{if(e.key!=='ArrowRight'&&e.key!=='ArrowLeft')return;const ids=Object.keys(MODS),i=(ids.indexOf(App.active)+(e.key==='ArrowRight'?1:ids.length-1))%ids.length;show(ids[i],true);$('t-'+ids[i]).focus()}); | |
| window.addEventListener('hashchange',()=>show(location.hash.slice(1))); | |
| function dirtyAll(){for(const k in MODS)if(MODS[k].dirty&&k===App.active)MODS[k].dirty()} | |
| window.addEventListener('resize',dirtyAll); | |
| matchMedia('(prefers-color-scheme: dark)').addEventListener('change',()=>{readColors();dirtyAll()}); | |
| XG.init();MP.init();TS.init();FB.init(); | |
| show(location.hash.slice(1)||'xgboost'); | |
| (function loop(now){try{MODS[App.active].tick(now||performance.now())}catch(e){console.error(e)}requestAnimationFrame(loop)})(); | |
| })(); | |
| </script> | |
| </body> | |
| </html> | |