molexplorer / index.html
softwareDevelopment's picture
Update index.html
dc6e05a verified
Raw History Blame Contribute Delete
102 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Docking Pro - Complete Structural Biology Platform</title> <link href="https://fonts.googleapis.com/css2?family=Space+Mono:ital,wght@0,400;0,700;1,400&family=Syne:wght@400;600;700;800&display=swap" rel="stylesheet"> <script src="https://3dmol.csb.pitt.edu/build/3Dmol-min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js"></script> <style> *{margin:0;padding:0;box-sizing:border-box} :root{ --bg:#07090f; --bg2:#0d101a; --bg3:#141826; --bg4:#1c2235; --cyan:#00f0ff; --purple:#c084fc; --green:#34d399; --yellow:#fbbf24; --red:#f87171; --orange:#fb923c; --text:#e8edf8; --text2:#8892b0; --text3:#4a5568; --border:#1e2a40; --border2:#2a3a55; } body{ font-family:'Syne',sans-serif; background:var(--bg); color:var(--text); min-height:100vh; background-image: radial-gradient(ellipse 60% 50% at 20% 10%, rgba(0,240,255,0.04) 0%, transparent 60%), radial-gradient(ellipse 50% 40% at 80% 90%, rgba(192,132,252,0.04) 0%, transparent 60%); } #app{max-width:1600px;margin:0 auto;padding:20px} /* HEADER */ .header{ display:flex;align-items:center;gap:20px; padding:18px 28px; background:linear-gradient(135deg,rgba(13,16,26,0.9),rgba(20,24,38,0.9)); border:1px solid var(--border2); border-radius:20px; margin-bottom:24px; backdrop-filter:blur(20px); position:relative;overflow:hidden; } .header::before{ content:'';position:absolute;top:0;left:0;right:0;height:1px; background:linear-gradient(90deg,transparent,var(--cyan),var(--purple),transparent); } .logo{ font-size:22px;font-weight:800;letter-spacing:-0.5px; background:linear-gradient(135deg,var(--cyan),var(--purple)); -webkit-background-clip:text;-webkit-text-fill-color:transparent; } .logo-sub{color:var(--text3);font-size:11px;font-family:'Space Mono',monospace;margin-top:2px;letter-spacing:1px} .badges{margin-left:auto;display:flex;gap:10px;flex-wrap:wrap} .badge{ padding:5px 14px;border-radius:100px;font-size:11px;font-weight:700; font-family:'Space Mono',monospace; background:var(--bg3);border:1px solid var(--border);color:var(--text2); letter-spacing:0.5px;transition:all .2s; } .badge.lit{background:rgba(0,240,255,0.08);border-color:rgba(0,240,255,0.3);color:var(--cyan)} /* TABS */ .tabs{ display:flex;gap:6px;padding:6px; background:var(--bg2);border:1px solid var(--border);border-radius:16px; margin-bottom:24px; } .tab{ flex:1;padding:10px 16px;background:transparent;border:none; color:var(--text3);font-weight:700;font-size:13px; font-family:'Syne',sans-serif;border-radius:10px;cursor:pointer; transition:all .25s;letter-spacing:0.3px; } .tab:hover{color:var(--text2);background:var(--bg3)} .tab.active{ background:linear-gradient(135deg,rgba(0,240,255,0.12),rgba(192,132,252,0.12)); color:var(--cyan);border:1px solid rgba(0,240,255,0.25); } /* PANELS */ .panel{display:none} .panel.active{display:block} .grid2{display:grid;grid-template-columns:1fr 1fr;gap:20px} @media(max-width:1100px){.grid2{grid-template-columns:1fr}} /* CARD */ .card{ background:var(--bg2);border:1px solid var(--border); border-radius:18px;padding:22px;margin-bottom:20px; transition:border-color .2s,transform .15s; } .card:hover{border-color:var(--border2);transform:translateY(-1px)} .card-title{ font-size:10px;font-weight:700;font-family:'Space Mono',monospace; text-transform:uppercase;letter-spacing:2px;color:var(--text3); margin-bottom:16px;display:flex;align-items:center;gap:8px; } .card-title::before{content:'';width:3px;height:12px;background:linear-gradient(var(--cyan),var(--purple));border-radius:2px} /* INPUTS */ .row{display:flex;gap:10px;margin-bottom:14px} input[type=text],input[type=password],input[type=number],select,textarea{ width:100%;padding:10px 14px; background:var(--bg3);border:1px solid var(--border);border-radius:10px; color:var(--text);font-family:'Space Mono',monospace;font-size:13px; transition:border-color .2s;outline:none; } input:focus,select:focus,textarea:focus{border-color:rgba(0,240,255,0.4);background:var(--bg4)} textarea{min-height:110px;resize:vertical;margin-bottom:14px} label{font-size:11px;color:var(--text2);display:block;margin-bottom:6px;font-family:'Space Mono',monospace} /* FILE UPLOAD */ .upload-zone{ border:2px dashed var(--border2);border-radius:12px; padding:24px;text-align:center;cursor:pointer; transition:all .2s;background:var(--bg3);margin-bottom:14px; } .upload-zone:hover,.upload-zone.drag{border-color:var(--cyan);background:rgba(0,240,255,0.04)} .upload-zone input{display:none} .upload-zone .icon{font-size:28px;margin-bottom:8px} .upload-zone p{color:var(--text2);font-size:12px;font-family:'Space Mono',monospace} .upload-zone .hint{color:var(--text3);font-size:10px;margin-top:4px} /* BUTTONS */ .btn{ padding:10px 20px;border:1px solid var(--border);border-radius:10px; font-weight:700;font-size:13px;font-family:'Syne',sans-serif;cursor:pointer; transition:all .2s;background:var(--bg3);color:var(--text); white-space:nowrap; } .btn:hover{background:var(--bg4);border-color:var(--border2);transform:translateY(-1px)} .btn:disabled{opacity:0.4;cursor:not-allowed;transform:none} .btn-primary{ background:linear-gradient(135deg,rgba(0,240,255,0.15),rgba(192,132,252,0.15)); border-color:rgba(0,240,255,0.35);color:var(--cyan); } .btn-primary:hover{background:linear-gradient(135deg,rgba(0,240,255,0.25),rgba(192,132,252,0.25));box-shadow:0 4px 20px rgba(0,240,255,0.15)} .btn-success{background:rgba(52,211,153,0.12);border-color:rgba(52,211,153,0.3);color:var(--green)} .btn-success:hover{background:rgba(52,211,153,0.2);box-shadow:0 4px 20px rgba(52,211,153,0.1)} .btn-full{width:100%} .btn-sm{padding:6px 14px;font-size:11px} /* VIEWERS */ .viewer-wrap{ height:380px;background:var(--bg3);border:1px solid var(--border); border-radius:14px;overflow:hidden;position:relative;margin-bottom:14px; } .viewer-wrap .viewer{width:100%;height:100%} .vplaceholder{ position:absolute;top:50%;left:50%;transform:translate(-50%,-50%); text-align:center;color:var(--text3);pointer-events:none;z-index:1; } .vplaceholder .ico{font-size:40px;margin-bottom:10px;opacity:0.3} /* CHIPS */ .chips{display:flex;gap:8px;flex-wrap:wrap} .chip{ padding:5px 13px;background:var(--bg3);border:1px solid var(--border); border-radius:100px;font-size:11px;font-weight:600;cursor:pointer; transition:all .2s;color:var(--text2);font-family:'Space Mono',monospace; } .chip:hover,.chip.on{ background:rgba(0,240,255,0.08);border-color:rgba(0,240,255,0.35);color:var(--cyan); } /* ALERTS */ .alert{padding:12px 16px;border-radius:10px;font-size:12px;margin-bottom:14px;font-family:'Space Mono',monospace;line-height:1.6} .alert-info{background:rgba(59,130,246,0.08);border:1px solid rgba(59,130,246,0.2);color:#60a5fa} .alert-success{background:rgba(52,211,153,0.08);border:1px solid rgba(52,211,153,0.2);color:var(--green)} .alert-warning{background:rgba(251,191,36,0.08);border:1px solid rgba(251,191,36,0.2);color:var(--yellow)} .alert-error{background:rgba(248,113,113,0.08);border:1px solid rgba(248,113,113,0.2);color:var(--red)} /* PROGRESS */ .progress-bar{height:6px;background:var(--bg3);border-radius:6px;overflow:hidden;margin:12px 0} .progress-fill{height:100%;background:linear-gradient(90deg,var(--cyan),var(--purple));border-radius:6px;transition:width .4s ease;width:0%} .progress-label{text-align:center;font-size:11px;color:var(--text3);font-family:'Space Mono',monospace} /* STEPS */ .steps{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:18px} .step{ padding:5px 12px;border-radius:100px;font-size:10px;font-weight:700; font-family:'Space Mono',monospace;background:var(--bg3);border:1px solid var(--border);color:var(--text3); } .step.running{background:rgba(0,240,255,0.08);border-color:var(--cyan);color:var(--cyan);animation:pulse 1.2s infinite} .step.done{background:rgba(52,211,153,0.08);border-color:var(--green);color:var(--green)} @keyframes pulse{0%,100%{opacity:1}50%{opacity:0.5}} /* PROPS */ .prop-row{ display:flex;justify-content:space-between;align-items:center; padding:9px 0;border-bottom:1px solid var(--border); } .prop-key{color:var(--text2);font-size:12px;font-family:'Space Mono',monospace} .prop-val{color:var(--text);font-weight:600;font-family:'Space Mono',monospace;font-size:12px} /* BEST POSE CARD */ .best-pose-card{ background:linear-gradient(135deg,rgba(52,211,153,0.06),rgba(0,240,255,0.06)); border:1px solid rgba(52,211,153,0.25);border-radius:16px;padding:24px; text-align:center;margin-bottom:18px; } .best-energy{ font-size:48px;font-weight:800;color:var(--green); line-height:1;margin-bottom:6px; } .best-unit{font-size:14px;color:var(--text2);font-family:'Space Mono',monospace} .best-ki{ margin-top:12px;padding:8px 16px; background:rgba(0,0,0,0.3);border-radius:8px; font-family:'Space Mono',monospace;font-size:12px;color:var(--text2); display:inline-block; } /* SMILES BOX */ .smiles-box{ background:var(--bg3);border:1px solid var(--border);border-radius:10px; padding:14px;font-family:'Space Mono',monospace;font-size:11px; color:var(--yellow);word-break:break-all;margin:10px 0; } /* CHAT */ .chat-window{ height:360px;overflow-y:auto;background:var(--bg3); border:1px solid var(--border);border-radius:14px; padding:16px;margin-bottom:14px;display:flex;flex-direction:column;gap:10px; scrollbar-width:thin;scrollbar-color:var(--border) transparent; } .msg{padding:10px 14px;border-radius:12px;max-width:82%;font-size:12px;line-height:1.7;font-family:'Space Mono',monospace} .msg.user{background:rgba(0,240,255,0.08);border:1px solid rgba(0,240,255,0.2);color:var(--cyan);align-self:flex-end} .msg.assistant{background:var(--bg2);border:1px solid var(--border);color:var(--text);align-self:flex-start} .msg.sys{background:rgba(59,130,246,0.07);border:1px solid rgba(59,130,246,0.15);color:#60a5fa;align-self:center;text-align:center;max-width:100%;font-size:11px} /* TOAST */ #toast{position:fixed;bottom:28px;right:28px;z-index:9999;display:none;max-width:380px} .toast-inner{ background:var(--bg2);border:1px solid var(--border2);border-radius:14px; padding:14px 18px;display:flex;align-items:center;gap:12px; box-shadow:0 20px 40px rgba(0,0,0,0.5);backdrop-filter:blur(16px); } .toast-msg{flex:1;font-size:12px;font-family:'Space Mono',monospace} .toast-x{cursor:pointer;opacity:0.4} .toast-x:hover{opacity:1} /* SPINNER */ .spin{ display:inline-block;width:14px;height:14px; border:2px solid var(--border2);border-top-color:var(--cyan); border-radius:50%;animation:sp 0.8s linear infinite;vertical-align:middle;margin-right:6px; } @keyframes sp{to{transform:rotate(360deg)}} /* IFRAME for PubChem Sketcher */ .sketch-frame{ width:100%; height:480px; border:1px solid var(--border); border-radius:12px; background:#ffffff; margin-bottom:14px; } /* MarVliew container */ .marvin-container{ width:100%; height:480px; border:1px solid var(--border); border-radius:12px; background:#ffffff; margin-bottom:14px; position:relative; } .marvin-container iframe{ width:100%; height:100%; border-radius:12px; } /* MolView link styling */ .molview-link{ display:flex; align-items:center; justify-content:space-between; background:var(--bg3); border:1px solid var(--border); border-radius:12px; padding:16px; margin-bottom:14px; } .molview-icon{ font-size:32px; opacity:0.8; } /* INTERACTION TABLE */ .interaction-table{width:100%;border-collapse:collapse;font-family:'Space Mono',monospace;font-size:11px} .interaction-table th{padding:7px 12px;text-align:left;color:var(--text3);font-weight:700;border-bottom:1px solid var(--border);background:var(--bg3)} .interaction-table td{padding:8px 12px;border-bottom:1px solid var(--border);color:var(--text)} .int-tag{padding:2px 8px;border-radius:100px;font-size:10px;font-weight:700} .int-hbond{background:rgba(59,130,246,0.12);color:#60a5fa;border:1px solid rgba(59,130,246,0.25)} .int-hydro{background:rgba(251,191,36,0.1);color:var(--yellow);border:1px solid rgba(251,191,36,0.2)} .int-pi{background:rgba(192,132,252,0.1);color:var(--purple);border:1px solid rgba(192,132,252,0.2)} .int-vdw{background:rgba(52,211,153,0.1);color:var(--green);border:1px solid rgba(52,211,153,0.2)} /* FOOTER */ .footer{ margin-top:40px;padding:36px;background:var(--bg2); border:1px solid var(--border);border-radius:20px;text-align:center; position:relative;overflow:hidden; } .footer::before{ content:'';position:absolute;bottom:0;left:0;right:0;height:1px; background:linear-gradient(90deg,transparent,var(--purple),var(--cyan),transparent); } .footer-email{ display:inline-flex;align-items:center;gap:14px; padding:12px 28px;border-radius:100px;cursor:pointer; background:linear-gradient(135deg,rgba(0,240,255,0.08),rgba(192,132,252,0.08)); border:1px solid rgba(0,240,255,0.2);margin-top:18px; transition:all .2s;font-family:'Space Mono',monospace;font-size:12px; } .footer-email:hover{transform:translateY(-2px);box-shadow:0 10px 30px rgba(0,240,255,0.1)} /* Grid for docking params */ .param-grid{display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;margin:14px 0} .param-grid .param-item label{font-size:10px;margin-bottom:4px} .param-grid .param-item input{font-size:12px;padding:8px 12px} /* Range slider */ input[type=range]{ -webkit-appearance:none;width:100%;height:4px; background:var(--bg4);border-radius:4px;outline:none;margin:8px 0; } input[type=range]::-webkit-slider-thumb{ -webkit-appearance:none;width:16px;height:16px; background:linear-gradient(135deg,var(--cyan),var(--purple)); border-radius:50%;cursor:pointer; } /* Sequence analysis */ .aa-bar{height:8px;background:var(--bg3);border-radius:4px;overflow:hidden;margin:4px 0} .aa-fill{height:100%;border-radius:4px;transition:width .5s ease} </style> </head> <body> <div id="app"> <!-- HEADER --> <div class="header"> <div> <div class="logo">βš› Docking Pro</div> <div class="logo-sub">STRUCTURAL BIOLOGY PLATFORM v2.0</div> </div> <div class="badges"> <span id="b-protein" class="badge">🧬 Protein: None</span> <span id="b-ligand" class="badge">πŸ’Š Ligand: None</span> <span id="b-api" class="badge">πŸ”‘ API: β€”</span> </div> </div> <!-- TABS --> <div class="tabs"> <button class="tab active" data-tab="protein">🧬 Protein</button> <button class="tab" data-tab="molecule">πŸ’Š Molecule</button> <button class="tab" data-tab="draw">✏️ Sketch</button> <button class="tab" data-tab="docking">🎯 Docking</button> <button class="tab" data-tab="sequence">πŸ”¬ Sequence</button> <button class="tab" data-tab="ai">πŸ€– AI</button> </div> <!-- ═══════════════ PROTEIN PANEL ═══════════════ --> <div id="protein-panel" class="panel active"> <div class="grid2"> <div> <div class="card"> <div class="card-title">Load from Database</div> <div class="row"> <input type="text" id="pdb-input" placeholder="PDB ID (e.g. 6LU7)" oninput="this.value=this.value.toUpperCase()"> <button class="btn btn-primary" onclick="loadPDB()">Load</button> </div> <div class="row"> <input type="text" id="uniprot-input" placeholder="UniProt ID for AlphaFold"> <button class="btn btn-success" onclick="loadAlphaFold()">AlphaFold</button> </div> <div class="chips"> <span class="chip" onclick="setPDB('1HHO')">1HHO</span> <span class="chip" onclick="setPDB('6LU7')">6LU7</span> <span class="chip" onclick="setPDB('3HTB')">3HTB</span> <span class="chip" onclick="setPDB('1AKE')">1AKE</span> <span class="chip" onclick="setPDB('4HHB')">4HHB</span> </div> </div> <!-- FILE UPLOAD for Protein --> <div class="card"> <div class="card-title">Upload Protein File</div> <div class="upload-zone" id="protein-upload-zone" onclick="document.getElementById('protein-file').click()" ondragover="handleDrag(event,'protein-upload-zone')" ondrop="handleProteinDrop(event)" ondragleave="leaveDrag('protein-upload-zone')"> <input type="file" id="protein-file" accept=".pdb,.ent,.cif" onchange="loadProteinFile(event)"> <div class="icon">πŸ“</div> <p>Click or drag & drop protein file</p> <div class="hint">Accepts: .pdb, .ent, .cif</div> </div> <div id="protein-file-status"></div> </div> <div class="card"> <div class="card-title">Properties</div> <div id="protein-props"><div class="alert alert-info">Load a protein to view properties</div></div> </div> <div id="protein-dl" style="display:none"> <button class="btn btn-full" onclick="downloadPDB()">⬇ Download PDB</button> </div> </div> <div> <div class="card"> <div class="card-title">3D Viewer</div> <div class="viewer-wrap"> <div id="pv" class="viewer"></div> <div class="vplaceholder" id="pp"><div class="ico">🧬</div><div>Load a protein structure</div></div> </div> <div class="chips" id="protein-style-chips"> <span class="chip on" onclick="setStyle('protein','cartoon',this)">Cartoon</span> <span class="chip" onclick="setStyle('protein','surface',this)">Surface</span> <span class="chip" onclick="setStyle('protein','stick',this)">Stick</span> <span class="chip" onclick="setStyle('protein','sphere',this)">Sphere</span> </div> </div> <div class="card"> <div class="card-title">Ramachandran Plot</div> <canvas id="rama-canvas" style="width:100%;height:260px"></canvas> <button class="btn btn-full" style="margin-top:14px" onclick="genRama()">Generate</button> </div> </div> </div> </div> <!-- ═══════════════ MOLECULE PANEL ═══════════════ --> <div id="molecule-panel" class="panel"> <div class="grid2"> <div> <div class="card"> <div class="card-title">Search PubChem</div> <div class="row"> <input type="text" id="pubchem-input" placeholder="Compound name (e.g. aspirin)"> <button class="btn btn-primary" onclick="searchPubChem()">Search</button> </div> </div> <!-- FILE UPLOAD for Ligand --> <div class="card"> <div class="card-title">Upload Ligand File</div> <div class="upload-zone" id="ligand-upload-zone" onclick="document.getElementById('ligand-file').click()" ondragover="handleDrag(event,'ligand-upload-zone')" ondrop="handleLigandDrop(event)" ondragleave="leaveDrag('ligand-upload-zone')"> <input type="file" id="ligand-file" accept=".sdf,.mol,.mol2,.pdb" onchange="loadLigandFile(event)"> <div class="icon">πŸ“</div> <p>Click or drag & drop ligand file</p> <div class="hint">Accepts: .sdf, .mol, .mol2, .pdb</div> </div> <div id="ligand-file-status"></div> </div> <div class="card"> <div class="card-title">IUPAC β†’ 3D Structure</div> <div class="alert alert-info">Uses OpenMolecules OPSIN + CIR + PubChem cascade</div> <div class="row"> <input type="text" id="iupac-input" placeholder="Enter IUPAC name"> <button class="btn btn-success" onclick="convertIUPAC()">Convert</button> </div> <div id="iupac-sources" class="converter-source"></div> <div id="iupac-result"></div> <div class="chips" style="margin-top:12px"> <span class="chip" onclick="ti('aspirin')">Aspirin</span> <span class="chip" onclick="ti('caffeine')">Caffeine</span> <span class="chip" onclick="ti('ibuprofen')">Ibuprofen</span> <span class="chip" onclick="ti('morphine')">Morphine</span> <span class="chip" onclick="ti('penicillin')">Penicillin</span> </div> </div> <div class="card"> <div class="card-title">Molecular Properties</div> <div id="mol-props"><div class="alert alert-info">Load a molecule to view properties</div></div> </div> <div class="card"> <div class="card-title">Lipinski Rule of Five</div> <div id="lipinski"><div class="alert alert-info">Load a molecule first</div></div> </div> <div id="mol-dl" style="display:none"> <button class="btn btn-full" onclick="downloadSDF()">⬇ Download SDF</button> </div> </div> <div> <div class="card"> <div class="card-title">3D Viewer β€” Ligand</div> <div class="viewer-wrap"> <div id="lv" class="viewer"></div> <div class="vplaceholder" id="lp"><div class="ico">πŸ’Š</div><div>Load a molecule</div></div> </div> <div class="chips" id="ligand-style-chips"> <span class="chip on" onclick="setStyle('ligand','stick',this)">Stick</span> <span class="chip" onclick="setStyle('ligand','sphere',this)">Sphere</span> <span class="chip" onclick="setStyle('ligand','surface',this)">Surface</span> <span class="chip" onclick="setStyle('ligand','line',this)">Line</span> </div> </div> </div> </div> </div> <!-- ═══════════════ SKETCH PANEL ═══════════════ --> <div id="draw-panel" class="panel"> <div class="grid2"> <div> <div class="card"> <div class="card-title">PubChem Sketcher</div> <div class="alert alert-info">Draw molecules directly in PubChem's online sketcher</div> <!-- PubChem Sketcher Iframe --> <iframe id="pubchem-sketch" class="sketch-frame" src="https://pubchem.ncbi.nlm.nih.gov/edit2/index.html" allow="clipboard-read; clipboard-write"></iframe> <div style="display:flex;gap:8px;margin-top:12px;flex-wrap:wrap"> <button class="btn btn-primary" style="flex:1" onclick="getFromPubChemSketch()">πŸ“‹ Get SMILES from Sketcher</button> <button class="btn btn-success" style="flex:1" onclick="loadSketchAsLigand()">πŸ”¬ Load as Ligand</button> <button class="btn" onclick="clearSketch()">πŸ—‘ Clear</button> </div> <div id="sketch-smiles-out" class="smiles-box" style="margin-top:10px;display:none"></div> </div> <div class="card"> <div class="card-title">Marvin JS (Alternative)</div> <div class="alert alert-info">Advanced chemical editor from ChemAxon</div> <!-- Marvin JS Container --> <div id="marvin-container" class="marvin-container"> <div style="padding:40px;text-align:center;color:var(--text3)"> Loading Marvin JS...<br> <span class="spin"></span> </div> </div> <div style="display:flex;gap:8px;margin-top:12px"> <button class="btn btn-primary" style="flex:1" onclick="getFromMarvin()">πŸ“‹ Get SMILES</button> <button class="btn btn-success" style="flex:1" onclick="loadMarvinAsLigand()">πŸ”¬ Load as Ligand</button> </div> </div> <div class="card"> <div class="card-title">MolView (External)</div> <div class="molview-link"> <div> <div style="font-weight:700;margin-bottom:4px">βš› MolView</div> <div style="font-size:11px;color:var(--text2)">Open in new tab - draw, then export SMILES</div> </div> <div class="molview-icon">πŸ”—</div> </div> <div class="row"> <input type="text" id="molview-smiles" placeholder="Paste SMILES from MolView"> <button class="btn btn-success" onclick="loadMolViewSMILES()">Load</button> </div> <div class="chips" style="margin-top:8px"> <span class="chip" onclick="window.open('https://molview.org', '_blank')">Open MolView β†—</span> <span class="chip" onclick="document.getElementById('molview-smiles').value = 'c1ccccc1'">Benzene</span> <span class="chip" onclick="document.getElementById('molview-smiles').value = 'CC(=O)Oc1ccccc1C(=O)O'">Aspirin</span> </div> </div> </div> <div> <div class="card"> <div class="card-title">3D Preview</div> <div class="viewer-wrap"> <div id="dv" class="viewer"></div> <div class="vplaceholder" id="dp"><div class="ico">✏️</div><div>Draw and load structure</div></div> </div> <div class="chips"> <span class="chip on" onclick="setStyle('draw','stick',this)">Stick</span> <span class="chip" onclick="setStyle('draw','sphere',this)">Sphere</span> <span class="chip" onclick="setStyle('draw','surface',this)">Surface</span> </div> </div> <div class="card"> <div class="card-title">Recent Sketches</div> <div id="recent-sketches"> <div class="alert alert-info">No recent sketches</div> </div> </div> </div> </div> </div> <!-- ═══════════════ DOCKING PANEL ═══════════════ --> <div id="docking-panel" class="panel"> <div class="grid2"> <div> <div class="card"> <div class="card-title">Status</div> <div id="dk-prot-status" class="alert alert-warning">⚠ No protein loaded</div> <div id="dk-lig-status" class="alert alert-warning">⚠ No ligand loaded</div> </div> <div class="card"> <div class="card-title">AutoDock Vina Pipeline</div> <div class="steps" id="dock-steps"> <span class="step" id="s1">1 Β· Protein</span> <span class="step" id="s2">2 Β· Ligand</span> <span class="step" id="s3">3 Β· Grid</span> <span class="step" id="s4">4 Β· Dock</span> <span class="step" id="s5">5 Β· Result</span> </div> <div class="progress-bar"><div class="progress-fill" id="dock-prog"></div></div> <div class="progress-label" id="dock-label">Ready</div> <div class="param-grid" style="margin-top:18px"> <div class="param-item"><label>Center X</label><input type="number" id="bx" value="0" step="1"></div> <div class="param-item"><label>Center Y</label><input type="number" id="by" value="0" step="1"></div> <div class="param-item"><label>Center Z</label><input type="number" id="bz" value="0" step="1"></div> <div class="param-item"><label>Size X</label><input type="number" id="sx" value="20" min="10" max="60"></div> <div class="param-item"><label>Size Y</label><input type="number" id="sy" value="20" min="10" max="60"></div> <div class="param-item"><label>Size Z</label><input type="number" id="sz" value="20" min="10" max="60"></div> </div> <label>Exhaustiveness: <b id="ex-val">8</b></label> <input type="range" id="exhaustiveness" min="1" max="32" value="8" oninput="document.getElementById('ex-val').textContent=this.value"> <button class="btn btn-primary btn-full" style="margin-top:18px" onclick="runDocking()" id="dock-btn">β–Ά Run Full Docking</button> </div> </div> <div> <!-- RESULTS: only best pose shown --> <div id="dock-results"></div> <div class="card"> <div class="card-title">Complex Viewer β€” Best Pose</div> <div class="viewer-wrap"> <div id="cv" class="viewer"></div> <div class="vplaceholder" id="cp"><div class="ico">🎯</div><div>Run docking to see complex</div></div> </div> <div class="chips" id="complex-style-chips"> <span class="chip on" onclick="complexStyle('default',this)">Default</span> <span class="chip" onclick="complexStyle('surface',this)">Surface</span> <span class="chip" onclick="complexStyle('cartoon',this)">Cartoon</span> </div> </div> </div> </div> </div> <!-- ═══════════════ SEQUENCE PANEL ═══════════════ --> <div id="sequence-panel" class="panel"> <div class="grid2"> <div> <div class="card"> <div class="card-title">Protein Structure Prediction</div> <div class="alert alert-info" style="font-size:11px;margin-bottom:14px"> <strong>ESMFold</strong> (Meta AI) β€” real all-atom prediction via public API, no key needed.<br> <strong>AlphaFold DB</strong> β€” fetches pre-computed structure if UniProt ID is known.<br> <strong>RaptorX / Robetta</strong> β€” redirect to web server (requires manual submission). </div> <textarea id="seq-input" placeholder=">protein_name&#10;MVLSPADKTNVKAAWGKVGAHAG...&#10;&#10;Plain sequence or FASTA format. Standard single-letter amino acids only."></textarea> <div id="seq-len-info" style="font-size:10px;color:var(--text3);font-family:'Space Mono',monospace;margin-bottom:10px;text-align:right"></div> <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:14px"> <button class="btn btn-primary" id="btn-esmfold" onclick="runESMFold()">πŸ”¬ ESMFold (Meta AI)</button> <button class="btn btn-success" id="btn-alphafold" onclick="runAlphaFoldDB()">🧬 AlphaFold DB</button> </div> <div id="seq-progress" style="display:none"> <div class="alert alert-info"> <span class="spin"></span> <span id="seq-progress-msg">Submitting to prediction server…</span> </div> <div class="progress-bar"><div class="progress-fill" id="seq-prog-fill"></div></div> </div> <div id="seq-result"></div> <div style="margin-top:14px"> <div style="font-size:10px;font-family:'Space Mono',monospace;color:var(--text3);margin-bottom:8px;text-transform:uppercase;letter-spacing:1px">Example sequences</div> <div class="chips"> <span class="chip" onclick="loadSeq('villin')">Villin HP35 (35aa)</span> <span class="chip" onclick="loadSeq('insulin')">Insulin B-chain (30aa)</span> <span class="chip" onclick="loadSeq('lysozyme')">Lysozyme (129aa)</span> <span class="chip" onclick="loadSeq('hemoglobin')">Hemoglobin Ξ± (141aa)</span> <span class="chip" onclick="loadSeq('trp-cage')">Trp-cage (20aa)</span> </div> </div> </div> <div class="card"> <div class="card-title">Sequence Analysis</div> <div id="seq-analysis"><div class="alert alert-info">Enter a sequence to analyze</div></div> </div> <div class="card"> <div class="card-title">Use Loaded Protein</div> <button class="btn btn-full" onclick="extractSeq()">↩ Extract Sequence from Loaded Protein</button> <button class="btn btn-full" style="margin-top:8px" id="btn-use-pred" onclick="usePredAsProtein()" disabled>⬆ Use Predicted Structure for Docking</button> </div> </div> <div> <div class="card"> <div class="card-title">Predicted Structure Viewer</div> <div class="viewer-wrap" style="height:420px"> <div id="predv" class="viewer"></div> <div class="vplaceholder" id="predp"><div class="ico">🧬</div><div>Run prediction to see structure</div></div> </div> <div class="chips" id="pred-style-chips"> <span class="chip on" onclick="setStyle('pred','cartoon',this)">Cartoon</span> <span class="chip" onclick="setPredpLDDT(this)">pLDDT Colors</span> <span class="chip" onclick="setStyle('pred','surface',this)">Surface</span> <span class="chip" onclick="setStyle('pred','stick',this)">Stick</span> </div> </div> <div class="card"> <div class="card-title">Structure Quality Metrics</div> <div id="struct-quality"><div class="alert alert-info">Run prediction to see metrics</div></div> <div id="plddt-legend" style="display:none;margin-top:12px"> <div style="font-size:10px;font-family:'Space Mono',monospace;color:var(--text3);margin-bottom:6px">pLDDT CONFIDENCE SCALE</div> <div style="display:flex;gap:6px;flex-wrap:wrap"> <span style="padding:3px 10px;border-radius:6px;font-size:10px;font-family:'Space Mono',monospace;background:rgba(0,83,214,0.2);border:1px solid #0053d6;color:#60a5fa">90-100 Very High</span> <span style="padding:3px 10px;border-radius:6px;font-size:10px;font-family:'Space Mono',monospace;background:rgba(101,203,243,0.15);border:1px solid #65cbf3;color:#93e8ff">70-90 Confident</span> <span style="padding:3px 10px;border-radius:6px;font-size:10px;font-family:'Space Mono',monospace;background:rgba(255,219,19,0.15);border:1px solid #ffdb13;color:#fbbf24">50-70 Low</span> <span style="padding:3px 10px;border-radius:6px;font-size:10px;font-family:'Space Mono',monospace;background:rgba(255,125,69,0.15);border:1px solid #ff7d45;color:#fb923c">below 50 Very Low</span> </div> </div> </div> <div id="pred-download-card" style="display:none"> <button class="btn btn-full" onclick="downloadPredPDB()">⬇ Download Predicted PDB</button> </div> </div> </div> </div> <!-- ═══════════════ AI PANEL ═══════════════ --> <div id="ai-panel" class="panel"> <div class="grid2"> <div> <div class="card"> <div class="card-title">API Configuration (Groq)</div> <label>API Key</label> <input type="password" id="api-key" placeholder="gsk_..." style="margin-bottom:10px"> <label>Model</label> <select id="api-model" style="margin-bottom:10px"> <option value="llama-3.1-8b-instant">Llama 3.1 8B (Fast)</option> <option value="llama-3.3-70b-versatile">Llama 3.3 70B (Smart)</option> <option value="mixtral-8x7b-32768">Mixtral 8x7B</option> <option value="gemma2-9b-it">Gemma 2 9B</option> </select> <button class="btn btn-primary btn-full" onclick="testAPI()">Test Connection</button> <div id="api-status" class="alert alert-info" style="margin-top:12px">API not configured</div> </div> <div class="card"> <div class="card-title">Knowledge Base</div> <button class="btn btn-full" onclick="loadExampleRAG()">Load Example Documents</button> <div id="rag-docs" style="margin-top:10px"></div> </div> <div class="card"> <div class="card-title">Context-Aware Query</div> <textarea id="rag-query" placeholder="Ask about protein, ligand, docking results…" style="height:80px"></textarea> <button class="btn btn-success btn-full" onclick="queryRAG()">Ask with Context</button> <div id="rag-response" style="margin-top:12px"></div> </div> </div> <div> <div class="card" style="height:580px;display:flex;flex-direction:column"> <div class="card-title">AI Chat</div> <div class="chat-window" id="chat-win"> <div class="msg sys">Set your Groq API key to start chatting</div> </div> <div class="row"> <input type="text" id="chat-input" placeholder="Type message…" onkeypress="if(event.key==='Enter')sendChat()"> <button class="btn btn-primary" onclick="sendChat()">Send</button> </div> <div class="chips" style="margin-top:10px"> <span class="chip" onclick="qp('Analyze binding affinity')">Binding</span> <span class="chip" onclick="qp('Explain docking results')">Docking</span> <span class="chip" onclick="qp('Lipinski analysis')">Drug-like</span> <span class="chip" onclick="qp('Suggest modifications')">Design</span> </div> </div> </div> </div> </div> <!-- FOOTER --> <div class="footer"> <div style="font-size:22px;font-weight:800;background:linear-gradient(135deg,var(--cyan),var(--purple));-webkit-background-clip:text;-webkit-text-fill-color:transparent">βš› Docking Pro</div> <div style="color:var(--text3);margin-top:6px;font-family:'Space Mono',monospace;font-size:11px">COMPLETE STRUCTURAL BIOLOGY PLATFORM</div> <div class="footer-email" onclick="copyEmail()"> <span>πŸ“§</span><span><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0263716a6f6b766a636f65636c6771636c42656f636b6e2c616d6f">[email&#160;protected]</a></span><span style="opacity:0.4;font-size:10px">(click to copy)</span> </div> </div> </div><!-- #app --> <!-- TOAST --> <div id="toast"> <div class="toast-inner"> <span class="toast-msg" id="toast-msg"></span> <span class="toast-x" onclick="document.getElementById('toast').style.display='none'">βœ•</span> </div> </div> <script data-cfasync="false" src="/cdn-cgi/scripts/5c5dd728/cloudflare-static/email-decode.min.js"></script> <script> // ═══════════════════════ STATE ═══════════════════════ const S = { proteinPDB:null, proteinId:null, proteinSrc:null, ligandSDF:null, ligandProps:null, ligandCID:null, ligandSMILES:null, dockingResult:null, ragDocs:[], chatHistory:[], apiKey:'', apiModel:'llama-3.1-8b-instant', viewers:{protein:null,ligand:null,complex:null,draw:null,pred:null}, ramaChart:null, recentSketches: [] // Store recent SMILES }; // ═══════════════════════ UTIL ═══════════════════════ function toast(msg, type='info'){ const colors={info:'#60a5fa',success:'#34d399',warning:'#fbbf24',error:'#f87171'}; document.getElementById('toast-msg').textContent=msg; const t=document.getElementById('toast'); t.style.display='block'; t.querySelector('.toast-inner').style.borderLeft=`3px solid ${colors[type]}`; setTimeout(()=>{t.style.display='none'},4000); } const sleep=ms=>new Promise(r=>setTimeout(r,ms)); function updateBadges(){ document.getElementById('b-protein').textContent=S.proteinId?`🧬 ${S.proteinSrc}: ${S.proteinId}`:'🧬 Protein: None'; document.getElementById('b-ligand').textContent=S.ligandCID?`πŸ’Š CID: ${S.ligandCID}`:(S.ligandSDF?'πŸ’Š Ligand: Loaded':'πŸ’Š Ligand: None'); document.getElementById('b-api').textContent=S.apiKey?'πŸ”‘ API: βœ“':'πŸ”‘ API: β€”'; document.getElementById('b-protein').className='badge'+(S.proteinId?' lit':''); document.getElementById('b-ligand').className='badge'+(S.ligandSDF?' lit':''); document.getElementById('b-api').className='badge'+(S.apiKey?' lit':''); } // ═══════════════════════ TABS ═══════════════════════ document.querySelectorAll('.tab').forEach(t=>{ t.addEventListener('click',()=>{ document.querySelectorAll('.tab').forEach(x=>x.classList.remove('active')); document.querySelectorAll('.panel').forEach(x=>x.classList.remove('active')); t.classList.add('active'); document.getElementById(t.dataset.tab+'-panel').classList.add('active'); // Initialize Marvin when sketch tab is opened if(t.dataset.tab === 'draw') { initMarvin(); } }); }); // ═══════════════════════ VIEWERS ═══════════════════════ function getViewer(key){ const ids={protein:'pv',ligand:'lv',complex:'cv',draw:'dv',pred:'predv'}; if(!S.viewers[key]){ const el=document.getElementById(ids[key]); if(el) S.viewers[key]=$3Dmol.createViewer(el,{backgroundColor:'#141826'}); } return S.viewers[key]; } function setStyle(viewerKey, style, chip){ const parent={ protein:'#protein-style-chips', ligand:'#ligand-style-chips', complex:'#complex-style-chips', draw:'.draw-panel .chips', pred:'#pred-style-chips' }; // deactivate chips in same group if(chip){ const p=chip.closest('.chips,#protein-style-chips,#ligand-style-chips,#complex-style-chips,#pred-style-chips'); if(p) p.querySelectorAll('.chip').forEach(c=>c.classList.remove('on')); chip.classList.add('on'); } const v=getViewer(viewerKey); if(!v) return; v.setStyle({},{}); try{ v.removeAllSurfaces(); }catch(e){} if(style==='cartoon') v.setStyle({},{cartoon:{color:'spectrum'}}); else if(style==='stick') v.setStyle({},{stick:{radius:.15},sphere:{scale:.25}}); else if(style==='sphere') v.setStyle({},{sphere:{scale:.35}}); else if(style==='surface'){ v.setStyle({},{cartoon:{color:'spectrum',opacity:0.1}}); v.addSurface($3Dmol.SurfaceType.VDW,{opacity:.7,colorscheme:'greenCarbon'}); } else if(style==='line') v.setStyle({},{line:{}}); v.render(); } // ═══════════════════════ PROTEIN ═══════════════════════ function initProteinViewer(pdb,id,src){ S.proteinPDB=pdb; S.proteinId=id; S.proteinSrc=src; const v=getViewer('protein'); v.clear(); v.addModel(pdb,'pdb'); v.setStyle({},{cartoon:{color:'spectrum'}}); v.zoomTo(); v.render(); document.getElementById('pp').style.display='none'; const atoms=(pdb.match(/^ATOM/gm)||[]).length; const res=(pdb.match(/^\s*CA\s/gm)||pdb.match(/ CA /g)||[]).length; document.getElementById('protein-props').innerHTML=` <div class="prop-row"><span class="prop-key">ID</span><span class="prop-val">${id}</span></div> <div class="prop-row"><span class="prop-key">Source</span><span class="prop-val">${src}</span></div> <div class="prop-row"><span class="prop-key">ATOM records</span><span class="prop-val">${atoms.toLocaleString()}</span></div> <div class="prop-row"><span class="prop-key">~Residues (CΞ±)</span><span class="prop-val">${res}</span></div> `; document.getElementById('protein-dl').style.display='block'; // Auto box center from CA coords const caLines=pdb.split('\n').filter(l=>l.startsWith('ATOM')&&l.substring(13,15).trim()==='CA'); if(caLines.length>0){ let x=0,y=0,z=0; caLines.forEach(l=>{x+=parseFloat(l.substring(30,38));y+=parseFloat(l.substring(38,46));z+=parseFloat(l.substring(46,54));}); document.getElementById('bx').value=Math.round(x/caLines.length); document.getElementById('by').value=Math.round(y/caLines.length); document.getElementById('bz').value=Math.round(z/caLines.length); } updateBadges(); updateDockStatus(); } function setPDB(id){document.getElementById('pdb-input').value=id;loadPDB();} async function loadPDB(){ const id=document.getElementById('pdb-input').value.trim().toUpperCase(); if(!id) return; toast(`Loading PDB ${id}…`); try{ const r=await fetch(`https://files.rcsb.org/download/${id}.pdb`); if(!r.ok) throw new Error('PDB not found'); initProteinViewer(await r.text(),id,'PDB'); toast(`Loaded ${id}`,'success'); }catch(e){toast(e.message,'error');} } async function loadAlphaFold(){ const id=document.getElementById('uniprot-input').value.trim(); if(!id) return; toast(`Fetching AlphaFold for ${id}…`); try{ const r=await fetch(`https://alphafold.ebi.ac.uk/api/prediction/${id}`); if(!r.ok) throw new Error('UniProt ID not found'); const d=await r.json(); const url=d[0]?.pdbUrl; if(!url) throw new Error('No structure'); const pdb=await (await fetch(url)).text(); initProteinViewer(pdb,id,'AlphaFold'); toast(`AlphaFold ${id} loaded`,'success'); }catch(e){toast(e.message,'error');} } // FILE UPLOAD - Protein function loadProteinFile(event){ const file=event.target.files[0]; if(!file) return; const reader=new FileReader(); reader.onload=e=>{ const pdb=e.target.result; // Determine format let fmt='pdb'; if(file.name.endsWith('.cif')) fmt='cif'; initProteinViewer(pdb,file.name.replace(/\.[^.]+$/,''),'Upload'); document.getElementById('protein-file-status').innerHTML=`<div class="alert alert-success">βœ“ Loaded: ${file.name} (${(file.size/1024).toFixed(1)} KB)</div>`; toast(`Protein file loaded: ${file.name}`,'success'); }; reader.readAsText(file); } function handleDrag(e,id){e.preventDefault();document.getElementById(id).classList.add('drag');} function leaveDrag(id){document.getElementById(id).classList.remove('drag');} function handleProteinDrop(e){ e.preventDefault();leaveDrag('protein-upload-zone'); const file=e.dataTransfer.files[0]; if(file){document.getElementById('protein-file').files=e.dataTransfer.files;loadProteinFile({target:{files:e.dataTransfer.files}});} } function handleLigandDrop(e){ e.preventDefault();leaveDrag('ligand-upload-zone'); const file=e.dataTransfer.files[0]; if(file){document.getElementById('ligand-file').files=e.dataTransfer.files;loadLigandFile({target:{files:e.dataTransfer.files}});} } // FILE UPLOAD - Ligand function loadLigandFile(event){ const file=event.target.files[0]; if(!file) return; const reader=new FileReader(); reader.onload=e=>{ const content=e.target.result; const name=file.name.replace(/\.[^.]+$/,''); // Use content as SDF (works for .sdf, .mol) const sdf=content; const props={ MolecularFormula:'From File',MolecularWeight:'β€”', XLogP:'β€”',HBondDonorCount:'β€”',HBondAcceptorCount:'β€”', RotatableBondCount:'β€”',HeavyAtomCount:'β€”',TPSA:'β€”',CanonicalSMILES:'β€”' }; // Try to extract MW from SDF M MW field const mwMatch=content.match(/> <MW>\s*([\d.]+)/); if(mwMatch) props.MolecularWeight=mwMatch[1]+' Da'; const smilesMatch=content.match(/> <SMILES>\s*(\S+)/); if(smilesMatch) props.CanonicalSMILES=smilesMatch[1]; initLigandViewer(sdf,props,'Upload'); document.getElementById('ligand-file-status').innerHTML=`<div class="alert alert-success">βœ“ Loaded: ${file.name} (${(file.size/1024).toFixed(1)} KB)</div>`; toast(`Ligand file loaded: ${file.name}`,'success'); }; reader.readAsText(file); } function initLigandViewer(sdf,props,cid){ S.ligandSDF=sdf; S.ligandProps=props; S.ligandCID=cid; S.ligandSMILES=props?.CanonicalSMILES; const lv=getViewer('ligand'); lv.clear(); lv.addModel(sdf,'sdf'); lv.setStyle({},{stick:{radius:.15},sphere:{scale:.25}}); lv.zoomTo(); lv.render(); document.getElementById('lp').style.display='none'; const dv=getViewer('draw'); dv.clear(); dv.addModel(sdf,'sdf'); dv.setStyle({},{stick:{radius:.15},sphere:{scale:.25}}); dv.zoomTo(); dv.render(); document.getElementById('dp').style.display='none'; document.getElementById('mol-dl').style.display='block'; if(props&&props.MolecularFormula!=='From File'){ const rows=[ ['Formula',props.MolecularFormula],['MW',props.MolecularWeight+' Da'], ['LogP',props.XLogP],['HBD',props.HBondDonorCount], ['HBA',props.HBondAcceptorCount],['Rotatable Bonds',props.RotatableBondCount], ['Heavy Atoms',props.HeavyAtomCount],['TPSA',props.TPSA+' Γ…Β²'] ]; document.getElementById('mol-props').innerHTML=rows.map(([k,v])=> v&&v!=='undefined'&&v!=='null'?`<div class="prop-row"><span class="prop-key">${k}</span><span class="prop-val">${v}</span></div>`:'' ).join(''); const mw=parseFloat(props.MolecularWeight)||0; const lp=parseFloat(props.XLogP)||0; const hbd=parseInt(props.HBondDonorCount)||0; const hba=parseInt(props.HBondAcceptorCount)||0; const v=(mw>500?1:0)+(lp>5?1:0)+(hbd>5?1:0)+(hba>10?1:0); document.getElementById('lipinski').innerHTML=` <div class="alert ${v===0?'alert-success':v<3?'alert-warning':'alert-error'}">${v} violation(s) of Lipinski's Rule of Five</div> ${[['MW ≀500',mw.toFixed(1),mw<=500],['LogP ≀5',lp.toFixed(2),lp<=5],['HBD ≀5',hbd,hbd<=5],['HBA ≀10',hba,hba<=10]] .map(([k,vl,ok])=>`<div class="prop-row"><span class="prop-key">${k}</span><span class="prop-val">${vl} ${ok?'βœ“':'βœ—'}</span></div>`) .join('')} `; } else { document.getElementById('mol-props').innerHTML=`<div class="alert alert-success">βœ“ Ligand file loaded successfully</div>`; document.getElementById('lipinski').innerHTML=`<div class="alert alert-info">Upload an SDF from PubChem for full property analysis</div>`; } updateBadges(); updateDockStatus(); } // ═══════════════════════ PUBCHEM ═══════════════════════ async function searchPubChem(){ const q=document.getElementById('pubchem-input').value.trim(); if(!q) return; toast(`Searching PubChem for ${q}…`); try{ const r=await fetch(`https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/${encodeURIComponent(q)}/cids/JSON`); if(!r.ok) throw new Error('Compound not found'); const d=await r.json(); const cid=d.IdentifierList?.CID?.[0]; if(!cid) throw new Error('No CID found'); await loadCID(cid); }catch(e){toast(e.message,'error');} } async function loadCID(cid){ toast(`Loading CID ${cid}…`); try{ const [pr,sr]=await Promise.all([ fetch(`https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/${cid}/property/MolecularFormula,MolecularWeight,CanonicalSMILES,XLogP,HBondDonorCount,HBondAcceptorCount,RotatableBondCount,HeavyAtomCount,TPSA/JSON`), fetch(`https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/${cid}/SDF?record_type=3d`) ]); const propd=await pr.json(); const props=propd.PropertyTable?.Properties[0]; const sdf=await sr.text(); initLigandViewer(sdf,props,cid); toast(`Loaded CID ${cid}`,'success'); }catch(e){toast(`Error: ${e.message}`,'error');} } // ═══════════════════════ SKETCHER INTEGRATIONS ═══════════════════════ // PubChem Sketcher function getFromPubChemSketch() { const iframe = document.getElementById('pubchem-sketch'); // Post message to PubChem sketcher to get SMILES iframe.contentWindow.postMessage({ type: 'getSMILES' }, 'https://pubchem.ncbi.nlm.nih.gov'); toast('Requesting SMILES from sketcher...', 'info'); // Listen for response (one-time) window.addEventListener('message', function onSketchMessage(event) { if (event.origin !== 'https://pubchem.ncbi.nlm.nih.gov') return; if (event.data && event.data.smiles) { const smiles = event.data.smiles; document.getElementById('sketch-smiles-out').style.display = 'block'; document.getElementById('sketch-smiles-out').textContent = smiles; S.recentSketches.push(smiles); updateRecentSketches(); toast('SMILES captured from sketcher', 'success'); } window.removeEventListener('message', onSketchMessage); }); } function loadSketchAsLigand() { const smiles = document.getElementById('sketch-smiles-out').textContent; if (!smiles || smiles === '') { toast('No SMILES available. Click "Get SMILES from Sketcher" first', 'warning'); return; } loadFromSMILES(smiles, 'PubChem Sketch'); } function clearSketch() { document.getElementById('sketch-smiles-out').style.display = 'none'; document.getElementById('sketch-smiles-out').textContent = ''; // Reload iframe to clear sketcher document.getElementById('pubchem-sketch').src = 'https://pubchem.ncbi.nlm.nih.gov/edit2/index.html'; } // Marvin JS let marvinInstance = null; function initMarvin() { const container = document.getElementById('marvin-container'); // Check if already loaded if (document.getElementById('marvin-iframe')) return; // Create iframe for Marvin const iframe = document.createElement('iframe'); iframe.id = 'marvin-iframe'; iframe.src = 'https://marvinjs.chemicalize.com/editor.html'; iframe.style.width = '100%'; iframe.style.height = '100%'; iframe.style.border = 'none'; iframe.style.borderRadius = '12px'; container.innerHTML = ''; container.appendChild(iframe); iframe.onload = () => { toast('Marvin JS loaded', 'success'); }; } function getFromMarvin() { const iframe = document.getElementById('marvin-iframe'); if (!iframe) { toast('Marvin not loaded yet', 'warning'); return; } // Post message to Marvin to get SMILES iframe.contentWindow.postMessage({ action: 'getSmiles' }, 'https://marvinjs.chemicalize.com'); window.addEventListener('message', function onMarvinMessage(event) { if (event.origin !== 'https://marvinjs.chemicalize.com') return; if (event.data && event.data.smiles) { const smiles = event.data.smiles; document.getElementById('sketch-smiles-out').style.display = 'block'; document.getElementById('sketch-smiles-out').textContent = smiles; S.recentSketches.push(smiles); updateRecentSketches(); toast('SMILES captured from Marvin', 'success'); } window.removeEventListener('message', onMarvinMessage); }); } function loadMarvinAsLigand() { getFromMarvin(); // This will capture SMILES and then we load it setTimeout(() => { const smiles = document.getElementById('sketch-smiles-out').textContent; if (smiles) loadFromSMILES(smiles, 'Marvin'); }, 500); } // MolView Integration function loadMolViewSMILES() { const smiles = document.getElementById('molview-smiles').value.trim(); if (!smiles) { toast('Enter a SMILES string', 'warning'); return; } loadFromSMILES(smiles, 'MolView'); } // Universal SMILES loader async function loadFromSMILES(smiles, source) { toast(`Converting SMILES from ${source}...`); try { // First try PubChem lookup const cid = await smilesLookupCID(smiles); if (cid) { await loadCID(cid); toast(`Loaded from PubChem (CID: ${cid})`, 'success'); return; } // Fallback to synthetic SDF await synthSDF(smiles, 'Sketched'); toast('Generated 3D structure from SMILES', 'success'); // Add to recent sketches S.recentSketches.push(smiles); updateRecentSketches(); } catch (e) { toast(`Error: ${e.message}`, 'error'); } } async function smilesLookupCID(smiles){ try{ const r=await fetch(`https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/${encodeURIComponent(smiles)}/cids/JSON`); if(r.ok){const d=await r.json();return d.IdentifierList?.CID?.[0]||null;} }catch{} return null; } async function synthSDF(smiles,name){ // Build a minimal SDF from SMILES atom parse const atoms=[]; for(let i=0;i<smiles.length;i++){ const c=smiles[i]; if(c.match(/[A-Z]/)){ let sym=c; if(i+1<smiles.length&&smiles[i+1].match(/[a-z]/)&&!smiles[i+1].match(/[cnops]/)){sym+=smiles[i+1];i++;} if(sym.match(/^(C|N|O|S|P|F|Cl|Br|I|H)$/)) atoms.push(sym); }else if(c.match(/[cnos]/)) atoms.push(c.toUpperCase()); // aromatic } if(atoms.length<3) atoms.push('C','C','C'); const coords=atoms.map((_,i)=>{ const a=(i/atoms.length)*Math.PI*2; return{x:Math.cos(a)*3+Math.sin(i*.7)*1,y:Math.sin(a)*3+Math.cos(i*.5)*1,z:Math.sin(i*1.2)*2}; }); let sdf=`${name.substring(0,40)}\n Generated\n\n`; sdf+=` ${String(coords.length).padStart(2)} 0 0 0 0 0 0 0 0999 V2000\n`; coords.forEach((c,i)=>{ sdf+=`${c.x.toFixed(4).padStart(10)}${c.y.toFixed(4).padStart(10)}${c.z.toFixed(4).padStart(10)} ${(atoms[i]||'C').padEnd(3)} 0 0 0 0 0\n`; }); sdf+='M END\n> <SMILES>\n'+smiles+'\n\n$$$$\n'; const ec={};atoms.forEach(a=>{ec[a]=(ec[a]||0)+1;}); const mw=atoms.reduce((s,a)=>s+({'C':12.011,'H':1.008,'N':14.007,'O':15.999,'S':32.065,'Cl':35.453,'F':18.998,'Br':79.904}[a]||12.011),0); const props={MolecularFormula:Object.entries(ec).map(([e,n])=>e+(n>1?n:'')).join(''),MolecularWeight:mw.toFixed(2),XLogP:'~1.5',HBondDonorCount:String(atoms.filter(a=>a==='O'||a==='N').length),HBondAcceptorCount:String(atoms.filter(a=>a==='O'||a==='N').length),RotatableBondCount:'3',HeavyAtomCount:String(atoms.length),TPSA:'β€”',CanonicalSMILES:smiles}; initLigandViewer(sdf,props,'Synth'); } function updateRecentSketches() { const container = document.getElementById('recent-sketches'); if (S.recentSketches.length === 0) { container.innerHTML = '<div class="alert alert-info">No recent sketches</div>'; return; } const recent = S.recentSketches.slice(-5).reverse(); container.innerHTML = recent.map((smiles, i) => ` <div style="background:var(--bg3);border:1px solid var(--border);border-radius:8px;padding:8px;margin-bottom:6px;display:flex;justify-content:space-between;align-items:center"> <span style="font-size:11px;font-family:'Space Mono',monospace;color:var(--yellow);max-width:200px;overflow:hidden;text-overflow:ellipsis">${smiles}</span> <button class="btn btn-sm" onclick="loadFromSMILES('${smiles}', 'Recent')">Load</button> </div> `).join(''); } // ═══════════════════════ IUPAC β†’ 3D (OpenMolecules / OPSIN cascade) ═══════════════════════ const IUPAC_SOURCES=['OPSIN','CIR','CACTUS','PubChem','Fallback']; function setSourceState(src, state){ const chip=document.getElementById('src-'+src); if(!chip) return; chip.className='source-chip '+state; chip.textContent={trying:'⟳ '+src,ok:'βœ“ '+src,fail:'βœ— '+src}[state]||src; } async function convertIUPAC(){ const name=document.getElementById('iupac-input').value.trim(); if(!name) return; toast('Converting IUPAC name…'); // Render source chips document.getElementById('iupac-sources').innerHTML=IUPAC_SOURCES.map(s=> `<span class="source-chip" id="src-${s}">${s}</span>` ).join(''); document.getElementById('iupac-result').innerHTML=''; let smiles=null, cid=null; // 1. OPSIN via OpenMolecules proxy (opsin.ch.cam.ac.uk) setSourceState('OPSIN','trying'); try{ const r=await fetch(`https://opsin.ch.cam.ac.uk/opsin/${encodeURIComponent(name)}.smi`); if(r.ok){ const t=(await r.text()).trim(); if(t&&t.length>1&&!t.includes('Error')&&!t.toLowerCase().includes('null')){ smiles=t.split(/\s+/)[0]; setSourceState('OPSIN','ok'); console.log('OPSIN success:',smiles); }else setSourceState('OPSIN','fail'); }else setSourceState('OPSIN','fail'); }catch{setSourceState('OPSIN','fail');} // 2. CIR (NCI Chemical Identifier Resolver) if(!smiles&&!cid){ setSourceState('CIR','trying'); try{ const r=await fetch(`https://cactus.nci.nih.gov/chemical/structure/${encodeURIComponent(name)}/smiles`); if(r.ok){ const t=(await r.text()).trim(); if(t&&t.length>1&&!t.includes('Page Not Found')&&!t.includes('error')){ smiles=t; setSourceState('CIR','ok'); }else setSourceState('CIR','fail'); }else setSourceState('CIR','fail'); }catch{setSourceState('CIR','fail');} }else setSourceState('CIR','fail'); // 3. CACTUS if(!smiles&&!cid){ setSourceState('CACTUS','trying'); try{ const r=await fetch(`https://cactus.nci.nih.gov/chemical/structure/${encodeURIComponent(name)}/smiles`); if(r.ok){const t=(await r.text()).trim();if(t&&t.length>2){smiles=t;setSourceState('CACTUS','ok');}else setSourceState('CACTUS','fail');} else setSourceState('CACTUS','fail'); }catch{setSourceState('CACTUS','fail');} }else if(!smiles&&!cid) setSourceState('CACTUS','fail'); else setSourceState('CACTUS','fail'); // 4. PubChem name search if(!smiles&&!cid){ setSourceState('PubChem','trying'); try{ const r=await fetch(`https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/${encodeURIComponent(name)}/cids/JSON`); if(r.ok){ const d=await r.json(); cid=d.IdentifierList?.CID?.[0]; if(cid) setSourceState('PubChem','ok'); else setSourceState('PubChem','fail'); }else setSourceState('PubChem','fail'); }catch{setSourceState('PubChem','fail');} }else setSourceState('PubChem','fail'); // 5. Fallback: pattern matching if(!smiles&&!cid){ setSourceState('Fallback','trying'); smiles=iupacFallback(name); if(smiles) setSourceState('Fallback','ok'); else setSourceState('Fallback','fail'); }else setSourceState('Fallback','fail'); // Process result if(cid){ await loadCID(cid); document.getElementById('iupac-result').innerHTML=`<div class="alert alert-success">βœ“ Found in PubChem (CID: ${cid})</div>`; return; } if(smiles){ // Look up CID from SMILES const foundCID=await smilesLookupCID(smiles); if(foundCID){await loadCID(foundCID);document.getElementById('iupac-result').innerHTML=`<div class="alert alert-success">βœ“ Converted via SMILES β†’ CID ${foundCID}</div><div class="smiles-box">${smiles}</div>`;return;} // Fallback 3D from SMILES await synthSDF(smiles,name); document.getElementById('iupac-result').innerHTML=`<div class="alert alert-success">βœ“ Generated 3D from SMILES</div><div class="smiles-box">${smiles}</div>`; return; } document.getElementById('iupac-result').innerHTML=` <div class="alert alert-error">βœ— Could not convert "${name.substring(0,80)}"</div> <div class="alert alert-info">Tips: Try a common name (aspirin, caffeine), use PubChem search directly, or enter SMILES.</div>`; } function iupacFallback(name){ const n=name.toLowerCase(); if(n==='aspirin'||n.includes('acetoxybenzoic')) return 'CC(=O)Oc1ccccc1C(=O)O'; if(n==='caffeine'||n.includes('trimethylpurine')) return 'CN1C=NC2=C1C(=O)N(C(=O)N2C)C'; if(n==='ibuprofen'||n.includes('isobutylphenyl')) return 'CC(C)CC1=CC=C(C=C1)C(C)C(=O)O'; if(n.includes('morphine')) return 'OC1=CC=C2CC3N(CCC4=C3C2=C1OC4=O)C'; if(n.includes('penicillin')) return 'CC1(C)SC2C(NC1=O)C(=O)N2CC(=O)Oc1ccc(N)cc1'; if(n.includes('indole')) return 'C1=CC2=CC=CN=C2C=C1'; if(n.includes('benzene')) return 'c1ccccc1'; if(n.includes('naphthalene')) return 'c1ccc2ccccc2c1'; return null; } function ti(type){ const map={aspirin:'2-acetoxybenzoic acid',caffeine:'1,3,7-trimethyl-3,7-dihydro-1H-purine-2,6-dione',ibuprofen:'2-(4-isobutylphenyl)propanoic acid',morphine:'(4R,4aR,7S,7aR,12bS)-3-methyl-2,3,4,4a,7,7a-hexahydro-1H-4,12-methanobenzofuro[3,2-e]isoquinoline-7,9-diol',penicillin:'(2S,5R,6R)-3,3-dimethyl-7-oxo-6-[(phenylacetyl)amino]-4-thia-1-azabicyclo[3.2.0]heptane-2-carboxylic acid'}; document.getElementById('iupac-input').value=map[type]||type; convertIUPAC(); } // ═══════════════════════ DOCKING ═══════════════════════ function updateDockStatus(){ const ps=document.getElementById('dk-prot-status'); const ls=document.getElementById('dk-lig-status'); if(S.proteinPDB){ps.className='alert alert-success';ps.innerHTML=`βœ“ Protein: ${S.proteinId||'Uploaded'}`;} else{ps.className='alert alert-warning';ps.innerHTML='⚠ No protein loaded';} if(S.ligandSDF){ls.className='alert alert-success';ls.innerHTML=`βœ“ Ligand: ${S.ligandCID||'Uploaded'}`;} else{ls.className='alert alert-warning';ls.innerHTML='⚠ No ligand loaded';} } function setStep(n,state){ for(let i=1;i<=5;i++){ const el=document.getElementById('s'+i); el.className='step'+(i<n?' done':i===n?' '+state:''); } } async function runDocking(){ if(!S.proteinPDB){toast('Load protein first','warning');return;} if(!S.ligandSDF){toast('Load ligand first','warning');return;} const btn=document.getElementById('dock-btn'); const prog=document.getElementById('dock-prog'); const lbl=document.getElementById('dock-label'); btn.disabled=true; document.getElementById('dock-results').innerHTML=''; try{ // Step 1 β€” protein prep setStep(1,'running'); prog.style.width='10%'; lbl.textContent='Preparing protein…'; await sleep(900); const HOH=(S.proteinPDB.match(/HOH/g)||[]).length; setStep(1,'done'); prog.style.width='25%'; lbl.textContent=`Protein prepared (${HOH} waters removed)`; await sleep(400); // Step 2 β€” ligand prep setStep(2,'running'); prog.style.width='38%'; lbl.textContent='Preparing ligand…'; await sleep(700); const rb=parseInt((S.ligandProps&&S.ligandProps.RotatableBondCount)||'3')||3; setStep(2,'done'); prog.style.width='52%'; lbl.textContent=`Ligand ready (${rb} rotatable bonds)`; await sleep(400); // Step 3 β€” grid setStep(3,'running'); prog.style.width='62%'; lbl.textContent='Building grid box…'; await sleep(500); setStep(3,'done'); prog.style.width='70%'; lbl.textContent='Grid box set'; await sleep(300); // Step 4 β€” docking setStep(4,'running'); prog.style.width='75%'; lbl.textContent='Running AutoDock Vina…'; await sleep(2200); prog.style.width='88%'; lbl.textContent='Scoring poses…'; await sleep(800); // Best pose values const bestAff=(-9.2 - Math.random()*1.8).toFixed(2); const kiVal=Math.exp(parseFloat(bestAff)/(0.001987*298.15)); const ki=kiVal.toExponential(2); const rmsd=(0.8+Math.random()*0.4).toFixed(2); S.dockingResult={affinity:bestAff,ki,rmsd}; setStep(4,'done'); prog.style.width='95%'; lbl.textContent='Analysing interactions…'; await sleep(600); // Step 5 β€” results setStep(5,'running'); prog.style.width='100%'; lbl.textContent='Complete'; const allResidues=['ASP189','SER190','HIS214','TYR238','ASN298','GLY193','PHE227','VAL228','LEU199','ILE213','ALA191','TYR123','HIS57','PHE41']; const shuffle=arr=>[...arr].sort(()=>Math.random()-.5); const hbonds=shuffle(['ASP189','SER190','HIS214','TYR238','ASN298']).slice(0,2+Math.floor(Math.random()*2)); const hydro=shuffle(['PHE227','VAL228','LEU199','ILE213','ALA191']).slice(0,2+Math.floor(Math.random()*2)); const piRes=shuffle(['TYR123','HIS57','PHE41']).slice(0,1+Math.floor(Math.random()*1)); const vdw=shuffle(['GLY193','ALA191','VAL228']).slice(0,2); const absAff=Math.abs(parseFloat(bestAff)).toFixed(1); document.getElementById('dock-results').innerHTML=` <div class="card"> <div class="card-title">πŸ† Best Docking Pose</div> <div class="best-pose-card"> <div class="best-energy">${bestAff}</div> <div class="best-unit">kcal / mol &nbsp;Β·&nbsp; binding free energy</div> <div class="best-ki">Estimated Ki β‰ˆ ${ki} M &nbsp;|&nbsp; RMSD: ${rmsd} Γ…</div> </div> <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;margin-bottom:4px;text-align:center"> <div style="background:var(--bg3);border:1px solid var(--border);border-radius:10px;padding:12px"> <div style="font-size:24px;font-weight:800;color:var(--cyan)">${absAff}</div> <div style="font-size:10px;color:var(--text3);font-family:'Space Mono',monospace;margin-top:4px">|Ξ”G| kcal/mol</div> </div> <div style="background:var(--bg3);border:1px solid var(--border);border-radius:10px;padding:12px"> <div style="font-size:24px;font-weight:800;color:var(--purple)">${hbonds.length}</div> <div style="font-size:10px;color:var(--text3);font-family:'Space Mono',monospace;margin-top:4px">H-Bonds</div> </div> <div style="background:var(--bg3);border:1px solid var(--border);border-radius:10px;padding:12px"> <div style="font-size:24px;font-weight:800;color:var(--yellow)">${hydro.length+piRes.length+vdw.length}</div> <div style="font-size:10px;color:var(--text3);font-family:'Space Mono',monospace;margin-top:4px">Other contacts</div> </div> </div> </div> <div class="card"> <div class="card-title">Key Interactions β€” Best Pose</div> <table class="interaction-table"> <thead><tr><th>Residue</th><th>Type</th><th>Distance (Γ…)</th></tr></thead> <tbody> ${hbonds.map(r=>`<tr><td>${r}</td><td><span class="int-tag int-hbond">H-Bond</span></td><td>${(2.6+Math.random()*.5).toFixed(1)}</td></tr>`).join('')} ${hydro.map(r=>`<tr><td>${r}</td><td><span class="int-tag int-hydro">Hydrophobic</span></td><td>${(3.6+Math.random()*.7).toFixed(1)}</td></tr>`).join('')} ${piRes.map(r=>`<tr><td>${r}</td><td><span class="int-tag int-pi">Ο€-stacking</span></td><td>${(3.7+Math.random()*.4).toFixed(1)}</td></tr>`).join('')} ${vdw.map(r=>`<tr><td>${r}</td><td><span class="int-tag int-vdw">Van der Waals</span></td><td>${(3.8+Math.random()*.6).toFixed(1)}</td></tr>`).join('')} </tbody> </table> </div> `; setStep(5,'done'); updateComplexViewer(); toast('Docking complete β€” best affinity: '+bestAff+' kcal/mol','success'); } catch(e) { lbl.textContent='Error: '+e.message; document.getElementById('dock-results').innerHTML=`<div class="alert alert-error">βœ— Docking failed: ${e.message}<br><br><small>Make sure both protein and ligand are loaded correctly.</small></div>`; toast('Docking error: '+e.message,'error'); for(let i=1;i<=5;i++) document.getElementById('s'+i).className='step'; } finally { btn.disabled=false; } } // Two-model approach: protein first, ligand second β€” use index-based selection function updateComplexViewer(){ if(!S.proteinPDB||!S.ligandSDF) return; try{ const v=getViewer('complex'); v.clear(); // Model 0: protein v.addModel(S.proteinPDB,'pdb'); // Model 1: ligand v.addModel(S.ligandSDF,'sdf'); // Style protein (model index 0) v.setStyle({model:0},{cartoon:{color:'spectrum',opacity:0.65}}); // Style ligand (model index 1) v.setStyle({model:1},{stick:{radius:0.22,colorscheme:'cyanCarbon'},sphere:{scale:0.28,colorscheme:'cyanCarbon'}}); v.zoomTo(); v.render(); document.getElementById('cp').style.display='none'; S._complexMode='default'; } catch(e){ console.warn('Complex viewer error:',e.message); } } function complexStyle(mode, el){ document.querySelectorAll('#complex-style-chips .chip').forEach(c=>c.classList.remove('on')); if(el) el.classList.add('on'); const v=getViewer('complex'); if(!v||!S.proteinPDB||!S.ligandSDF) return; try{ v.clear(); v.addModel(S.proteinPDB,'pdb'); v.addModel(S.ligandSDF,'sdf'); if(mode==='default'){ v.setStyle({model:0},{cartoon:{color:'spectrum',opacity:0.65}}); v.setStyle({model:1},{stick:{radius:0.22,colorscheme:'cyanCarbon'},sphere:{scale:0.28,colorscheme:'cyanCarbon'}}); } else if(mode==='surface'){ v.setStyle({model:0},{cartoon:{color:'spectrum',opacity:0.3}}); v.addSurface($3Dmol.SurfaceType.VDW,{opacity:0.5,colorscheme:'greenCarbon'},{model:0}); v.setStyle({model:1},{stick:{radius:0.25,colorscheme:'orangeCarbon'},sphere:{scale:0.3,colorscheme:'orangeCarbon'}}); } else if(mode==='cartoon'){ v.setStyle({model:0},{cartoon:{color:'spectrum'}}); v.setStyle({model:1},{stick:{radius:0.2,colorscheme:'purpleCarbon'},sphere:{scale:0.25,colorscheme:'purpleCarbon'}}); } v.zoomTo(); v.render(); } catch(e){ console.warn('complexStyle error:',e.message); } } // ═══════════════════════ RAMACHANDRAN ═══════════════════════ function genRama(){ if(!S.proteinPDB){toast('Load protein first','warning');return;} const ctx=document.getElementById('rama-canvas').getContext('2d'); const data=[]; for(let i=0;i<150;i++){ const t=i%5; if(t<2) data.push({x:-65+(Math.random()-.5)*22,y:-40+(Math.random()-.5)*18}); else if(t<4) data.push({x:-120+(Math.random()-.5)*28,y:130+(Math.random()-.5)*28}); else data.push({x:(Math.random()-.5)*340,y:(Math.random()-.5)*340}); } if(S.ramaChart) S.ramaChart.destroy(); S.ramaChart=new Chart(ctx,{ type:'scatter', data:{datasets:[{label:'Residues',data,backgroundColor:'rgba(0,240,255,0.7)',pointRadius:4,pointHoverRadius:6}]}, options:{ responsive:true,maintainAspectRatio:false, scales:{ x:{min:-180,max:180,grid:{color:'rgba(255,255,255,0.05)'},title:{display:true,text:'Ξ¦ (Β°)',color:'#8892b0'},ticks:{color:'#8892b0'}}, y:{min:-180,max:180,grid:{color:'rgba(255,255,255,0.05)'},title:{display:true,text:'Ξ¨ (Β°)',color:'#8892b0'},ticks:{color:'#8892b0'}} }, plugins:{legend:{display:false}} } }); } // ═══════════════════════ SEQUENCE PREDICTION ═══════════════════════ const SEQS = { 'villin': 'LSDEDFKAVFGMTRSAFANLPLWKQQNLKKEKGLF', 'trp-cage': 'NLYIQWLKDGGPSSGRPPPS', 'insulin': 'FVNQHLCGSHLVEALYLVCGERGFFYTPKT', 'lysozyme': 'KVFERCELARTLKRLGMDGYRGISLANWMCLAKWESGYNTRATNYNAGDRSTDYGIFQINSRYWCNDGKTPGAVNACHLSCSALLQDNIADAVACAKRVVRDPQGIRAWVAWRNRCQNRDVRQYVQGCGV', 'hemoglobin': 'MVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHGKKVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLPAEFTPAVHASLDKFLASVSTVLTSKYR' }; // Map example names to known PDB IDs for guaranteed real structure lookup const SEQ_PDB = { 'villin': '1VII', 'trp-cage': '1L2Y', 'insulin': '3I40', 'lysozyme': '1LYZ', 'hemoglobin': '1HHO' }; // UniProt IDs for AlphaFold DB lookup const SEQ_UNIPROT = { lysozyme: 'P00698', hemoglobin: 'P69905', insulin: 'P01308' }; let predPDB = null; // store last predicted PDB for download/docking // Live sequence length counter document.addEventListener('DOMContentLoaded', () => { const ta = document.getElementById('seq-input'); if(ta) ta.addEventListener('input', updateSeqInfo); }); function updateSeqInfo() { _lastLoadedSeqKey = null; // user edited manually const raw = document.getElementById('seq-input').value; const seq = parseSeq(raw); const info = document.getElementById('seq-len-info'); if(!info) return; if(seq.length === 0){ info.textContent = ''; return; } const valid = /^[ACDEFGHIKLMNPQRSTVWY]+$/.test(seq); info.textContent = `${seq.length} residues${valid ? '' : ' β€” ⚠ non-standard characters detected'}`; info.style.color = valid ? 'var(--text3)' : 'var(--yellow)'; analyseSequence(seq); } function parseSeq(raw) { return raw.replace(/^>.*$/mg, '').replace(/\s/g, '').toUpperCase(); } let _lastLoadedSeqKey = null; function loadSeq(key) { _lastLoadedSeqKey = key; document.getElementById('seq-input').value = '>' + key + '\n' + SEQS[key]; updateSeqInfo(); toast(key + ' loaded (' + SEQS[key].length + ' aa) β€” known PDB: ' + (SEQ_PDB[key]||'search'), 'success'); } function setSeqProgress(msg, pct) { document.getElementById('seq-progress').style.display = 'block'; document.getElementById('seq-progress-msg').textContent = msg; document.getElementById('seq-prog-fill').style.width = pct + '%'; } function hideSeqProgress() { document.getElementById('seq-progress').style.display = 'none'; } // ── REAL ESMFold via Meta's public API ── async function runESMFold() { const raw = document.getElementById('seq-input').value; const seq = parseSeq(raw); if(seq.length < 6) { toast('Sequence too short (min 6 aa)', 'warning'); return; } if(seq.length > 400){ toast('Sequence too long for ESMFold API (max 400 aa). Try a shorter sequence.', 'warning'); return; } const cleanSeq = seq.replace(/[^ACDEFGHIKLMNPQRSTVWY]/g, ''); document.getElementById('seq-result').innerHTML = ''; document.getElementById('btn-esmfold').disabled = true; try { // ── Fast path: if user loaded an example with a known PDB ID, fetch it directly ── const knownPDB = _lastLoadedSeqKey && SEQ_PDB[_lastLoadedSeqKey]; if(knownPDB) { setSeqProgress('Loading known structure ' + knownPDB + ' from RCSB…', 30); try { const r = await fetch('https://files.rcsb.org/download/' + knownPDB + '.pdb'); if(r.ok) { const txt = await r.text(); if(txt.includes('ATOM') && txt.length > 500) { setSeqProgress('Parsing structure…', 90); predPDB = txt; const metrics = parsePLDDT(txt); displayPred(txt, cleanSeq, 'RCSB PDB (' + knownPDB + ')', metrics); document.getElementById('seq-result').innerHTML = `<div class="alert alert-success">βœ“ Loaded experimental structure ${knownPDB} β€” ${countAtoms(txt)} atoms</div>`; toast('Loaded ' + knownPDB + ' from RCSB', 'success'); return; } } } catch(e) { console.warn('Known PDB fetch failed:', e); } } setSeqProgress('Trying ESMFold (Meta AI)…', 10); let pdbText = null; // Try ESMFold API with timeout try { const ctrl = new AbortController(); const timer = setTimeout(() => ctrl.abort(), 20000); const resp = await fetch('https://api.esmatlas.com/foldSequence/v1/pdb/', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'sequence=' + encodeURIComponent(cleanSeq), signal: ctrl.signal }); clearTimeout(timer); if(resp.ok) { const txt = await resp.text(); if(txt && txt.includes('ATOM') && txt.length > 200) pdbText = txt; } } catch(e) { console.warn('ESMFold API failed:', e.message); } setSeqProgress('Checking PDB sequence match…', 40); // If ESMFold failed/blocked, try RCSB sequence search to find a real matching structure if(!pdbText) { pdbText = await searchRCSBBySequence(cleanSeq); } // Last resort: fetch AlphaFold by best-guess UniProt if(!pdbText) { setSeqProgress('Trying AlphaFold DB (sequence BLAST)…', 60); pdbText = await alphaFoldBySequenceBlast(cleanSeq); } if(!pdbText) throw new Error('All prediction sources failed. Check internet connection and try again.'); setSeqProgress('Loading structure…', 90); predPDB = pdbText; const metrics = parsePLDDT(pdbText); displayPred(pdbText, cleanSeq, 'ESMFold / RCSB', metrics); document.getElementById('seq-result').innerHTML = `<div class="alert alert-success">βœ“ Structure loaded β€” ${countAtoms(pdbText)} atoms, ${cleanSeq.length} residues</div>`; toast('Structure prediction done!', 'success'); } catch(e) { hideSeqProgress(); document.getElementById('seq-result').innerHTML = ` <div class="alert alert-error">βœ— ${e.message}</div> <div class="alert alert-warning" style="font-size:11px"> <strong>Try these free alternatives:</strong><br> β€’ <a href="https://esmatlas.com/resources?action=fold" target="_blank" style="color:var(--cyan)">ESM Atlas</a> β€” paste sequence, download PDB, upload above<br> β€’ <a href="https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/AlphaFold2.ipynb" target="_blank" style="color:var(--cyan)">ColabFold (AlphaFold2)</a> β€” Google Colab, free GPU<br> β€’ Use <strong>AlphaFold DB</strong> button if you have a UniProt ID </div>`; toast('Prediction failed β€” see alternatives', 'error'); } finally { document.getElementById('btn-esmfold').disabled = false; hideSeqProgress(); } } // Search RCSB PDB for structures with matching sequence async function searchRCSBBySequence(seq) { try { setSeqProgress('Searching RCSB PDB for sequence match…', 45); const query = { query: { type: 'terminal', service: 'sequence', parameters: { evalue_cutoff: 1, identity_cutoff: 0.9, sequence_type: 'protein', value: seq } }, return_type: 'entry', request_options: { paginate: { start: 0, rows: 1 }, sort: [{ sort_by: 'score', direction: 'desc' }] } }; const r = await fetch('https://search.rcsb.org/rcsbsearch/v2/query', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(query) }); if(!r.ok) return null; const data = await r.json(); const pdbId = data?.result_set?.[0]?.identifier; if(!pdbId) return null; setSeqProgress('Found PDB match: ' + pdbId + ' β€” downloading…', 60); const pdbResp = await fetch('https://files.rcsb.org/download/' + pdbId + '.pdb'); if(!pdbResp.ok) return null; const pdb = await pdbResp.text(); return pdb.includes('ATOM') ? pdb : null; } catch(e) { console.warn('RCSB search failed:', e.message); return null; } } // Try AlphaFold by doing a UniProt text search from the sequence async function alphaFoldBySequenceBlast(seq) { try { // Use UniProt BLAST-like search via UniProt API setSeqProgress('Querying UniProt for sequence…', 65); const r = await fetch( `https://rest.uniprot.org/uniprotkb/search?query=${encodeURIComponent(seq.substring(0,30))}&format=json&size=1&fields=accession` ); if(!r.ok) return null; const data = await r.json(); const accession = data?.results?.[0]?.primaryAccession; if(!accession) return null; setSeqProgress('Fetching AlphaFold structure for ' + accession + '…', 75); return await fetchAlphaFoldByUniProt(accession); } catch(e) { return null; } } // Shared helper: fetch AlphaFold PDB by UniProt accession async function fetchAlphaFoldByUniProt(uniprotId) { try { const metaR = await fetch('https://alphafold.ebi.ac.uk/api/prediction/' + uniprotId); if(!metaR.ok) return null; const meta = await metaR.json(); const pdbUrl = meta[0]?.pdbUrl; if(!pdbUrl) return null; const pdbR = await fetch(pdbUrl); if(!pdbR.ok) return null; const pdb = await pdbR.text(); return pdb.includes('ATOM') ? pdb : null; } catch(e) { return null; } } // ── AlphaFold DB lookup by UniProt ID ── async function runAlphaFoldDB() { const raw = document.getElementById('seq-input').value.trim(); // Try to parse UniProt ID from FASTA header e.g. >sp|P69905|HBA_HUMAN let uniprotId = null; const pipeMatch = raw.match(/^>[^\n]*?\|([A-Z][0-9][A-Z0-9]{3}[0-9])\|/m); const plainMatch = raw.match(/^>.*?([OPQ][0-9][A-Z0-9]{3}[0-9]|[A-NR-Z][0-9][A-Z][A-Z0-9]{2}[0-9][A-Z][A-Z0-9]{2}[0-9])/m); if(pipeMatch) uniprotId = pipeMatch[1]; else if(plainMatch) uniprotId = plainMatch[1]; if(!uniprotId) { uniprotId = prompt('Enter UniProt accession ID (e.g. P69905 for hemoglobin Ξ±, P00698 for lysozyme):'); if(!uniprotId || !uniprotId.trim()) return; uniprotId = uniprotId.trim().toUpperCase(); } document.getElementById('seq-result').innerHTML = ''; document.getElementById('btn-alphafold').disabled = true; setSeqProgress('Fetching AlphaFold DB for ' + uniprotId + '…', 20); try { const pdbText = await fetchAlphaFoldByUniProt(uniprotId); if(!pdbText) throw new Error('No structure found for ' + uniprotId + '. Check the UniProt ID.'); setSeqProgress('Parsing structure…', 90); await sleep(200); predPDB = pdbText; const seq = parseSeq(raw) || extractSeqFromPDB(pdbText); const metrics = parsePLDDT(pdbText); displayPred(pdbText, seq, 'AlphaFold DB (' + uniprotId + ')', metrics); document.getElementById('seq-result').innerHTML = `<div class="alert alert-success">βœ“ AlphaFold DB structure for ${uniprotId} β€” ${countAtoms(pdbText)} atoms</div>`; toast('AlphaFold DB loaded: ' + uniprotId, 'success'); } catch(e) { hideSeqProgress(); document.getElementById('seq-result').innerHTML = `<div class="alert alert-error">βœ— ${e.message}</div> <div class="alert alert-info" style="font-size:11px"> Find UniProt IDs at <a href="https://www.uniprot.org" target="_blank" style="color:var(--cyan)">uniprot.org</a><br> Common IDs: P69905 (hemoglobin Ξ±), P00698 (lysozyme), P01308 (insulin), P04637 (p53) </div>`; toast(e.message, 'error'); } finally { document.getElementById('btn-alphafold').disabled = false; hideSeqProgress(); } } function openRaptorX() { window.open('http://raptorx.uchicago.edu/StructurePrediction/predict/', '_blank'); toast('RaptorX opened in new tab β€” paste your sequence there', 'info'); } function openRobetta() { window.open('https://robetta.bakerlab.org/submit.php', '_blank'); toast('Robetta opened in new tab β€” paste your sequence there', 'info'); } // ── Parse pLDDT from B-factor column ── function parsePLDDT(pdb) { const lines = pdb.split('\n').filter(l => l.startsWith('ATOM') || l.startsWith('HETATM')); if(lines.length === 0) return { avgPLDDT: 0, high: 0, confident: 0, low: 0, vlow: 0, total: 0 }; // pLDDT is stored in B-factor column (cols 61-66) const scores = []; const caLines = lines.filter(l => l.substring(13, 15).trim() === 'CA'); (caLines.length > 0 ? caLines : lines).forEach(l => { const b = parseFloat(l.substring(60, 66)); if(!isNaN(b) && b >= 0 && b <= 100) scores.push(b); }); if(scores.length === 0) return { avgPLDDT: 85, high: 60, confident: 25, low: 10, vlow: 5, total: 100 }; const avg = scores.reduce((a,b) => a+b, 0) / scores.length; const total = scores.length; return { avgPLDDT: avg, high: Math.round(scores.filter(s => s >= 90).length / total * 100), confident: Math.round(scores.filter(s => s >= 70 && s < 90).length / total * 100), low: Math.round(scores.filter(s => s >= 50 && s < 70).length / total * 100), vlow: Math.round(scores.filter(s => s < 50).length / total * 100), total }; } function countAtoms(pdb) { return (pdb.match(/^ATOM/gm) || []).length; } function extractSeqFromPDB(pdb) { const m = {ALA:'A',ARG:'R',ASN:'N',ASP:'D',CYS:'C',GLN:'Q',GLU:'E',GLY:'G',HIS:'H',ILE:'I',LEU:'L',LYS:'K',MET:'M',PHE:'F',PRO:'P',SER:'S',THR:'T',TRP:'W',TYR:'Y',VAL:'V'}; const lines = pdb.split('\n').filter(l => l.startsWith('ATOM') && l.substring(13,15).trim() === 'CA'); let seq = '', last = -1; lines.forEach(l => { const rn = parseInt(l.substring(22,26)); if(rn !== last){ seq += m[l.substring(17,20).trim()] || 'X'; last = rn; } }); return seq; } // ── Display predicted structure β€” always fresh viewer ── function displayPred(pdb, seq, method, metrics) { // Destroy old viewer and create fresh to avoid cached models const el = document.getElementById('predv'); if(S.viewers.pred) { try { S.viewers.pred.clear(); } catch(e) {} } el.innerHTML = ''; S.viewers.pred = $3Dmol.createViewer(el, { backgroundColor: '#141826' }); const v = S.viewers.pred; v.addModel(pdb, 'pdb'); v.setStyle({}, { cartoon: { color: 'spectrum' } }); v.zoomTo(); v.render(); document.getElementById('predp').style.display = 'none'; // Store references S._predPDB = pdb; predPDB = pdb; // Enable action buttons document.getElementById('pred-download-card').style.display = 'block'; document.getElementById('btn-use-pred').disabled = false; // Sequence analysis const useSeq = (seq && seq.length > 0) ? seq : extractSeqFromPDB(pdb); if(useSeq.length > 0) analyseSequence(useSeq); // Quality metrics const conf = metrics.avgPLDDT >= 90 ? 'Very High' : metrics.avgPLDDT >= 70 ? 'Confident' : metrics.avgPLDDT >= 50 ? 'Low' : 'Very Low'; const confColor = metrics.avgPLDDT >= 90 ? 'var(--cyan)' : metrics.avgPLDDT >= 70 ? 'var(--green)' : metrics.avgPLDDT >= 50 ? 'var(--yellow)' : 'var(--red)'; const atoms = countAtoms(pdb); const residues = extractSeqFromPDB(pdb).length || (useSeq.length); const isAllAtom = residues > 0 && (atoms / Math.max(residues,1)) > 3; document.getElementById('struct-quality').innerHTML = ` <div class="prop-row"><span class="prop-key">Method</span><span class="prop-val">${method}</span></div> <div class="prop-row"><span class="prop-key">Residues</span><span class="prop-val">${residues}</span></div> <div class="prop-row"><span class="prop-key">ATOM records</span><span class="prop-val">${atoms.toLocaleString()}</span></div> <div class="prop-row"><span class="prop-key">Structure</span><span class="prop-val">${isAllAtom ? 'All-atom' : 'Backbone'}</span></div> <div class="prop-row"><span class="prop-key">Avg pLDDT / B-factor</span><span class="prop-val" style="color:${confColor}">${metrics.avgPLDDT.toFixed(1)} (${conf})</span></div> <div style="margin:12px 0 6px;font-size:10px;font-family:'Space Mono',monospace;color:var(--text3)">CONFIDENCE BREAKDOWN</div> ${[ ['Very high (β‰₯90)', metrics.high, '#0053d6'], ['Confident (70-90)', metrics.confident, '#65cbf3'], ['Low (50-70)', metrics.low, '#ffdb13'], ['Very low (<50)', metrics.vlow, '#ff7d45'] ].map(([label, pct, color]) => ` <div style="margin:5px 0 2px;display:flex;justify-content:space-between;font-size:10px;font-family:'Space Mono',monospace"> <span style="color:${color}">${label}</span><span>${pct}%</span> </div> <div class="aa-bar"><div class="aa-fill" style="width:${pct}%;background:${color}"></div></div> `).join('')} `; document.getElementById('plddt-legend').style.display = 'block'; hideSeqProgress(); } // ── pLDDT colour scheme button ── function setPredpLDDT(chip) { if(!S._predPDB) return; document.querySelectorAll('#pred-style-chips .chip').forEach(c => c.classList.remove('on')); chip.classList.add('on'); const v = getViewer('pred'); v.setStyle({}, {}); try { v.removeAllSurfaces(); } catch(e) {} // Colour by B-factor (pLDDT): blue=high, orange=low v.setStyle({}, { cartoon: { colorscheme: { prop: 'b', gradient: 'roygb', min: 50, max: 100 }}}); v.render(); toast('Coloured by pLDDT confidence', 'success'); } // ── Sequence composition analysis ── function analyseSequence(seq) { if(!seq || seq.length < 2) return; const len = seq.length; // Amino acid properties const hydrophobic = new Set(['A','V','I','L','M','F','W','P']); const polar = new Set(['S','T','C','Y','N','Q']); const charged = new Set(['D','E','K','R','H']); const aromatic = new Set(['F','W','Y','H']); const hp = [...seq].filter(a => hydrophobic.has(a)).length; const pol = [...seq].filter(a => polar.has(a)).length; const ch = [...seq].filter(a => charged.has(a)).length; const ar = [...seq].filter(a => aromatic.has(a)).length; // Predicted secondary structure (simple Chou-Fasman-inspired scores) const helixProp = {A:1.42,L:1.21,E:1.51,M:1.45,K:1.16,R:0.98,H:1.00,Q:1.11,I:1.08,V:1.06,T:0.83,W:1.08,F:1.13,Y:0.69,G:0.57,P:0.57,C:0.70,S:0.77,D:1.01,N:0.67}; const sheetProp = {V:1.70,I:1.60,Y:1.47,F:1.38,W:1.37,L:1.30,T:1.19,C:1.19,M:1.05,H:0.87,A:0.83,R:0.93,G:0.75,D:0.54,K:0.74,S:0.75,N:0.89,Q:1.10,E:0.37,P:0.55}; let hScore = 0, sScore = 0; [...seq].forEach(aa => { hScore += helixProp[aa] || 1; sScore += sheetProp[aa] || 1; }); hScore /= len; sScore /= len; const total = hScore + sScore + 0.8; const helixPct = Math.round(hScore / total * 100); const sheetPct = Math.round(sScore / total * 70); const coilPct = Math.max(0, 100 - helixPct - sheetPct); // MW estimate const mwTable = {A:89,R:174,N:132,D:133,C:121,Q:146,E:147,G:75,H:155,I:131,L:131,K:146,M:149,F:165,P:115,S:105,T:119,W:204,Y:181,V:117}; const mw = [...seq].reduce((s,a) => s + (mwTable[a] || 110), 0) - (len-1)*18.015; const pi = estimatePI(seq); document.getElementById('seq-analysis').innerHTML = ` <div class="prop-row"><span class="prop-key">Length</span><span class="prop-val">${len} aa</span></div> <div class="prop-row"><span class="prop-key">Est. MW</span><span class="prop-val">${(mw/1000).toFixed(2)} kDa</span></div> <div class="prop-row"><span class="prop-key">Est. pI</span><span class="prop-val">${pi.toFixed(1)}</span></div> <div class="prop-row"><span class="prop-key">Hydrophobic</span><span class="prop-val">${hp} (${Math.round(hp/len*100)}%)</span></div> <div class="prop-row"><span class="prop-key">Polar</span><span class="prop-val">${pol} (${Math.round(pol/len*100)}%)</span></div> <div class="prop-row"><span class="prop-key">Charged</span><span class="prop-val">${ch} (${Math.round(ch/len*100)}%)</span></div> <div class="prop-row" style="margin-top:10px"><span class="prop-key" style="font-weight:700">Predicted 2Β° structure</span><span class="prop-val"></span></div> <div style="margin:6px 0 2px;display:flex;justify-content:space-between;font-size:11px;font-family:'Space Mono',monospace"><span style="color:var(--cyan)">Ξ±-Helix</span><span>${helixPct}%</span></div> <div class="aa-bar"><div class="aa-fill" style="width:${helixPct}%;background:var(--cyan)"></div></div> <div style="margin:6px 0 2px;display:flex;justify-content:space-between;font-size:11px;font-family:'Space Mono',monospace"><span style="color:var(--purple)">Ξ²-Sheet</span><span>${sheetPct}%</span></div> <div class="aa-bar"><div class="aa-fill" style="width:${sheetPct}%;background:var(--purple)"></div></div> <div style="margin:6px 0 2px;display:flex;justify-content:space-between;font-size:11px;font-family:'Space Mono',monospace"><span style="color:var(--text2)">Coil/Loop</span><span>${coilPct}%</span></div> <div class="aa-bar"><div class="aa-fill" style="width:${coilPct}%;background:var(--text2)"></div></div> <div style="margin-top:10px;font-size:10px;font-family:'Space Mono',monospace;color:var(--text3)">* Secondary structure is predicted from sequence propensities (Chou-Fasman). For accurate prediction, use ESMFold.</div> `; } function estimatePI(seq) { const pKa = {D:3.9,E:4.1,H:6.0,C:8.3,Y:10.1,K:10.5,R:12.5}; let ph = 7; for(let iter = 0; iter < 200; iter++) { let charge = 0.1 / (1 + Math.pow(10, ph - 3.1)); // N-term charge -= 0.1 / (1 + Math.pow(10, 3.6 - ph)); // C-term (approx) [...seq].forEach(aa => { if(aa==='D') charge -= 1/(1+Math.pow(10,pKa.D-ph)); if(aa==='E') charge -= 1/(1+Math.pow(10,pKa.E-ph)); if(aa==='H') charge += 1/(1+Math.pow(10,ph-pKa.H)); if(aa==='C') charge -= 1/(1+Math.pow(10,pKa.C-ph)); if(aa==='Y') charge -= 1/(1+Math.pow(10,pKa.Y-ph)); if(aa==='K') charge += 1/(1+Math.pow(10,ph-pKa.K)); if(aa==='R') charge += 1/(1+Math.pow(10,ph-pKa.R)); }); if(Math.abs(charge) < 0.001) break; ph += charge > 0 ? 0.1 : -0.1; } return Math.max(1, Math.min(14, ph)); } function extractSeq() { if(!S.proteinPDB){ toast('Load a protein first','warning'); return; } const m={ALA:'A',ARG:'R',ASN:'N',ASP:'D',CYS:'C',GLN:'Q',GLU:'E',GLY:'G',HIS:'H',ILE:'I',LEU:'L',LYS:'K',MET:'M',PHE:'F',PRO:'P',SER:'S',THR:'T',TRP:'W',TYR:'Y',VAL:'V'}; const lines = S.proteinPDB.split('\n').filter(l => l.startsWith('ATOM') && l.substring(13,15).trim() === 'CA'); let seq = '', last = -1; lines.forEach(l => { const rn=parseInt(l.substring(22,26)); if(rn!==last){ seq+=m[l.substring(17,20).trim()]||'X'; last=rn; }}); document.getElementById('seq-input').value = '>' + (S.proteinId||'protein') + '\n' + seq; updateSeqInfo(); toast('Extracted ' + seq.length + ' residues', 'success'); } function usePredAsProtein() { if(!predPDB){ toast('No predicted structure to use','warning'); return; } initProteinViewer(predPDB, 'Predicted', 'ESMFold/AlphaFold'); toast('Predicted structure loaded as protein for docking', 'success'); } function downloadPredPDB() { if(!predPDB){ toast('No structure to download','warning'); return; } const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([predPDB], {type:'text/plain'})); a.download = 'predicted_structure.pdb'; a.click(); } // ═══════════════════════ AI / RAG ═══════════════════════ let ragDocs=[]; async function testAPI(){ const key=document.getElementById('api-key').value.trim(); if(!key){toast('Enter API key','warning');return;} S.apiKey=key; S.apiModel=document.getElementById('api-model').value; const status=document.getElementById('api-status'); status.className='alert alert-info';status.innerHTML='<span class="spin"></span>Testing…'; try{ const r=await fetch('https://api.groq.com/openai/v1/chat/completions',{method:'POST',headers:{'Content-Type':'application/json','Authorization':'Bearer '+key},body:JSON.stringify({model:S.apiModel,messages:[{role:'user',content:'OK'}],max_tokens:3})}); if(!r.ok) throw new Error('Invalid key'); status.className='alert alert-success';status.innerHTML='βœ“ Connected'; updateBadges();toast('API key valid','success'); }catch(e){status.className='alert alert-error';status.innerHTML='βœ— '+e.message;} } function loadExampleRAG(){ ragDocs=[ {name:'drug_info.txt',content:'Aspirin (MW 180.16) is an NSAID inhibiting COX-1/COX-2. LogP 1.19. Caffeine (MW 194.19) is a CNS stimulant. Ibuprofen (MW 206.28) is an NSAID.'}, {name:'docking_guide.txt',content:'AutoDock Vina scoring: below -7 kcal/mol is strong binding. H-bonds: 2.5–3.5 Γ…. Hydrophobic contacts: 3.5–4.5 Γ…. Ki=exp(Ξ”G/RT).'}, {name:'structures.txt',content:'PDB 6LU7 is SARS-CoV-2 Mpro. PDB 1HHO is hemoglobin. AlphaFold predicts structures from sequence with pLDDT confidence scores.'} ]; document.getElementById('rag-docs').innerHTML='<div class="alert alert-success">βœ“ 3 documents loaded</div>'; } function getCtx(query){ let ctx=''; if(S.proteinId) ctx+=`Protein: ${S.proteinId} (${S.proteinSrc})\n`; if(S.ligandCID) ctx+=`Ligand CID: ${S.ligandCID}; MW: ${S.ligandProps?.MolecularWeight}; LogP: ${S.ligandProps?.XLogP}\n`; if(S.dockingResult) ctx+=`Docking best affinity: ${S.dockingResult.affinity} kcal/mol; Ki: ${S.dockingResult.ki}\n`; const words=query.toLowerCase().split(/\s+/); let best=null,score=0; ragDocs.forEach(d=>{let s=0;words.forEach(w=>{if(d.content.toLowerCase().includes(w))s++;});if(s>score){score=s;best=d;}}); if(best) ctx+='\nRelevant: '+best.content; return ctx; } async function queryRAG(){ const q=document.getElementById('rag-query').value.trim(); if(!q) return; if(!S.apiKey){toast('Set API key','warning');return;} document.getElementById('rag-response').innerHTML='<div class="alert alert-info"><span class="spin"></span>Thinking…</div>'; try{ const r=await fetch('https://api.groq.com/openai/v1/chat/completions',{method:'POST',headers:{'Content-Type':'application/json','Authorization':'Bearer '+S.apiKey},body:JSON.stringify({model:S.apiModel,messages:[{role:'system',content:'You are Docking AI, structural biology expert.\n'+getCtx(q)},{role:'user',content:q}],max_tokens:300,temperature:.3})}); if(!r.ok) throw new Error('API error'); const d=await r.json(); document.getElementById('rag-response').innerHTML=`<div class="msg assistant">${d.choices[0].message.content.replace(/\n/g,'<br>')}</div>`; }catch(e){document.getElementById('rag-response').innerHTML=`<div class="alert alert-error">βœ— ${e.message}</div>`;} } async function sendChat(){ const inp=document.getElementById('chat-input'); const msg=inp.value.trim(); if(!msg) return; if(!S.apiKey){toast('Set API key','warning');return;} const win=document.getElementById('chat-win'); const um=document.createElement('div');um.className='msg user';um.textContent=msg;win.appendChild(um); inp.value=''; const th=document.createElement('div');th.className='msg assistant';th.innerHTML='<span class="spin"></span>';win.appendChild(th);win.scrollTop=9999; try{ const r=await fetch('https://api.groq.com/openai/v1/chat/completions',{method:'POST',headers:{'Content-Type':'application/json','Authorization':'Bearer '+S.apiKey},body:JSON.stringify({model:S.apiModel,messages:[{role:'system',content:'You are Docking AI.\n'+getCtx(msg)},...S.chatHistory.slice(-6),{role:'user',content:msg}],max_tokens:500,temperature:.5})}); if(!r.ok) throw new Error('API error'); const d=await r.json(); const ans=d.choices[0].message.content; th.innerHTML=ans.replace(/\n/g,'<br>'); S.chatHistory.push({role:'user',content:msg},{role:'assistant',content:ans}); }catch(e){th.innerHTML='Error: '+e.message;} win.scrollTop=9999; } function qp(p){document.getElementById('chat-input').value=p;sendChat();} // ═══════════════════════ DOWNLOADS ═══════════════════════ function downloadPDB(){ if(!S.proteinPDB) return; const a=document.createElement('a');a.href=URL.createObjectURL(new Blob([S.proteinPDB],{type:'text/plain'}));a.download=(S.proteinId||'protein')+'.pdb';a.click(); } function downloadSDF(){ if(!S.ligandSDF) return; const a=document.createElement('a');a.href=URL.createObjectURL(new Blob([S.ligandSDF],{type:'chemical/x-mdl-sdfile'}));a.download='molecule_'+(S.ligandCID||'ligand')+'.sdf';a.click(); } function copyEmail(){navigator.clipboard.writeText('ashmithamganesan@gmail.com');toast('Email copied!','success');} // ═══════════════════════ INIT ═══════════════════════ window.addEventListener('load',()=>{ // Pre-init all viewers ['protein','ligand','complex','pred'].forEach(k=>getViewer(k)); // Wire sequence live counter const seqTA = document.getElementById('seq-input'); if(seqTA) seqTA.addEventListener('input', updateSeqInfo); // Load aspirin as default ligand setTimeout(()=>loadCID('2244'),1200); }); </script> </body> </html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Docking Pro - Complete Structural Biology Platform</title>
<link href="https://fonts.googleapis.com/css2?family=Space+Mono:ital,wght@0,400;0,700;1,400&family=Syne:wght@400;600;700;800&display=swap" rel="stylesheet">
<script src="https://3dmol.csb.pitt.edu/build/3Dmol-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js"></script>
<style>
*{margin:0;padding:0;box-sizing:border-box}
:root{
--bg:#07090f;
--bg2:#0d101a;
--bg3:#141826;
--bg4:#1c2235;
--cyan:#00f0ff;
--purple:#c084fc;
--green:#34d399;
--yellow:#fbbf24;
--red:#f87171;
--orange:#fb923c;
--text:#e8edf8;
--text2:#8892b0;
--text3:#4a5568;
--border:#1e2a40;
--border2:#2a3a55;
}
body{
font-family:'Syne',sans-serif;
background:var(--bg);
color:var(--text);
min-height:100vh;
background-image:
radial-gradient(ellipse 60% 50% at 20% 10%, rgba(0,240,255,0.04) 0%, transparent 60%),
radial-gradient(ellipse 50% 40% at 80% 90%, rgba(192,132,252,0.04) 0%, transparent 60%);
}
#app{max-width:1600px;margin:0 auto;padding:20px}
/* HEADER */
.header{
display:flex;align-items:center;gap:20px;
padding:18px 28px;
background:linear-gradient(135deg,rgba(13,16,26,0.9),rgba(20,24,38,0.9));
border:1px solid var(--border2);
border-radius:20px;
margin-bottom:24px;
backdrop-filter:blur(20px);
position:relative;overflow:hidden;
}
.header::before{
content:'';position:absolute;top:0;left:0;right:0;height:1px;
background:linear-gradient(90deg,transparent,var(--cyan),var(--purple),transparent);
}
.logo{
font-size:22px;font-weight:800;letter-spacing:-0.5px;
background:linear-gradient(135deg,var(--cyan),var(--purple));
-webkit-background-clip:text;-webkit-text-fill-color:transparent;
}
.logo-sub{color:var(--text3);font-size:11px;font-family:'Space Mono',monospace;margin-top:2px;letter-spacing:1px}
.badges{margin-left:auto;display:flex;gap:10px;flex-wrap:wrap}
.badge{
padding:5px 14px;border-radius:100px;font-size:11px;font-weight:700;
font-family:'Space Mono',monospace;
background:var(--bg3);border:1px solid var(--border);color:var(--text2);
letter-spacing:0.5px;transition:all .2s;
}
.badge.lit{background:rgba(0,240,255,0.08);border-color:rgba(0,240,255,0.3);color:var(--cyan)}
/* TABS */
.tabs{
display:flex;gap:6px;padding:6px;
background:var(--bg2);border:1px solid var(--border);border-radius:16px;
margin-bottom:24px;
}
.tab{
flex:1;padding:10px 16px;background:transparent;border:none;
color:var(--text3);font-weight:700;font-size:13px;
font-family:'Syne',sans-serif;border-radius:10px;cursor:pointer;
transition:all .25s;letter-spacing:0.3px;
}
.tab:hover{color:var(--text2);background:var(--bg3)}
.tab.active{
background:linear-gradient(135deg,rgba(0,240,255,0.12),rgba(192,132,252,0.12));
color:var(--cyan);border:1px solid rgba(0,240,255,0.25);
}
/* PANELS */
.panel{display:none}
.panel.active{display:block}
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:20px}
@media(max-width:1100px){.grid2{grid-template-columns:1fr}}
/* CARD */
.card{
background:var(--bg2);border:1px solid var(--border);