Metadata-Version: 2.5
Name: megan-onnx
Version: 0.1.0
Summary: Run MEGAN explainable graph neural networks for molecules from their ONNX exports, without PyTorch
Project-URL: Homepage, https://github.com/the16thpythonist/vgd_web
Project-URL: Source, https://github.com/the16thpythonist/vgd_web/tree/master/megan_onnx
Author-email: Jonas Teufel <jonseb1998@gmail.com>
License-Expression: MIT
License-File: LICENSE
Keywords: MEGAN,ONNX,counterfactuals,explainable AI,graph neural networks,molecules
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Chemistry
Requires-Python: >=3.10
Requires-Dist: numpy>=1.24
Requires-Dist: onnxruntime>=1.18
Requires-Dist: rdkit>=2023.9
Requires-Dist: rich-click>=1.7
Provides-Extra: test
Requires-Dist: pytest>=7; extra == 'test'
Description-Content-Type: text/x-rst

==========
megan-onnx
==========

Runs MEGAN models, graph neural networks that predict a property of a molecule *and explain their
prediction*, from their ONNX exports. It needs nothing heavier than NumPy, RDKit and ONNX Runtime: no
PyTorch, no graph_attention_student.

megan-onnx computes what the `MeganExplains <https://github.com/the16thpythonist/vgd_web>`_ website
computes in the browser, and gets the same numbers:

- the **prediction** of a model, or of an ensemble with the **uncertainty** that its spread gives;
- the **explanation**: how important each atom and bond is for each explanation channel, with the
  ensemble's explanations combined as on the website (``average``, ``max``, ``min`` or ``disagreement``);
- what each channel **contributes** to the prediction (its leave-one-out deviation);
- **counterfactuals**: the molecules one or two edits away whose prediction changes the most, each
  described in words, such as "Amino group on the ring". The search runs offline.

It downloads models from the website, or loads any MEGAN model exported by graph_attention_student 1.7.0
or newer.

Installation
============

.. code-block:: console

    pip install megan-onnx

It needs Python 3.10 or newer. The "Python script" button on a model's page writes a script that installs
megan-onnx with `uv <https://docs.astral.sh/uv/>`_ and repeats the prediction on the page.

Predicting
==========

.. code-block:: python

    from megan_onnx import load_model

    # The address of the model's page on the website. The model is downloaded into megan_models/ the first
    # time; a version that is there already needs no network.
    model = load_model('https://megan.example.org/#/models/megan_solubility', version=4)

    result = model.predict('CC(C)Cc1ccc(cc1)C(C)C(=O)O', explain='min', contributions=True)
    print(result.summary())

.. code-block:: text

    Megan Water Solubility, version 4, an ensemble of 3 models
    Molecule: CC(C)Cc1ccc(cc1)C(C)C(=O)O

    Prediction: -3.79 ± 0.52 logS (low uncertainty)

    Explanation (min of the models):
      Lowers solubility: most important atoms C4, C5, C9, C3, C6; contributes -2.11 ± 0.64 logS
      Raises solubility: most important atoms C12, O14, O13, C10, C11; contributes +1.75 ± 0.52 logS

A ``Prediction`` holds the numbers:

- ``result.value``: one value per output, the ensemble's mean (a classifier's class probabilities), and
  ``result.members`` each model's own;
- ``result.uncertainty``: ``value``, ``level`` (``"low"``, ``"medium"`` or ``"high"``) and the ``spread``
  per output; None for a single model;
- ``result.explanation``: ``node_importance`` (atoms × channels) and ``edge_importance`` (edges ×
  channels), between 0 and 1, with the ``edge_indices`` of the edges (two per bond) and the ``atoms``;
- ``result.contributions``: per channel, its ``value`` and ``spread``, in the model's unit (for a
  classifier, in the log-odds of the predicted class).

``model.predict_many(smiles_list)`` predicts many molecules in batches. ``result.to_dict()`` and
``result.save_json(path)`` give everything as JSON.

Counterfactuals
===============

.. code-block:: python

    search = model.counterfactuals('CC(C)Cc1ccc(cc1)C(C)C(=O)O', edits=2, direction='pos', num_results=8)
    print(search.summary())
    search.save_csv('counterfactuals.csv')

``direction`` is ``"pos"`` (the molecules whose prediction is lowest compared to the input first),
``"neg"`` (the highest) or ``"abs"`` (the largest change either way); by default, the model's. With
``leave_out_uncertain=True`` (the default), molecules about which an ensemble is highly uncertain are left
out. Each ``Counterfactual`` has its ``smiles``, ``value``, ``change``, ``uncertainty``, ``description``
and the ``atoms`` that changed.

The molecules nearby are made with RDKit: atoms added, bonds added, removed or changed in order, as the
website's model settings allow. For two edits, the best one-edit molecules are expanded once more, up to
``max_candidates`` molecules (10,000) in all.

Other exports
=============

``load_model`` also takes a folder: the export folder that graph_attention_student writes (with its
manifest.json and model.onnx), or an ensemble's folder with an ensemble.json that lists its members'
folders and the calibration of the uncertainty.

.. code-block:: python

    from megan_onnx import load_export

    model = load_export('results/onnx_export', channels=['lowers', 'raises'], unit='logS')

Without the website's settings, the channels are called "Channel 1", "Channel 2", ... and the classes
"Class 0", "Class 1", ...; keyword arguments set them (see ``ModelInfo``).

The command line
================

.. code-block:: console

    megan-onnx predict https://megan.example.org/#/models/megan_solubility -s CCO -s c1ccccc1O
    megan-onnx predict path/to/onnx_export --csv molecules.csv --column smiles -o predictions.csv
    megan-onnx counterfactuals https://megan.example.org/#/models/megan_solubility -s CCO --edits 2 -o cf.csv
    megan-onnx download https://megan.example.org/#/models/megan_solubility --version 4
    megan-onnx info megan_models/megan_solubility-v4

``megan-onnx --help`` and ``megan-onnx COMMAND --help`` list the options.

How it matches the website
==========================

A MEGAN model reads a molecule as a graph with features per atom and bond. Every export's manifest.json
says how its training data was featurized, column by column; megan-onnx rebuilds the features from that
description with RDKit, as the website's megan.js does in the browser. They match graph_attention_student's
featurization exactly, for every one of the 439,032 molecules of the AqSolDB, Ames and TADF datasets that
were checked, and the tests compare the outputs with those that PyTorch recorded in each export's
fixtures.json. The models run on the CPU with one thread, which gives the same results from run to run.

Development
===========

megan-onnx lives in the ``megan_onnx/`` folder of the MeganExplains repository, whose backend uses its
counterfactual neighbourhoods and descriptions too.

.. code-block:: console

    cd megan_onnx
    uv venv && uv pip install -e ".[test]"
    .venv/bin/python -m pytest

Licence
=======

MIT. The molecule edits (``edits.py``) come from vgd_counterfactuals 0.3.14, also MIT.
