Skip to content

feat(vector): draw MOL chemical structures (.mol V2000) as PNG and SVG - #2100

Open
YusufMntm wants to merge 2 commits into
KnifeLemon:mainfrom
YusufMntm:feat/mol-structures-954
Open

YusufMntm wants to merge 2 commits into
KnifeLemon:mainfrom
YusufMntm:feat/mol-structures-954

Conversation

@YusufMntm

Copy link
Copy Markdown
Contributor

Refs #954

What and why

As agreed in the issue: KingDraw's own .kdx isn't documented, but KingDraw exports MOL, so this becomes MOL → PNG. This PR reads MOL V2000 and draws the structure. Refs rather than Fixes, since the issue title is .kdx and .kdx itself stays unread; change it if you'd rather close the issue with this.

Design

  • Vector/Chemistry/MolFile.cs, written from the published CTfile V2000 description: header, counts line, atom block (coordinates, element, mass difference, charge code, explicit valence), bond block (types 1–4, query types read but drawn as single, stereo 1/4/6), properties M CHG, M ISO, M RAD (which supersede the atom-block columns, as the format says), up to M END. V3000 is refused as an unsupported variant (error.mol_v3000_unsupported); other text as "not a MOL file". .sdf isn't registered (the extension also means SQL Server Compact and EDA files), though a single SDF record parses.
  • Vector/Chemistry/MolDepiction.cs draws on an SKCanvas, so PNG (SKBitmap) and SVG (SKSvgCanvas) share one routine. The file's 2D coordinates (z ignored), scaled so the median bond is 60 px, 48 px padding, 128–4096 px per side, white background, antialiased:
    • single; double (in a 3–8 ring: second line inset toward the ring centre and shortened; otherwise a centred pair); triple; aromatic (type 4): solid bond + dashed inner line toward the ring centre, which needs no Kekulé guess; wedge (filled), hash (bars), either (wavy).
    • labels for heteroatoms and for carbons that are charged, isotopic or isolated, with implicit H from standard valences (OH, NH₂, NH₃⁺), isotopes as leading superscript, charges as trailing superscript; bond lines are clipped at the label boxes.
    • fonts through the existing CadFonts resolver (headless-safe on all CI OSes).
  • Converter: mol → png and mol → svg added to the built-in VectorConverter (no new engine id); PDF and other pictures follow through the planner. Output goes to a temp file beside the target and is moved into place.
  • Registration: mol in FormatRegistry (Vector, read-only), FormatFields Specialist with an Overlaps row to the off-by-default science field (FORMAT-RULES rule 5), pinned lists/counts in FormatFieldsTests, SharedPresetVersions, schema 121 with a LearnExtensions step. 120 is taken by my open feat(email): open Outlook mailbox files (.pst) as one EML per message #2098 (.pst): if this merges first, it can become 120 (AppSettings, UserDataStore, MolFormatTests).
  • Caps: 16 MB file, 4096-byte lines, 100 000 lines, 10 000 atoms, 10 000 bonds, bounded ring search (size ≤ 8, 256 visits per bond), image ≤ 4096 px per side. Every refusal has its own error.mol_* key in all i18n files.
  • Docs: README.md row, docs/ENGINES.md.

Tests

  • MolTests (19): benzene as KingDraw exports it; ethanol (OH); charged N⁺ via M CHG; isotope; wedge/hash/wavy; triple; aromatic ring; PNG and SVG output; pixel checks (bond midpoints dark, ring centre light, label areas inked); V3000, garbage, out-of-range bond index, too many atoms, empty → refused with the right keys; existing output kept on failure.
  • MolFormatTests: detection, grade/field, schema 121 migration.
  • Locally: MolTests 19/19, Core MolFormatTests|FormatFieldsTests|DefaultOutputTests 80/80, localization tests pass, dotnet format --verify-no-changes on the changed files.
  • By hand with filee-cli convert … --to png: a benzene V2000 file and a substituted aromatic ring (OH, NH₃⁺, wedge methyl) both rendered as expected. I didn't download the reporter's gist file; the benzene test mirrors its V2000 layout.

Proposed CHANGELOG lines (CHANGELOG untouched per your policy)

- **MOL chemical structures (`.mol`)** (#954). MOL V2000 files, such as KingDraw exports, convert to PNG and SVG (and
  from there to PDF and other pictures): single, double, triple, aromatic and stereo bonds, atom labels with implicit
  hydrogens, charges and isotopes.
ko: 화학 구조 파일(MOL V2000, .mol)을 PNG와 SVG로 바로 변환할 수 있어요
en: Chemical structure files (MOL V2000, .mol) convert straight to PNG and SVG

🤖 Generated with Claude Code

Reads MOL V2000 connection tables (atoms, bonds, M CHG/ISO/RAD) and
draws the 2D structure with SkiaSharp: single, double (inset in rings),
triple, aromatic, wedge, hash and wavy bonds, heteroatom labels with
implicit hydrogens, charges and isotopes. V3000 and non-MOL text are
refused with their own reasons; sizes and counts are capped. Schema 121
learns .mol (120 is taken by the open .pst PR).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@YusufMntm
YusufMntm requested a review from KnifeLemon as a code owner December 6, 2026 00:29
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@KnifeLemon KnifeLemon left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. Going from MOL instead of .kdx is the right call, and the code is in good shape. The V2000 columns are right: the counts line, the atom block (with valence 15 meaning zero), the charge codes and the bond block. Every read is length-checked, indices are validated (including a1 == a2), and the caps apply before anything is allocated. The output is written to a temp file first, so a failure leaves an existing file alone. The tests build their inputs inline, and the four new strings are translated everywhere. I have one must-fix and a few smaller points.

Must fix: huge coordinates make the whole picture NaN. ParseAtomLine (MolFile.cs:473) only refuses NaN and Infinity. A field like 1.0E+308 fits in 10 characters, and the whitespace fallback takes any length. In BuildLayout (MolDepiction.cs:171-203), X * scale then overflows to +Inf, so shrink becomes 0 and centerX * shrink becomes NaN. As a result, every position is NaN. Two atoms at 0.0 and 1.0E+308 give a blank 128 × 128 PNG, and the job still reports Completed. Please refuse |x|, |y| or |z| above 1e5 as error.mol_not_mol: F10.4 can't go past ±99999.9999. Also guard scale, shrink and the offsets with double.IsFinite, and add a test for each.

Smaller:

  • M RAD (MolFile.cs:265-272): the format says M CHG and M RAD each replace both the charge and the radical from the atom block. Right now a file with M RAD and no M CHG keeps the atom-block charges. Please let the first of the two lines clear both.
  • Ring search (MolDepiction.cs:624-660): the 256 cap counts atoms reached, not edges scanned. Duplicate bonds are accepted, so 10,000 copies of 1 2 2 cost about 2 × 10⁸ lookups. Please count scanned edges toward the cap, or refuse a second bond between the same two atoms.
  • Query bond types 6 and 7 map to Aromatic (MolFile.cs:537-538) and add 1.5 to the implicit-H count. The PR body says query types are drawn as single. Either is fine; please make the code and the body agree.
  • Tests: Existing_output_survives_a_failed_conversion fails at V3000 parsing, before anything is written, so it never reaches the temp-then-move path. A failure after layout would cover it. Coverage for M RAD, the bond cap and degenerate geometry (all atoms at one point) would be welcome too.

Schema and version: you don't need to change anything here. #2098 still has open changes, so whichever PR merges first takes 120, and I'll renumber the other one at merge time. I'll also move ["mol"] in SharedPresetVersions to the next version: 2.6.0 is about to ship, so this goes into the release after it.

A pyrrole-type [nH] losing its H and the cis/trans "either" double bond are fine to leave for later.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants