AI QSAR ======= Let's walk through how to use AI QSAR to build an activity model for a target protein and predict on a new compound library. AI QSAR learns from published ChEMBL activity data for a target protein and builds a model that predicts activity for new compounds. Unlike the single-submission modules in this SDK, it is a 5-stage pipeline -- fetch, confirm task, compute descriptors, train, predict -- where each stage is its own blocking call, its own token cost, and its own result slot. Once a project reaches the predict stage, the earlier four stages are permanently locked; predict itself can be re-run as many times as you like. ``descriptor``/``train``/``predict`` run on a remote compute instance and can take anywhere from minutes (descriptor) to hours (train, up to 4h). Only ``fetch``/``confirm`` run in-process and return almost immediately. :: qsar = molcube.create_qsar_project() Resume an Existing Project ---------------------------- If you already have a submitted AI QSAR project id, resume it with :py:meth:`resume_project() ` instead of creating a new one:: qsar = molcube.create_qsar_project() qsar.resume_project("submitted-qsar-project-id") qsar.get_stage() # one of "created", "fetched", "confirmed", "descriptor", "trained", "predicted" Resuming clears any task/results this ``QsarProject`` instance had cached locally, so it is safe to reuse one object across several projects one after another -- :py:meth:`get_results() `, :py:meth:`run_train() `, etc. all re-derive their state from the newly resumed project rather than leaking the previous one's. Note that the confirmed task itself (binary vs. regression) is re-derived from the server on first use after resuming, not restored instantly -- see the note on :py:meth:`get_pvalues() ` below about the pValue snapshot not surviving a resume either. Find a Target -------------- Every project is keyed to a UniProt accession. If you already know it, skip to the next section and pass it straight to ``create_project()``. If you only know a gene name, look it up with :py:meth:`search_targets() `:: for hit in qsar.search_targets("EGFR"): print(hit["acc"], hit["genes"], hit["proteinName"]) # P00533 EGFR ERBB ERBB1 HER1 Epidermal growth factor receptor Matching is case-insensitive and ranked: an exact accession returns that entry alone, otherwise gene names, entry names and accession prefixes are matched and the shortest match wins (searching ``"TP53"`` puts ``TP53`` above ``TP53TG1``). At most 50 results come back. The search runs locally against the reviewed-human UniProt index, which :py:meth:`get_protein_index() ` fetches once and caches for the life of the process -- repeated searches cost no further requests. Call it directly only if you want the index itself (its ``release`` id or entry ``count``); pass ``force=True`` to either method to re-fetch. .. warning:: This index is a server-side snapshot provisioned by a monthly background task, so a deployment that has not yet built one (or cannot reach UniProt) will make both methods raise. That is a lookup convenience failing, not the pipeline -- ``create_project()`` accepts a UniProt accession directly whether or not the index is available. Fetch and Curate ChEMBL Data ----------------------------- Fetch and curate ChEMBL activity records for a target with :py:meth:`create_project() `:: assert qsar.create_project( title="EGFR binary QSAR", uniprot_id="P00533", # EGFR organism="Homo sapiens", # ignored when all_organisms=True assay_types=["IC50", "Kd"], # order = tie-break priority when a compound has both relations=["="], # "=" only, or add "<", "<=", ">", ">=" to widen outlier_clip=(3.0, 11.0), # pValue range kept after curation ) This call always curates in regression mode and blocks until fetch finishes -- there is no ``task`` argument. Binary vs. regression is decided in the next step, after you have seen the actual pValue distribution. Locally validated before anything is sent: ``title`` (non-empty, ≤100 chars), ``uniprot_id`` (non-empty, no whitespace, ≤20 chars), ``engine`` (only ``"ml"`` is implemented -- ``engine="dl"`` raises ``NotImplementedError`` immediately rather than burning a fetch+descriptor token before failing in training), and ``workspace`` (``"personal"`` or ``"team"``). Inspect the curation result ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Before choosing binary/regression cutoffs, look at how much data survived curation and how it is distributed:: summary = qsar.get_fetch_summary() summary["nCompounds"], summary["nRaw"] # curated count / raw ChEMBL count summary["fetchSource"] # "sqlite" (local snapshot) or "api" (slower REST fallback) pvalues = qsar.get_pvalues() # same data as the curation histogram impact = qsar.get_filter_impact_frame() # which filter removed how much, as a DataFrame ``pvalues`` are on the ``pValue = 9 - log10(nM)`` scale -- larger means a stronger compound. ``get_filter_impact_frame()`` reports each filter's effect independently against the raw data, not as a sequential pipeline, so the rows do not sum to the total removed. **Note:** :py:meth:`get_pvalues() ` and :py:meth:`get_filter_impact_frame() ` only work before :py:meth:`confirm_task() ` is called. Confirming overwrites this part of the server response, so the SDK caches a snapshot right after fetch and falls back to it automatically. If neither the live response nor a snapshot is available (e.g. resuming an already-confirmed project from another session), both raise ``ValueError``. Confirm the task type ^^^^^^^^^^^^^^^^^^^^^^ Decide binary classification or regression with :py:meth:`confirm_task() `, based on what you just saw:: assert qsar.confirm_task("binary", active_nm=1000, inactive_nm=10000) For binary, compounds at or below ``active_nm`` are labeled active, compounds at or above ``inactive_nm`` are labeled inactive, and everything strictly between the two (the "grayzone") is dropped from training. ``active_nm`` must be strictly less than ``inactive_nm`` -- an inverted or equal pair is rejected locally before the request is sent, and if the gap swallows every compound the server itself rejects the confirmation. This step costs no tokens and does not require re-fetching, so trying a few different cutoffs is normal practice. To resubmit fetch with different curation options instead (a new UniProt ID, different assay types, etc.), use :py:meth:`refetch(**overrides) `, which keeps every option you don't override. Compute Descriptors --------------------- Turn the curated compounds into numeric features with :py:meth:`run_descriptor() `:: assert qsar.run_descriptor( morgan_radius=2, # 2 = ECFP4 morgan_nbits=1024, do_select=True, # drop low-variance / high-missing / highly-correlated columns variance=0.0, missing=0.0, correlation=0.95, external_csv="external_val.csv", # optional -- smiles + label columns ) All 5 descriptor sets (``ecfp4``, ``rdkit``, ``mordred``, ``rdkit_mordred``, ``chemberta``) are always computed together in one job for one token -- there is no option to compute a subset. This is usually the slowest of the cheap stages, since Mordred alone produces ~1,800 columns per compound. ``external_csv`` is optional and supplies a held-out validation set (``smiles`` + ``label`` columns, no empty cells) that :py:meth:`run_train(use_external=True) ` scores against later, in addition to the standard cross-validation. It is validated locally (columns present, no empty cells) before upload. Check what survived feature selection with :py:meth:`get_descriptor_summary() `:: summary = qsar.get_descriptor_summary() {s["name"]: s["nCols"] for s in summary["sets"]} # remaining feature count per set A set-level ``skipped`` flag means that one descriptor set alone failed (e.g. ChemBERTa needing a model download) -- the other four can still succeed independently. Train Models -------------- Cross-validate one or more models against every descriptor set with :py:meth:`run_train() `:: from molcube.qsar import MlModel, TuneMode, Scaler assert qsar.run_train( models=[MlModel.RF, MlModel.XGB], val_method="", # "" resolves to the task's default (skf/kfold) tune_mode=TuneMode.FIXED, scaler=Scaler.STANDARD, k=5, seed=42, use_external=True, # score against the external_csv uploaded above, if any ) Every model in ``models`` is trained against all 5 descriptor sets, so ``models=[RF, XGB]`` produces 10 trained combinations. ``models`` is checked against the confirmed task before anything is submitted -- ``ridge`` is regression-only, ``lr`` is binary-only, and mismatches raise ``ValueError`` immediately rather than failing deep inside a training container hours later. Note that ``n_jobs`` is deliberately left out above. Leaving it unset lets the server pick the right parallelism for the ``tune_mode`` you chose -- 4 for ``FIXED``, 48 for ``GRID`` -- and that default is what a grid search needs to finish at all. Pass an explicit ``n_jobs`` (1-48) only when you have a reason to; anything outside that range raises ``ValueError`` before the job is submitted. Grid search costs more than fixed ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ``tune_mode=TuneMode.GRID`` searches each model's full parameter grid across all 5 descriptor sets, so it runs for hours rather than minutes and gets a wider server-side timeout (12 hours, against 4 for ``FIXED``). It also costs more. Train is the one stage in this pipeline whose token cost is not flat: it is billed on the instance the run actually rents (vCPUs x runtime) on top of a 1-token base. A short ``FIXED`` run still costs 1 token, but a full-width grid run can cost several. Estimate before you submit:: from molcube.qsar.utils import estimate_train_tokens estimate_train_tokens(runtime_hours=0.5, tune_mode="fixed", models=["rf", "xgb"]) # 1 estimate_train_tokens(runtime_hours=8, tune_mode="grid", models=["rf"]) # 3 estimate_train_tokens(runtime_hours=12, tune_mode="grid", models=["rf"]) # 5 ``runtime_hours`` is your own estimate of how long the run will take -- the server bills on actual elapsed time, so this is a planning aid, not a quote. ``run_train()`` neither calls it nor blocks on it. .. warning:: Do not hardcode ``n_jobs=4`` for a grid search. A grid run at 4 jobs overruns even the 12-hour timeout and fails, losing the token; the same run at the server's own default (48) finishes in roughly 8 hours. Omitting ``n_jobs`` gets you the right value for whichever ``tune_mode`` you passed. Inspect training results ^^^^^^^^^^^^^^^^^^^^^^^^^^ :: results = qsar.get_train_results() # raw slot: rows / bestKey / task / scoreKey frame = qsar.get_train_frame() # the same rows as a DataFrame best = qsar.get_best_combo() # server-chosen {"set", "model"} qsar.list_trained_combos() # every trained {"set", "model"} roc = qsar.get_roc_curve(best) # binary tasks only scatter = qsar.get_scatter(best) # regression tasks only importance = qsar.get_feature_importance(best) # tree models only (rf/xgb/lgb) :py:meth:`get_train_frame() ` excludes the nested ``roc``/``scatter``/``featImp`` arrays by default -- use the dedicated accessors above for those. Every accessor that takes a ``combo`` argument accepts a ``(set, model)`` tuple, a ``{"set", "model"}`` dict, or a row taken straight from ``get_train_frame()``. Predict on a New Library -------------------------- Run trained combos against a new compound library with :py:meth:`run_predict() `:: run = qsar.run_predict( "library.csv", # local CSV with a smiles column, uploaded fresh every call combos=[best, ("ecfp4", "rf")], threshold=None, # binary only; None = automatic Youden's J top_n=50, ) run["combos"] # this run's successful combos run["failed"] # this run's failed combos -- not an exception, logged as a warning Unlike the earlier stages, predict is not locked and can be called again as many times as needed -- each call requires its own fresh CSV upload (there is no "reuse the last file" option). A combo you never trained is rejected before the file is even uploaded. When a combo names a model by its short identifier (``"rf"``) rather than the display name the training run actually saved it under (``"Random Forest"``), it is resolved automatically against what this project trained -- both spellings work. Because predict results accumulate on the server across every run a project has ever done, and the server -- not the caller -- decides each run's id, :py:meth:`run_predict() ` snapshots the results before and after submission and returns only what this call added. Inspect predict results ^^^^^^^^^^^^^^^^^^^^^^^^^ :: qsar.get_predict_results() # every run this project has ever submitted qsar.get_predict_frame() # same data, one row per run x combo qsar.list_predict_runs() # grouped by run id qsar.get_predict_top_frame(run["combos"][0]) # one combo's top-N preview rows qsar.get_dropped_smiles_reports() # compounds the standardizer could not parse Download Outputs ------------------ Each download method returns the local path it was saved to:: qsar.download_train_model(best, "best_model.pkl") qsar.download_predict_result(run["combos"][0], "predictions.csv") qsar.download_project("qsar_project.tar.gz") qsar.download_pkl_usage_notebook("qsar_pkl_usage.ipynb") :py:meth:`download_predict_result() ` needs the ``run`` id to disambiguate accumulated runs, so pass the full combo dict a predict call returned rather than reconstructing ``{"set", "model"}`` by hand. :py:meth:`download_project() ` bundles the most recently completed stage's outputs (predict → train → descriptor → fetch, in that priority) -- raw ChEMBL data and descriptor matrices are never included -- and raises ``ValueError`` locally if no stage has completed yet, instead of a server error. Use a downloaded model ^^^^^^^^^^^^^^^^^^^^^^^^ A ``.pkl`` on its own is not enough to predict with: it records neither the Morgan fingerprint settings it was trained on nor the class definitions an MLP model needs to unpickle. :py:meth:`download_pkl_usage_notebook() ` gets you a runnable notebook with all of that filled in from *this* project's own Step 2 options, so pair it with any ``.pkl`` you download:: qsar.download_train_model(best, "best_model.pkl") qsar.download_pkl_usage_notebook("qsar_pkl_usage.ipynb") It does not need any stage to have finished -- the server renders it from the project's stored options alone. A copy also ships inside ``download_project()``'s archive once training has produced at least one model, so this method is mainly for when you want a single model rather than the whole bundle. .. note:: The server always names this file ``qsar_pkl_usage.ipynb``, and that name wins over the path you pass if you pass a *directory*. Downloading notebooks for several projects into one directory will overwrite the same file each time -- give each an explicit file path, as above. Status and Utilities ---------------------- * ``get_step()`` / ``get_options()`` -- the raw ``project_step`` integer and its options. ``step == 1`` is ambiguous (it means both "fetch not run" and "fetch done, confirm pending"), so prefer ``get_stage()`` for status checks. * :py:meth:`get_stage() ` -- one of ``"created"``, ``"fetched"``, ``"confirmed"``, ``"descriptor"``, ``"trained"``, ``"predicted"``, resolved unambiguously from all 4 result slots. * :py:meth:`get_results(refresh=False) ` -- the raw ``{"fetch", "descriptor", "train", "predict"}`` slots, cached until the next successful submission. * :py:meth:`stop_project() ` -- cancels the currently running stage. Meaningful for descriptor/train/predict (which run remotely); fetch/confirm usually finish before a cancel would matter. * :py:meth:`smiles_to_svg(smiles) ` -- renders one SMILES string as a 2D structure SVG. Stateless -- no project or prior submission required.