Kekule.js Cheminformatics Toolkit

repository·master·Indexed 43 days ago

https://github.com/partridgejiang/kekule.js

An open-source JavaScript toolkit for cheminformatics (version 1.0.5) that enables web and Node.js applications to read, write, display, and edit chemical structures. It provides capabilities for aromaticity detection, sub-structure searching, and data I/O via the Kekule.IO module. The toolkit includes visualization and editing widgets (Kekule.ChemWidget.Viewer and Kekule.Editor.Composer) and offers integration options for Vue, React, Moodle, and CKEditor 4.

Tokens
25.3K
Snippets
79
Records
95
Agent score
55%

What's inside Kekule.js

  1. Overview of Kekule.js Common and Chem Widgets

    master

    Kekule.js widgets are categorized into two main groups:

    Common Widgets

    General-purpose UI components not directly related to chemoinformatics. Examples include:

    • Kekule.Widget.Button: A standard button widget.
    • Kekule.Widget.ButtonGroup: A toolbar used to group buttons together.
    • Other types include drop boxes, text editors, tab groups, menus, and dialogs.

    Chem Widgets

    Specialized widgets designed for chemoinformatics tasks:

    • Kekule.ChemWidget.PeriodicTable: An interactive periodic table that allows users to select one or more elements.
    • Kekule.ChemWidget.Viewer: A widget for displaying molecules and other chemical objects in 2D or 3D, supporting interactions like zooming and rotation.
    • Kekule.Editor.Composer: A powerful 2D chemical structure editor that handles molecule structures, text blocks, and reaction symbols.
  2. Overview of the Moono skin for CKEditor 4.x

    master

    Moono is a monochromatic skin designed for CKEditor 4.x. It provides a modern aesthetic using gradients and transparency. Key features include:

    • Chameleon feature: Supports brightness adjustments.
    • High-contrast compatibility: Designed to work well in high-contrast modes.
    • SVG Graphics: Uses SVG for icon sources to ensure scalability.

    This skin is maintained by the core CKEditor developers and was selected as the default skin for CKEditor 4.x.

  3. Overview of Kekule.js major modules

    master

    Kekule.js is organized into several functional modules:

    • Core: Representation of chemical concepts (elements, atoms, bonds, molecules, reactions).
    • IO: Reading/writing chemical data (Kekule JSON/XML, CML, MDL MOL2000/3000, JCAMP-DX/CS, SMILES).
    • Render: Low-level cross-browser rendering for chemical objects.
    • Spectroscopy: Representation and rendering of molecule spectra.
    • Widget: General UI components (buttons, text boxes, dialogs, etc.).
    • Chem Widget: Chemistry-specific UI (Periodical table, 2D/3D viewers, 2D diagram editors).
    • Algorithm: Chemical graph theory algorithms (Ring perception, aromaticity, molecule comparison, sub-structure search, stereo identification).
  4. Use the Chem Viewer Widget to display molecules

    master

    The Kekule.ChemWidget.Viewer is a core widget used to display molecules and other chemistry objects in 2D or 3D. It supports direct user interaction via mouse or touch and can be customized with a toolbar.

    Key properties for customization include:

    • chemObj: The chemistry object to display.
    • renderType: Set to Kekule.Render.rendererType.R2D for 2D or Kekule.Render.rendererType.R3D for 3D.
    • moleculeDisplayType: Controls the visual model (e.g., SKELETAL, WIRE, SPACE_FILL).
    • enableToolbar: Boolean to show/hide the functional toolbar.
    • backgroundColor: CSS color format (e.g., '#ffffff').
    • enableDirectInteraction: Enables zooming, rotating, or moving objects via mouse/touch.
    var chemViewer = new Kekule.ChemWidget.Viewer(document);
    chemViewer.setDimension('500px', '400px');
    chemViewer.appendToElem(document.getElementById('parent')).setChemObj(molecule);
  5. How to interact with wrapped Web Component widgets

    master

    When using a wrapped Kekule widget as a Web Component, you can interact with it in two ways:

    1. Direct Property Access: By default, most widget properties are mapped to the custom element. You can get or set these properties directly on the HTML element.
    2. Via the .widget property: For calling methods or attaching event listeners (which are not mapped by default), access the underlying instance through the .widget property.

    Example of direct property mapping: myButton.text = 'Value' is equivalent to myButton.widget.text = 'Value'.

    // Direct property setting (mapped)
    myButton.text = 'Web Component Button';
    
    // Method/Event access (requires .widget)
    myButton.widget.on('click', function(e){ console.log('click'); });
  6. Use Pseudoatoms, VariableAtoms, and SubGroups

    master

    Kekule.js supports specialized node types beyond standard atoms:

    • Pseudoatom: Use Kekule.Pseudoatom and set the type via setAtomType(Kekule.PseudoatomType.ANY).
    • VariableAtom: Use Kekule.VariableAtom and define allowed isotopes using setAllowedIsotopeIds(['F', 'Cl', ...]).
    • SubGroup: Use Kekule.SubGroup to create a structural fragment. You can define an anchor node using appendAnchorNode(node) to connect the subgroup to the main molecule body, and set an abbreviation using setAbbr('Et').
    // Example of adding different node types
    var mol = new Kekule.Molecule();
    
    // Pseudo atom
    var pseudo = new Kekule.Pseudoatom().setAtomType(Kekule.PseudoatomType.ANY).setCoord2D({x: 0, y: -0.80});
    mol.appendNode(pseudo);
    
    // Variable atom
    var variable = new Kekule.VariableAtom().setAllowedIsotopeIds(['F', 'Cl', 'Br']).setCoord2D({x: 1.39, y: 0.80});
    mol.appendNode(variable);
    
    // Subgroup
    var sub = new Kekule.SubGroup();
    sub.appendNode(new Kekule.Atom().setSymbol('C').setCoord2D({x: 1.39, y: 0.80}));
    sub.appendNode(new Kekule.Atom().setSymbol('C').setCoord2D({x: 2.0, y: 0.40}));
    sub.appendBond([0, 1], 1);
    sub.appendAnchorNode(sub.getNodeAt(0));
    sub.setAbbr('Et');
    mol.appendNode(sub);
  7. Handle molecule correlation and peak assignments

    master

    Spectra are often linked to specific molecule structures.

    1. Molecule Correlation: The refMolecules property of Kekule.Spectroscopy.Spectrum stores the related molecules.
    2. Peak Assignments: Peak assignments (mapping peaks to specific atoms or bonds) are stored within Kekule.Spectroscopy.DataSection. You can access this via getExtraInfoOf(value) or getExtraInfoAt(index), which returns a Kekule.Spectroscopy.SpectrumDataDetails object containing the assignment.
    // Check if a spectrum is correlated to a molecule
    var molecule = chemObjList.getChildAt(0);
    var spectrum = chemObjList.getChildAt(1);
    console.log(spectrum.getRefMolecules()[0] === molecule); // true
    
    // Access peak assignments
    var dataSection = spectrum.getDataSectionAt(0);
    for (var i = 0, l = dataSection.getDataCount(); i < l; ++i) {
        var value = dataSection.getValueAt(i);
        var extraInfo = dataSection.getExtraInfoOf(value);
        
        if (extraInfo instanceof Kekule.Spectroscopy.SpectrumDataDetails) {
            var atom = extraInfo.getAssignment();
            console.log(molecule.indexOfNode(atom)); // Returns index of the assigned atom
        }
    }
  8. How Kekule.js rendering architecture works

    master

    Kekule.js uses a bridge pattern to achieve platform independence across different 2D and 3D graphics technologies (like SVG, Canvas, or WebGL).

    Key abstractions include:

    • Draw Bridge: A platform-specific implementation (e.g., DrawBridge2DMananger or DrawBridge3DMananger) that handles concrete drawing operations like lines and text.
    • Draw Context: The actual drawing surface created within an HTML element.
    • Renderer: A class responsible for drawing specific object types (like molecules). Instead of instantiating renderers directly, you should use the Renderer Manager (via get2DRendererClass or get3DRendererClass) to obtain the correct class for your object.

    This architecture allows developers to write code once that runs across different environments by abstracting the underlying graphics technology.

  9. Configure Composer via renderConfigs and editorConfigs

    master

    For advanced customization beyond presets, the Composer Widget uses two primary configuration objects:

    1. renderConfigs: Controls aspects like molecule rendering style.
    2. editorConfigs: Controls aspects like interaction style, text font style, and color style.

    These settings can be accessed and modified via the Change Settings button in the common toolbar. For a complete list of available properties within these objects, refer to the official Kekule.js API documentation.

  10. Understand the LGPL (Lesser General Public License) for libraries

    master

    The repository contains references to the GNU Lesser General Public License (LGPL) version 2.1. This license is specifically designed for software libraries to allow for more flexible linking compared to the standard GPL.

    Key Concepts

    • Purpose: To encourage the widest possible use of a library (e.g., making it a de-facto standard) by permitting non-free programs to link with it.
    • Linking: The LGPL permits more lax criteria for linking other code with the library than the ordinary GPL. It distinguishes between a "work based on the library" (derived code) and a "work that uses the library" (combined with the library to run).
    • User Freedom: Even though it is "Lesser" protective, it ensures that a user of a program linked with the library has the freedom to run that program using a modified version of the library.
    • Responsibilities: If you distribute copies of the library, you must provide recipients with the same rights granted to you, including access to the source code and providing complete object files so they can relink the library after making changes.
  11. How resources work in Kekule.js

    master

    A resource is a way to embed molecule data directly into HTML elements (like <script> or <link>) or link to external files using a resource identifier.

    To use a resource:

    1. Embed the data in an element with a specific id and a correct MIME type (e.g., type="chemical/x-mdl-molfile").
    2. Reference the resource using a url(#id) syntax.
    3. Load it asynchronously using Kekule.IO.loadResourceData with a callback function (mol, success).

    Example HTML embedding:

    <script id="molResInsideElem" type="chemical/x-mdl-molfile">
      <!-- MOL file data here -->
    </script>

    Example HTML external link:

    <link id="molResExternalLink" href="./data/mol2D/porphyrin.mol" type="chemical/x-mdl-molfile" />
    // resource is referred by url(#id), similar to CSS URI
    var resId = 'url(#molResInsideElem)';
    Kekule.IO.loadResourceData(resId, function(mol, success)
    {
      if (success)
      {
        console.log('Loading from ' + resId + ' Successful');
        showMolecule(mol);
      }
      else
      {
        console.log('Loading from ' + resId + ' Failed');
      }
    });