🆕 Convert HELM to SMILES
Problem
You want to convert a HELM string to a SMILES string.
See also
[Zhang-2012] publication
Ingredients
|
Difficulty Level
🌶️
Download
Source Code
helm2smiles
#!/usr/bin/env python3
# (C) 2026 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
"""Convert HELM string to SMILES."""
import argparse
import json
import os
import pathlib
import sys
import rich.console
from openeye import oechem
from rich_argparse import HelpPreviewAction, RichHelpFormatter
__SCRIPT_NAME__ = pathlib.Path(__file__).absolute().stem
__SCRIPT_DESC__ = "Convert HELM string to SMILES."
__SCRIPT_TOOLKITS__ = ["oechem"]
__SCRIPT_KEYWORDS__ = ["HELM", "SMILES", "peptide", "peptide-informatics"]
__SCRIPT_CATEGORIES__ = ["peptide-informatics"]
def parse_options() -> argparse.Namespace:
"""Set up command line options."""
parser = argparse.ArgumentParser(
add_help=True,
formatter_class=RichHelpFormatter,
description="[yellow]" + __SCRIPT_DESC__ + "[/yellow]",
)
input_group = parser.add_argument_group("Input options")
input_group.add_argument(
"--helm",
metavar="HELM-STRING",
type=str,
required=True,
help="input HELM string",
)
monomers_group = parser.add_argument_group("Monomer set options")
_add_monomer_collection(monomers_group)
parser.add_argument("--help-image", action=HelpPreviewAction)
parser.add_argument(
"--save-console-svg",
default=False,
action="store_true",
help=f"run command and capture console output in {__SCRIPT_NAME__}.svg file",
)
return parser.parse_args()
def main() -> int:
"""Convert HELM string to SMILES."""
args = parse_options()
monomers = _get_monomer_collection(args)
console = rich.console.Console(record=args.save_console_svg)
mol = oechem.OEGraphMol()
result = oechem.OEHelmParsingResult()
if oechem.OEHelmToMol(mol, args.helm, monomers, result):
# successful parsing
console.print(oechem.OEMolToSmiles(mol), markup=False, highlight=False)
else:
# failed parsing
console.print(f"[red]Warning: {result.GetWarning()}[/red]")
console.print(args.helm, markup=False, highlight=False)
console.print("[red]" + "-" * result.GetErrorPosition() + "^[/red]")
if args.save_console_svg:
console.save_svg(f"{__SCRIPT_NAME__}.svg", title="output")
return os.EX_OK
class MonomerSetParameter: # noqa: PLW1641
"""Utility class to handle both built-in and user defined monomer sets."""
def __init__(self) -> None: # noqa: D107
self._monomer_sets = ["Standard", "OpenEye", "JSON-FILENAME"]
def __repr__(self) -> str: # noqa: D105
return ",".join(self._monomer_sets)
def __eq__(self, param: object) -> bool: # noqa: D105
if not isinstance(param, str):
return False
if param in ["Standard", "OpenEye"]:
return True
console = rich.console.Console()
monomer_set_filepath = pathlib.Path(param)
if (
not monomer_set_filepath.exists()
or monomer_set_filepath.suffix.lower() != ".json"
):
console.print(f"[red]Invalid monomer set file '{param}' ![/red]")
return False
try:
with monomer_set_filepath.open("r") as json_file:
json.load(json_file)
except json.JSONDecodeError as e:
console.print(f"[red]Invalid monomer set file '{param}' ![/red]")
console.print(f"[red]Error decoding JSON: {e} ![/red]")
return False
return True
def _add_monomer_collection(arg_group: argparse._ArgumentGroup) -> None:
arg_group.add_argument(
"-m",
"--monomers",
type=str,
default="Standard",
choices=[MonomerSetParameter()],
help="built-in monomer-set type or json file of monomers",
)
def _get_monomer_collection(args: argparse.Namespace) -> oechem.OEMonomerSet:
monomers = oechem.OEMonomerSet()
match args.monomers:
case "Standard":
oechem.OELoadStandardMonomerSet(monomers)
case "OpenEye":
oechem.OELoadOpenEyeMonomerSet(monomers)
case _:
oechem.OEReadMonomerSet(monomers, args.monomers)
return monomers
setattr(main, "__SCRIPT_NAME__", __SCRIPT_NAME__)
setattr(main, "__SCRIPT_DESC__", __SCRIPT_DESC__)
setattr(main, "__SCRIPT_TOOLKITS__", __SCRIPT_TOOLKITS__)
setattr(main, "__SCRIPT_KEYWORDS__", __SCRIPT_KEYWORDS__)
setattr(main, "__SCRIPT_CATEGORIES__", __SCRIPT_CATEGORIES__)
if __name__ == "__main__":
sys.exit(main())
Solution
The OEHelmToMol function can take a HELM string and a monomer set (OEMonomerSet) and convert it into a molecule representation.
mol = oechem.OEGraphMol()
result = oechem.OEHelmParsingResult()
if oechem.OEHelmToMol(mol, args.helm, monomers, result):
# successful parsing
console.print(oechem.OEMolToSmiles(mol), markup=False, highlight=False)
else:
# failed parsing
console.print(f"[red]Warning: {result.GetWarning()}[/red]")
console.print(args.helm, markup=False, highlight=False)
console.print("[red]" + "-" * result.GetErrorPosition() + "^[/red]")
Usage
See Download section to download the script.
> helm2smiles --help
By default, the helm2smiles script uses OEChem TK’s
built-in Standard monomer set for the conversion.
> helm2smiles --helm 'PEPTIDE1{P.E.P.T.I.D.E}$$$$'
If the conversion fails, the helm2smiles will print a warning message and show the position where the parsing error occurred in the HELM string.
> helm2smiles --helm 'PEPTIDE1{P.E.P.T.I.D.X}$$$$'
Monomer Set Options
- --monomers OpenEye
OEChem TK’s built-in OpenEye monomer set can be used with the --monomers OpenEye
parameter.
The OEHelmToMol function can also parse a HELM string with an embedded SMILES string that specifies
unnamed fragments of the peptide.
> helm2smiles --helm 'PEPTIDE1{[N1[C@@H](CCC1=O)C([R2])=O].P.S.K.D.A.F.I.G.L.M.[am]}$$$$' --monomers OpenEye
- --monomers JSON-MONOMER-FILE
The following example shows how to parse a HELM string with a custom monomer set
defined in a json file
(custom-monomers.json)
> helm2smiles --helm 'PEPTIDE1{[Cys].[Pro].[Phe(4-F)].[Ala].[Cys]}$PEPTIDE1,PEPTIDE1,1:R3-5:R3$$$' --monomers custom-monomers.json
See also in OEChem TK manual
API
OEHelmToMol function
OEHelmParsingResult class
OEHelmParsingReturnCode namespace
OEMonomerSet class