---
name: chem-vis
description: Generate 2D structure images and interactive 3D viewers from chemical names or SMILES. Supports PNG/SVG output for 2D and 3Dmol.js HTML viewers for 3D conformers.
license: MIT
---

# Chemical Visualization Skill

## Overview

Generate publication-quality 2D molecular structure images and interactive 3D conformer viewers from chemical names, SMILES, or InChI strings.

Needs network access to `*.nih.gov` servers to access PubChem for common names like caffeine, testosterone, estrogen, etc.

Much of the code was generated by Claude, with careful validation, error fixing, and OPSIN integration by Geoff Hutchison.

## Quick Start

```bash
# 2D structure image
python scripts/chem_2d.py "caffeine" --output caffeine.png

# 3D interactive viewer
python scripts/chem_3d.py "caffeine" --output caffeine.html

# Both at once
python scripts/chem_vis.py "caffeine" --both --output-dir ./caffeine/
```

## Dependencies

```bash
pip install rdkit pubchempy py2opsin --break-system-packages
```

## Scripts

| Script | Purpose |
|--------|---------|
| `chem_2d.py` | Generate 2D structure images (PNG/SVG) |
| `chem_3d.py` | Generate 3D conformer viewers (HTML) |
| `chem_vis.py` | Unified CLI for both |
| `common.py` | Shared utilities (name resolution, etc.) |

---

## 2D Structure Images

Generate static images of molecular structures.

### Usage

```bash
python scripts/chem_2d.py "aspirin" --output aspirin.png
python scripts/chem_2d.py "CCO" --input-type smiles --output ethanol.svg --format svg
python scripts/chem_2d.py "glucose" --width 400 --height 400 --output glucose.png
```

### Options

| Option | Description | Default |
|--------|-------------|---------|
| `--input-type`, `-t` | Input: `name`, `smiles`, `inchi` | `name` |
| `--output`, `-o` | Output file path | `molecule.png` |
| `--format`, `-f` | Output: `png`, `svg` | `png` |
| `--width`, `-W` | Width in pixels | 300 |
| `--height`, `-H` | Height in pixels | 300 |
| `--kekulize`, `-k` | Show Kekulé structure | False |
| `--show-atom-numbers`, `-n` | Display atom indices | False |
| `--highlight-atoms` | Atom indices to highlight | None |

### Python API

```python
from scripts.chem_2d import chemical_to_image, batch_convert

# Single molecule
chemical_to_image("caffeine", "caffeine.png", width=400, height=400)

# Batch conversion
chemicals = ["aspirin", "ibuprofen", "acetaminophen"]
results = batch_convert(chemicals, output_dir="./structures/", format="svg")
```

---

## 3D Conformer Viewers

Generate interactive HTML viewers with 3Dmol.js.

### Usage

```bash
python scripts/chem_3d.py "dopamine" --output dopamine.html
python scripts/chem_3d.py "CCO" --input-type smiles --style ballstick --output ethanol.html
python scripts/chem_3d.py "serotonin" --embed --output serotonin_widget.html
```

### Options

| Option | Description | Default |
|--------|-------------|---------|
| `--input-type`, `-t` | Input: `name`, `smiles` | `name` |
| `--output`, `-o` | Output file path | `molecule_3d.html` |
| `--width`, `-W` | Viewer width (px) | 500 |
| `--height`, `-H` | Viewer height (px) | 400 |
| `--style`, `-s` | Style: `stick`, `sphere`, `line`, `ballstick` | `stick` |
| `--conformers`, `-c` | Conformers to sample | 10 |
| `--no-optimize` | Skip MMFF optimization | False |
| `--no-controls` | Hide interactive buttons | False |
| `--embed` | Output snippet without HTML wrapper | False |

### Embed Mode

Use `--embed` to generate a snippet for inserting into existing web pages:

```bash
python scripts/chem_3d.py "aspirin" --embed --output aspirin_widget.html
```

The parent page must load 3Dmol.js:
```html
<script src="https://3dmol.org/build/3Dmol-min.js"></script>
```

Each viewer gets a unique ID, so multiple molecules can coexist on one page.

### Python API

```python
from scripts.chem_3d import chemical_to_3d, generate_conformer, generate_html_viewer

# Full pipeline
chemical_to_3d("caffeine", "caffeine.html")

# Step by step
from scripts.common import get_smiles
smiles = get_smiles("caffeine", "name")
mol_block = generate_conformer(smiles, num_conformers=20)
html = generate_html_viewer(mol_block, title="Caffeine", width=600, height=500)

# Embeddable snippet
snippet = generate_html_viewer(mol_block, title="Caffeine", embed=True)
```

---

## Unified CLI

Generate both 2D and 3D outputs with one command.

```bash
# 2D only
python scripts/chem_vis.py "caffeine" --2d --output caffeine.png

# 3D only
python scripts/chem_vis.py "caffeine" --3d --output caffeine.html

# Both
python scripts/chem_vis.py "caffeine" --both --output-dir ./caffeine/
```

---

## Examples

### Generate structures for a lecture

```python
from scripts.chem_2d import batch_convert

neurotransmitters = ["dopamine", "serotonin", "acetylcholine", "GABA", "glutamate"]
batch_convert(neurotransmitters, output_dir="./lecture_slides/", width=400, height=400)
```

### Comparison page with multiple 3D viewers

```python
from scripts.chem_3d import generate_conformer, generate_html_viewer
from scripts.common import get_smiles

molecules = ["aspirin", "ibuprofen", "naproxen"]

page = '''<!DOCTYPE html>
<html>
<head>
    <script src="https://3dmol.org/build/3Dmol-min.js"></script>
    <style>
        .container { display: flex; gap: 20px; flex-wrap: wrap; padding: 20px; }
    </style>
</head>
<body>
<h1>NSAID Comparison</h1>
<div class="container">
'''

for mol_name in molecules:
    smiles = get_smiles(mol_name, "name")
    mol_block = generate_conformer(smiles)
    page += generate_html_viewer(mol_block, title=mol_name.title(), 
                                  width=350, height=300, embed=True)

page += '</div></body></html>'

with open("nsaid_comparison.html", "w") as f:
    f.write(page)
```

---

## Troubleshooting

### "Could not find chemical"
- Check if network access is enabled to `*.nih.gov` sites for PubChem use.
- Check spelling
- Try alternative names (IUPAC vs common)
- Use SMILES directly: `--input-type smiles`

### "Could not generate 3D conformer"
- Try `--no-optimize` flag
- Increase `--conformers` count
- Some structures (metals, unusual bonding) may not embed well

### Poor 2D layout
- RDKit's 2D coordinate generation works best for typical organic molecules
- Very large or unusual structures may need manual adjustment

### 3D viewer doesn't load
- Check internet connection (3Dmol.js loads from CDN)
- Check browser console for errors
- For embed mode, ensure parent page loads 3Dmol.js first
