Skip to main content

Mascope SDK

Python SDK for the Mascope mass spectrometry data analysis platform. Designed for researchers who want to load and analyze data from a Mascope server in Jupyter notebooks or Python scripts, or export it to use in other environments.

New to Python? The user docs include a step-by-step getting started guide that walks you from installing an editor to running your first tutorial notebook. It is also available on any Mascope instance under /docs/sdk/getting-started/.

Contents

Installation

Prerequisites

Set up a virtual environment

python -m venv .venv

Activate it (Windows):

.venv\Scripts\activate

Or on macOS/Linux:

source .venv/bin/activate

Install the SDK

pip install mascope_sdk

Or with uv:

uv add mascope_sdk

To run the bundled tutorial notebooks, install with the examples extra instead - it adds the plotting and analysis libraries the notebooks use (plotly + nbformat, matplotlib, numpy, scipy, ipykernel):

pip install "mascope_sdk[examples]"   # or: uv add "mascope_sdk[examples]"

Tutorial Notebooks

The best way to learn the SDK is to walk through the bundled example notebooks. They cover everything from basic setup to advanced analysis workflows.

The notebooks need the examples extra (see Installation): pip install "mascope_sdk[examples]".

Copy them to your project directory:

import mascope_sdk

mascope_sdk.copy_examples("./tutorials")

This creates a tutorials/ folder with the following notebooks:

# Notebook Topic
1 01_getting_started.ipynb Connect, list datasets/batches/samples, view a spectrum
2 02_batch_timeseries.ipynb Load peaks across batches, filter, and plot
3 03_intra_sample_timeseries.ipynb Per-scan intensity timeseries for specific compounds
4 04_mass_defect_plot.ipynb Mass defect visualization
5 05_peaks_by_stage.ipynb Compare measurement stages within a single sample
6 06_normalization.ipynb Normalize intensities by TIC or reagent-ion signal
7 07_background_subtraction.ipynb Subtract a background sample (matched ions or m/z bins)
8 08_correlation_analysis.ipynb Find co-varying peaks via correlation and clustering
9 09_batch_stages.ipynb Split a batch into stages and compare per-stage averages
10 10_peak_assignment.ipynb Read a server-side peak-assignment run: tiers, sources, Van Krevelen
11 11_assignment_round_trip.ipynb Assign a sample's peaks yourself, publish the run, compare it with Mascope's

Open them in VS Code (or any Jupyter-compatible IDE) and run the cells. Each notebook is self-contained, just make sure your .env credentials are set up first (see Configuration).

Existing files are never overwritten, so you can safely re-run copy_examples after an SDK update to get new notebooks.

Quick Start

1. Configure credentials

Create a .env file in your working directory (or any parent directory):

MASCOPE_URL=https://example.mascope.app
MASCOPE_ACCESS_TOKEN=your-api-token

Tip: Generate the API token in your Mascope instance's user settings.

2. Use the SDK

from mascope_sdk import MascopeClient

# Auto-loads credentials from .env
mascope = MascopeClient(workspace="My Workspace")

# List datasets (returns a DataFrame). Besides the name, type and instrument,
# each row carries the dataset's descriptive metadata: license, authors
# (name, orcid, affiliation), keywords, related_identifiers and funding,
# empty where the dataset has none
datasets = mascope.datasets.list()

# List batches by dataset name
batches = mascope.batches.list("My Dataset")

# List samples from a single batch (raises if ambiguous)
samples = mascope.samples.list(batch="My Batch")

# List samples from all matching batches (containing the given keyword)
samples = mascope.samples.list(batches="Uronium")

# Load peaks across all samples in matching batches
peaks = mascope.load_peaks(dataset="My Dataset", batches="Uronium")

# Load peaks across a subset of samples, within matching batches
peaks = mascope.load_peaks(dataset="My Dataset", batches="Uronium", samples="12:")

# Plot a sample spectrum (based on sample id)
spectrum = mascope.samples.get_spectrum(sample_id=samples.iloc[0]["sample_item_id"])

import matplotlib.pyplot as plt

plt.scatter(spectrum["mz"], spectrum["intensity"])
plt.xlabel("m/z")
plt.ylabel("Intensity")
plt.show()

See more examples below.

Configuration

The MascopeClient can be configured in three ways (in override priority order):

  1. Constructor parameters (highest priority):

    Initialize client with parameters:

    mascope = MascopeClient(
        url="https://example.mascope.app",
        access_token="your-token",
        workspace="My Workspace",
    )
    
  2. Environment variables:

    Set environment variables:

    export MASCOPE_URL=https://example.mascope.app
    export MASCOPE_ACCESS_TOKEN=your-token
    

    Initialize client (parameters are read from the environment unless overridden):

    mascope = MascopeClient()
    
  3. .env file (recommended for notebooks):

    Create .env file in the project directory:

    MASCOPE_URL=https://example.mascope.app
    MASCOPE_ACCESS_TOKEN=your-token
    

    Initialize client (parameters are read from the .env file unless overridden):

    mascope = MascopeClient()
    

Workspace Selection

The workspace parameter selects which workspace to operate on. It accepts a name, substring, or ID:

# Explicit workspace selection
mascope = MascopeClient(workspace="My Workspace")

If omitted and your account belongs to exactly one workspace, it is auto-selected. If you belong to multiple workspaces, a ConfigurationError is raised listing the available options.

High-Level Loaders

The SDK provides four convenience loaders that handle dataset/batch/sample resolution, concurrent requests, and progress bars automatically. These are the recommended way to load data for analysis.


load_peaks: Peaks across batches

Load averaged peaks ("sum spectrum") for all samples across one or more batches, returned as a single DataFrame enriched with batch and sample metadata.

The batches / samples filters are case-insensitive literal substrings, so one filter can select several batches at once. Pass exact=True to match a single batch by its full name, or a compiled re.Pattern for a regex.

import re

import pandas as pd

# All peaks from every batch whose name contains "Uronium"
peaks = mascope.load_peaks(dataset="My Dataset", batches="Uronium")

# Exactly one batch, by full name
peaks = mascope.load_peaks(dataset="My Dataset", batches="Uronium 2026-01", exact=True)

# Regex: batches from 2025 or 2026
peaks = mascope.load_peaks(
    dataset="My Dataset", batches=re.compile("2025|2026", re.IGNORECASE)
)

# Filter by sample name
peaks = mascope.load_peaks(dataset="My Dataset", samples="blank")

# All peaks from every batch (skip confirmation prompt)
peaks = mascope.load_peaks(dataset="My Dataset", confirm_above=None)

# With match data, areas only
peaks = mascope.load_peaks(dataset="My Dataset", matches=True, heights=False)

# Keep a snapshot of one batch to work on offline, without the server
peaks = mascope.load_peaks(
    dataset="My Dataset",
    batches="Uronium 2026-01",
    exact=True,
    save_path="uronium.parquet",
)
peaks = pd.read_parquet("uronium.parquet")  # later, anywhere: attrs included

Each batch comes a hundred samples per request: the server sends their peak lists as one table (batch_peaks.peak_lists), so a batch of up to a hundred samples is one request. A larger batch is read in parts, so that no request takes the server long enough to time out, two parts at a time. With samples=, the requests name the samples chosen, and the server reads no others. A server older than that read answers 404, and load_peaks then reads each sample on its own, eight at a time, as it always did. The frame is the same either way, with two differences:

  • Match columns. matches left out reads no matches where batches are read a hundred samples per request, and reads them from an older server, as before. Pass matches=True or matches=False to get the same columns from either.
  • is_satellite. The batch read adds this column. It is False throughout, because satellite peaks are left out, as get_peaks leaves them out.

The columns, one row per peak (per match with matches=True):

  • sample_batch_name, sample_item_id, sample_item_name, datetime_utc (the sample's start, UTC).
  • peak_id, mz, area, height (averaged over the sample's scans; summed with average=False), sparsity.
  • signal_to_noise, NaN where the file stores no estimate.
  • segment, only for a stitched sample.
  • is_satellite, as above.
  • With matches, the match columns of get_peaks: target_isotope_id, target_ion_id, target_compound_id and their formulas and names, match_score_isotope, match_score_ion, match_score_compound, relative_abundance, ionization_mechanism, target_collection_ids, target_collection_names.

save_path writes the frame as a Parquet file, attrs included, and pd.read_parquet reads back the same frame: the rows, the provenance and the failures (see Provenance). Nothing is written when the load finds nothing.


load_peak_timeseries: Intra-sample timeseries

Load per-scan intensity timeseries for peaks matching a compound, ion, or isotope across batches. Provide exactly one of compound, ion, or isotope — the value can be a formula or compound name. Pass a list to load multiple targets in a single call (peaks are discovered once per sample).

# Timeseries for all peaks matched to Urea (by name or formula)
ts = mascope.load_peak_timeseries(
    dataset="My Dataset",
    batches="Uronium",
    compound="Urea",  # or compound="CH4N2O"
)

# Multiple compounds in one call
ts = mascope.load_peak_timeseries(
    dataset="My Dataset",
    compound=["Urea", "Lactic acid"],
)

# Plot per-sample timeseries
import matplotlib.pyplot as plt

for name, group in ts.groupby("sample_item_name"):
    plt.plot(group["time"], group["height"], label=name)
plt.legend()
plt.show()

load_peaks_by_stage: Stage-based peak loading

Load averaged peaks for distinct time-range stages of a single sample. Useful when a measurement has phases (e.g. blank, sample introduction, wash).

stages = [
    (0, 30, "blank"),
    (30, 120, "sample"),
    (120, 180, "wash"),
]

peaks = mascope.load_peaks_by_stage(sample="My Sample", stages=stages)

# Compare areas between stages
peaks.groupby("stage_name")["area"].sum()

The sample parameter accepts a sample name or ID. Stage tuples can be (t_min, t_max) or (t_min, t_max, name).

Key columns: stage, stage_name, t_min, t_max, plus all columns from get_peaks.

Peaks left out of a time range

A stage, like any get_peaks(..., t_min=, t_max=), is averaged from each peak's per-scan timeseries, and the server computes a timeseries only when it is first requested. Matching requests the peaks it matches, so the ones still without are mostly the unmatched peaks - and a time-ranged read leaves those out. The frame is then shorter than the same read without a time range, and nothing in its rows shows it.

The server says so in a warning, which the SDK logs and attaches to the frame:

peaks = mascope.load_peaks_by_stage(sample=sample_id, stages=stages)
# WARNING | API warning: 212 peak(s) were excluded because their timeseries
#           have not been computed yet. ... SDK:
#           samples.compute_peak_timeseries('...') computes them.

peaks.attrs["warnings"]  # [] when nothing was left out

When every peak is left out - a sample that was detected and never matched has no timeseries at all - the result is an empty frame that carries the warning, not None. None still means that nothing was found and nothing was warned about.

compute_peak_timeseries requests the timeseries of every peak that has none, which computes and stores them; a time-ranged read made afterwards includes all peaks:

if peaks is not None and peaks.attrs["warnings"]:
    mascope.samples.compute_peak_timeseries(sample_id)
    peaks = mascope.load_peaks_by_stage(sample=sample_id, stages=stages)

It is slow where many peaks are missing: the API computes one peak per request, and the server reads the sample's data file back for each, so a sample that was never matched can take thousands of requests. Give it mz_min / mz_max, or peak_ids=[...], to compute only what the analysis needs. Peaks that already have a timeseries are skipped, so it can be interrupted and run again, and it goes on where it stopped.

Older servers. An empty attrs["warnings"] means "nothing was left out" from a server newer than 1.10.1. Servers up to 1.10.1 warn only while the read still lists some peaks: one that left out every peak is answered exactly as a range that holds none. The SDK cannot tell the two apart there, so an empty time-ranged read from such a server carries a warning of the SDK's own that says it may be either. Their warning also still ends "Re-run peak detection", which does not bring the peaks back; the SDK's hint that follows it in the log is the one to act on.

Combining loads. pd.concat keeps attrs only when every frame's are equal, and the warning carries a count - so two samples that are both short differ, and pd.concat drops their warnings and their provenance. Combine loads with mascope.concat, which keeps both:

peaks = mascope.concat(
    mascope.load_peaks_by_stage(sample=sample_id, stages=stages)
    for sample_id in sample_ids
)

peaks.attrs["warnings"]  # what any of the loads warned, each once
peaks.attrs["provenance"]  # kept when every load came from the same build

attrs["warnings"] is on the frames get_peaks, load_peaks and load_peaks_by_stage return, with the caveats every attrs entry has (see Provenance): read it from the frame the loader returned, or from mascope.concat of several.


load_batch_ledger: The batch ledger

Load a batch's batch ledger — the batch-primary record of peak assignment: one batch peak per species across the batch's samples, with the consensus formula and tier the samples' assignments vote for, and one member per sample the species was seen in, carrying that sample's own reading of the peak. Every processed sample folds in as it arrives, so the ledger is complete without a per-sample run in sight.

# One row per member: the whole ledger of every matching batch, flat
ledger = mascope.load_batch_ledger(dataset="My Dataset", batches="Uronium")
ledger.to_csv("ledger.csv", index=False)  # a short way to any format

# The species table rides along: one row per batch peak
species = ledger.attrs["batch_peaks"]
species.groupby("sample_batch_name")["consensus_tier"].value_counts()

# Or the species table alone
species = mascope.load_batch_ledger(dataset="My Dataset", members=False)

Key columns of a member row: the anchor's batch_peak_id, batch_mz, consensus_formula, consensus_tier, support_fraction, n_present, curated (pinned by hand for the whole batch), beside the member's sample_item_name, sample_peak_id, mz, intensity, assigned_formula, source, tier, role, fit_score — so a sample that dissents from the batch reads as one row saying both. Per batch, the same reads are mascope.batch_peaks.list(batch_id), .members(batch_id, sample_id=...) and .verdicts(batch_id) (the batch-level verdicts recorded on its species). The app's Batch peaks pane exports the same rows as a CSV from its view menu.

load_assignments: Peak assignments across batches

Load the persisted peak-assignment results (see Peak assignments) of every sample across one or more batches, concatenated into a single DataFrame enriched with batch and sample metadata — the peak-assignment counterpart of load_peaks.

Read-only: each sample contributes its latest completed assignment run; samples without one are skipped (and logged), not assigned on the fly.

# Assignments of every sample in matching batches
assignments = mascope.load_assignments(dataset="My Dataset", batches="Uronium")

# Confidently assigned peaks that came from the untargeted stage
assignments = mascope.load_assignments(
    dataset="My Dataset", tier="assigned", source="untargeted"
)

# Tier breakdown per sample
assignments.groupby(["sample_item_name", "tier"]).size()

Key columns: sample_batch_name, sample_item_name, datetime_utc, plus all columns from peak_assignments.get (one row per observed peak; core rows only — fetch alternatives/provenance per assignment with peak_assignments.detail).


Confirmation prompt

load_peaks, load_peak_timeseries, and load_assignments show an interactive confirmation prompt when the number of samples exceeds confirm_above. Defaults are 100 for load_peaks and load_assignments, and 20 for load_peak_timeseries. This prevents accidentally launching hundreds of concurrent requests from a notebook cell. Set confirm_above=None to disable.

A caller with no interactive input - a script run with stdin closed or redirected from /dev/null, a pipeline, an agent's shell - cannot answer the prompt, and is stopped rather than waved through: the loader raises ConfirmationRequiredError before loading anything, with the sample count and the threshold on count and threshold. A script that means to load that many passes confirm_above=None (or a higher threshold).

from mascope_sdk import ConfirmationRequiredError

try:
    peaks = mascope.load_peaks(dataset="My Dataset")
except ConfirmationRequiredError as e:
    print(f"{e.count} samples - narrow the selection, or pass confirm_above=None")

Partial loads

The loaders read sample by sample, and a sample whose read fails does not stop the others: the load returns what it could read, and logs a warning. So that a script can tell "these samples have little in them" from "some samples failed to load", the frame says which it is:

peaks = mascope.load_peaks(dataset="My Dataset", batches="Uronium")
peaks.attrs["complete"]  # True when every read succeeded
peaks.attrs["failures"]  # one dict per failed read, [] when none failed

Each failure names the sample (sample_batch_name, sample_item_id, sample_item_name; load_peaks_by_stage the stage, load_peak_timeseries also the peak_id where a peak's series failed) and the error (error_type, error). When every read failed the loader returns an empty frame carrying the failures, not None, which would say there was nothing to load. load_peaks, load_assignments, load_peaks_by_stage, load_peak_timeseries and samples.list(batches=...) (per batch) report this; mascope.concat of several loads keeps every load's failures, and is complete only when every load was.

Provenance

Every frame a high-level loader returns, and those of batches.ion_series, batch_peaks.series and sample_files.list, carries the provenance of the server that served it, on df.attrs["provenance"]: the deployment's id, the Mascope version it runs, the match-score and peak-assignment engine versions in force, and when this client first heard from that build. Keep it with what you derive from the frame, and a published figure can name the build its numbers came from.

peaks = mascope.load_peaks(dataset="My Dataset", batches="Uronium")

peaks.attrs["provenance"]
# {'provenance_version': 1,
#  'generated_utc': '2026-10-01T12:00:00Z',
#  'deployment_id': 'k3J9xQ2mP0aB7cD1',
#  'produced_with': {'mascope_version': 'vX.Y.Z',
#                    'match_score_version': 1,
#                    'peak_assignment_engine_version': '0.5.0'}}

# The same block, asked directly
mascope.provenance()

The versions describe the server as it runs when asked. A result it stored earlier was computed by whichever build ran then; where a record carries provenance of its own, as a peak-assignment run does on df.attrs["run"], that record is the authority for it.

Frames loaded from one deployment and build carry the same block, so pd.concat of several loads keeps it. Frames from different builds - the server was updated between two loads - carry different blocks, and pd.concat drops the attribute: no single build produced the result. pd.concat compares the whole of attrs, so the same happens when two peak loads differ in attrs["warnings"]. That is not only a load short of peaks beside a whole one: the warning carries a count, so any two loads that are both short differ, which is the usual case for a loop over samples. mascope.concat combines loads without that: it keeps every load's warnings, and the provenance when every load carries the same block.

The attribute is best effort, in two ways. A server that predates it (GET /api/provenance answers 404) returns its frames without the attribute, and the load succeeds as before; so does any other failure to ask, which holds the frame back for about 15 seconds at most. And pandas does not reliably carry attrs through other operations - merge, copy and the like - so read it from the frames the loaders returned, or from their concatenation: the same caveat attrs["run"] and attrs["batch_peaks"] live with.

Keeping it when you save a frame

attrs live only on the DataFrame: saving it as CSV or Excel drops them without a word. Write the block beside the file instead:

import json

peaks.to_csv("peaks.csv", index=False)
with open("peaks.provenance.json", "w", encoding="utf-8") as f:
    json.dump(peaks.attrs["provenance"], f, indent=2)

Parquet keeps attrs inside the file - peaks.to_parquet("peaks.parquet"), and pd.read_parquet brings them back. The SDK requires pandas 2.1 or newer and pyarrow, which this needs; load_peaks(..., save_path=...) does it for you. A load_batch_ledger frame is the exception: its attrs also hold the species table, a DataFrame that Parquet cannot keep there, so to_parquet raises. Save the species table as a file of its own first:

ledger = mascope.load_batch_ledger(dataset="My Dataset")

species = ledger.attrs.pop("batch_peaks")
species.to_parquet("species.parquet")
ledger.to_parquet("ledger.parquet")  # keeps attrs["provenance"]

Peak Assignments

Mascope's peak-centric assignment engine assigns a composition to every observed peak of a sample — database-known targets first (Stage A), then untargeted composition search (Stage B) — arbitrates a single owner per peak, and files each assignment into a confidence tier (assigned | candidate | below_assignability | unassigned). The tier is read off the row's evidence — its fit_score weighted by the chemical plausibility of the assigned formula — under the run's tier_bands. fit_score is served alongside it, unchanged, as the pure fit measurement. Runs are launched from the Mascope app, on ingest, or from the SDK (Running and verifying), and persisted; the SDK reads the results.

The top tier used to be called identified. The API still accepts that spelling wherever a tier is sent and normalises it to assigned, so scripts written against the old vocabulary keep working.

This coexists with targeted matching (mascope.matching, get_peaks match columns): a database-sourced assignment is the targeted result, anchored on the peak.

# Run history of a sample, newest first
runs = mascope.peak_assignments.list_runs(sample_id)

# The whole ledger of the latest completed run: one row per observed peak.
# Pages through the API internally; run metadata rides on df.attrs["run"].
assignments = mascope.peak_assignments.get(sample_id)
assignments.attrs["run"]["engine_version"]
assignments["tier"].value_counts()

# Server-side filters (a bad value raises ValidationError naming the accepted set)
assigned = mascope.peak_assignments.get(sample_id, tier="assigned")
stage_b = mascope.peak_assignments.get(sample_id, source="untargeted")
curated = mascope.peak_assignments.get(sample_id, source="manual")

# A specific (e.g. older) run
old = mascope.peak_assignments.get(
    sample_id, run_id=runs.iloc[-1]["peak_assignment_run_id"]
)

# Full detail of one assignment: alternatives considered + scoring provenance
full = mascope.peak_assignments.detail(
    sample_id, assignments.iloc[0]["peak_assignment_id"]
)

Key get() columns: sample_peak_mz, sample_peak_intensity, role (M0 | iso_child | reagent | artifact | unassigned), assigned_formula, ion_formula, isotope_formula, source (database | untargeted | manual), fit_score, evidence, mz_error_ppm, tier, p_correct, and target_compound_id/target_ion_id for database-sourced assignments.

Hand-curated rows (source: manual)

A person can overrule the engine on a single row from the app's peak inspector — promote a close alternative, or commit a re-search hit. That row is persisted with source manual, so it leaves database/untargeted rather than joining them:

# Wrong: these two no longer sum to the run
stage_a = mascope.peak_assignments.get(sample_id, source="database")
stage_b = mascope.peak_assignments.get(sample_id, source="untargeted")

# Right: read the run once and split it locally, so nothing can fall out
assignments = mascope.peak_assignments.get(sample_id)
assignments.groupby("source", dropna=False).size()

Peaks nothing explained carry no source at all (None), which is why the groupby above passes dropna=False. A manual row is not necessarily an assigned one either: when an override displaces a compound, the isotopologues of that compound are stripped and end up source: manual, tier: unassigned, with no formula.

peak_assignments.detail() on a curated row returns a provenance.manual block — action, user_id, at, and previous (the displaced winner, kept verbatim), plus manual.demoted, the archive of the isotopologues the override stripped so committing that compound back restores them.

Which engine produced a run

A run's ledger does not say who computed it — the run does. list_runs (and df.attrs["run"]) carries:

Column Meaning
engine mascope for a run this deployment computed, otherwise the external engine that published its ledger here. Never null, and mascope is reserved server-side so an import cannot claim it.
engine_version That engine's version string.
tier_bands The assigned / candidate evidence thresholds the run tiered with.
calibration What an external engine disclosed about its calibration at import. Null for mascope runs, whose calibration state is the sample's own.
sigma_ppm, sigma_source The mass-error width the run scored at [ppm], and where it came from. A mascope run says fitted (the sample's own lines) or instrument_class (too few lines, so the class stood in). An imported run gives what its engine disclosed.
mu_ppm, mu_source The mass-error centre the run corrected by [ppm], and where it came from: fitted, reagent or none for a mascope run.

The four width columns are null for a run that never reached scoring, an import that disclosed no width, and the batch run. Read the width a run scored at here instead of measuring it again from the spectrum.

A sample without any run still says what width its lines have. mascope.samples.get(sample_id)["line_width"] holds:

Key Meaning
instrument_class orbi or tof: the class the assignment engine reads the file as.
reference_mz The m/z the width is quoted at, 200.
resolution The resolving power m/dm there, from the instrument functions detection fitted to the file.
fwhm_ppm The full width at half maximum of a line there [ppm], 1e6 / resolution.

resolution and fwhm_ppm are null for a blank and for a file whose instrument functions were never fitted. The line width is not the run's sigma_ppm: one is how wide a peak is, the other how widely the measured masses scatter around the true ones.

This matters because reads default to the latest completed run whatever its engine, so a published run is what you get unless you ask for another. It is also what makes two engines comparable on one sample — read each run by id and join on sample_peak_id:

runs = mascope.peak_assignments.list_runs(sample_id)
runs[["engine", "engine_version", "tier_bands", "status"]]

mine = mascope.peak_assignments.get(sample_id, run_id=<a mascope run id>)
theirs = mascope.peak_assignments.get(sample_id, run_id=<an imported run id>)
side_by_side = mine.merge(theirs, on="sample_peak_id", suffixes=("_mascope", "_ext"))

Compare tiers only against each run's own tier_bands: the same word means different confidence under different thresholds. An imported run's p_correct is always empty — that column is Mascope's own calibrated judgement and an import may not write it.

Running and verifying

Three calls change or score a sample's assignments. The two that write need the editor role on the sample, and a server with peak assignment switched on (peak_assignment = true under [meta]); otherwise they raise PermissionDeniedError.

from mascope_sdk import AssignmentInFlightError, SampleIneligibleError

# Run the engine on a sample, wait for it, and read what it assigned
assignments = mascope.peak_assignments.assign(sample_id)
assignments = mascope.peak_assignments.assign(
    sample_id, config={"run_untargeted": False, "assigned_threshold": 0.8}
)

# Or launch it and come back for it
run_id = mascope.peak_assignments.assign(sample_id, wait=False)
assignments = mascope.peak_assignments.wait_for_run(sample_id, run_id)

try:
    mascope.peak_assignments.assign(sample_id)
except AssignmentInFlightError as e:
    # One run per sample at a time: follow the one already going. Its id is
    # None while the other launch is still creating it; list_runs shows it.
    if e.peak_assignment_run_id is not None:
        mascope.peak_assignments.wait_for_run(sample_id, e.peak_assignment_run_id)
except SampleIneligibleError as e:
    print(e.reason)  # "blank sample (no peaks)", "m/z calibration not verified"

# Record a verdict on one assignment
row = assignments.iloc[0]
mascope.peak_assignments.verify(
    sample_id, row["peak_assignment_id"], "confirmed", evidence_level="msms"
)
verdicts = mascope.peak_assignments.list_verifications(sample_id)
current = verdicts[verdicts["superseded_utc"].isna()]

# Score any composition against the sample: its isotope table
fit = mascope.peak_assignments.fit_aggregate(
    sample_id, row["assigned_formula"], row["ionization_mechanism_id"]
)
  • assign asks the server to run the engine on one sample. The server decides before it answers: it creates the run and returns its id, or refuses. A sample with a run already going raises AssignmentInFlightError, naming that run in peak_assignment_run_id. The name is None while another launch is still creating its run, and wait_for_run refuses a None id with a ValueError: look at list_runs instead. A sample that cannot be assigned, a blank or one whose m/z calibration is not verified, raises SampleIneligibleError with its reason. Neither ever waits.
  • With wait=True, the default, assign looks at the run every poll_interval seconds (5) and returns its ledger as get(sample_id, run_id=...) does. A run that failed raises AssignmentRunError with the run's error; so does a cancelled one, which wrote no rows. If the run is still going after timeout seconds (1800; None waits as long as it takes), AssignmentTimeoutError hands back its peak_assignment_run_id. The run carries on, and wait_for_run waits again.
  • config takes the run's settings, any of them: run_untargeted, profile, context, mz_precision_ppm, formula_ranges, max_untargeted_peaks, peak_intensity_threshold, max_alternatives, assigned_threshold and candidate_threshold. One left out takes the server's default. A run records the settings it ran with under config in list_runs.
  • verify records a verdict: confirmed, rejected or unsure. confirmed needs an evidence_level: reference_standard, msms, orthogonal, pattern or visual. The server keeps every verdict and snapshots the assignment's fit_score, evidence and p_correct beside it. A later verdict on the same peak, formula and adduct replaces the earlier one as the current answer and stamps its superseded_utc.
  • confirmed and rejected verdicts are the labels the instrument's confidence calibration is refitted on. A verdict on an imported run's assignment is recorded the same way but kept out of that refit, because its scores are the external engine's.
  • list_verifications lists every verdict on the sample, newest first: assignment_verification_id, peak_assignment_id, peak_assignment_run_id, sample_peak_id, assigned_formula, ionization_mechanism_id, verdict, evidence_level, note, fit_score, evidence, p_correct, verified_by, verified_utc and superseded_utc.
  • fit_aggregate scores a neutral formula and an ionization mechanism against the sample, as targeted matching scores a compound, and saves nothing. It is how an untargeted assignment, which has no target ion, is checked line by line: match_ions holds the ion and its match_score, match_isotopes one record per isotope line with the peak it matched.

assign and verify are sent once, as every write is (see Changing Data): sent again, they would be carried out twice. A second verdict counts twice in the calibration refit, and a second launch is refused as already in flight. The reads, fit_aggregate among them, are sent again when the server does not answer. If the answer to assign or verify is lost on the way back, the call raises MascopeConnectionError, MascopeTimeoutError or a ServerError (502 to 504) that says the server may have done it: look at list_runs or list_verifications before sending it again.

Verdicts of a batch or dataset

The verification verdicts recorded in the app are the labelled record of what an assignment got right. verifications_for_batch and verifications_for_dataset read them for every sample of a batch or dataset in one request, one row per judged peak, as each sample's assignment ledger shows them:

verdicts = mascope.peak_assignments.verifications_for_batch(batch_id)
confirmed = mascope.peak_assignments.verifications_for_dataset(
    dataset_id, verdict="confirmed", evidence_level="msms"
)

# Join to a run's ledger on the peak
ledger = mascope.peak_assignments.get(sample_id)
judged = ledger.merge(
    verdicts[verdicts["sample_item_id"] == sample_id],
    on="sample_peak_id",
    suffixes=("", "_verdict"),
)

A row is either the sample's own verdict or a batch-level verdict (batch_peaks.verdicts) that reaches it: the sample's peak folded into the judged batch peak and claims the formula and mechanism judged, and the sample has no current verdict of its own on that claim. The second kind has borrowed true. The sample's own verdict wins before the filters apply. Filters: verdict, evidence_level, since (recorded at or after; a time without a zone is UTC) and include_superseded (also the sample's own verdicts a later one replaced; batch-level verdicts are listed live only).

Column Meaning
sample_item_id, sample_item_name, sample_batch_id, filename, datetime, datetime_utc The sample
sample_peak_id, sample_peak_mz The judged peak
assigned_formula, ionization_mechanism_id The claim judged
verdict confirmed, rejected or unsure
evidence_level reference_standard, msms, orthogonal, pattern or visual
fit_score, evidence, p_correct The score snapshot taken when the sample's own verdict was recorded; null on a borrowed one
note, context, verified_by, verified_utc, superseded_utc The record
borrowed A batch-level verdict reaching the sample
assignment_verification_id, peak_assignment_id, peak_assignment_run_id On the sample's own verdict
batch_peak_verification_id, batch_peak_id, stale On a borrowed one; stale when the batch peak's consensus has since left the claim judged

The batch data spreadsheet carries the same table as its Verifications sheet.

Publishing a run of your own

An engine outside Mascope can publish its result for a sample as a run of its own: the same ledger, run selector and batch fold-in as a run Mascope computed, stamped with the engine's name. import_run takes one row per peak and returns the new run's id.

peaks = mascope.samples.get_peaks(sample_id)
rows = my_engine(peaks)  # a DataFrame, one row per peak

run_id = mascope.peak_assignments.import_run(
    sample_id,
    rows,
    engine="my-engine",
    engine_version="0.3.1",
    tier_bands={"assigned": 0.75, "candidate": 0.45},
    calibration={"method": "none"},
    config={"window_ppm": 3},  # the engine's own settings, stored as they are
)
theirs = mascope.peak_assignments.get(sample_id, run_id=run_id)

The columns of a row:

Column Meaning
sample_peak_id The peak (peak_id of get_peaks). Required, one row per peak
sample_peak_mz, sample_peak_intensity The peak as the engine observed it. Required, and never NaN. The intensity is the peak height for an Orbitrap file and the peak area for a TOF file, the quantity Mascope's own engine uses
role Required: M0, iso_child, reagent, artifact or unassigned
sample_peak_tof The peak's time of flight, if the engine has it
assigned_formula, ion_formula, isotope_label, isotope_formula What the engine assigned
ionization_mechanism_id This server's mechanism id, if the engine has it
adduct The adduct's notation, [M+H]+; fills in ionization_mechanism_id where a row has none (below)
source database, untargeted, manual, reagent or artifact
fit_score, mz_error_ppm, abundance_error The engine's measurement; fit_score between 0 and 1
tier Better left out: the server derives it (below)
engine_tier The tier the engine concluded by rules of its own; stored as it is
target_compound_id, target_ion_id For a database row, the library compound and ion
owner_sample_peak_id For an iso_child row, the sample_peak_id of the row it belongs to
alternatives, provenance The inspector's detail. Keep the engine's own numbers under provenance["engine_provenance"]

A frame read with get() imports as it is. The columns the server computes or looks up itself are left out. Its owner_peak_assignment_id links are sent as owner_sample_peak_id from iso_child rows; a reagent's isotope lines, which the in-app engine also links, go without the link. Its tier goes as engine_tier, where the frame has none, and the server derives tier again: the in-app engine settles some rows below what their evidence earns. Any other column is left out with a warning.

  • The frame is checked before anything is sent, and a fault raises ImportValidationError, naming the column and the rows. It catches a missing required column, a value outside a vocabulary, a peak twice, an owner that is not a row of the frame or is itself an iso_child, a NaN in sample_peak_mz or sample_peak_intensity, and a value no JSON can carry. A NaN in any other column is sent as null.
  • Leave tier out. The server reads each row's tier off its evidence, fit_score weighted by the chemical plausibility of assigned_formula, under tier_bands. Where the frame has a tier column, a row stating a tier its bare fit_score cannot reach is refused here, as evidence is never above the fit. Any other disagreement is the server's 422 to raise. A row with no fit or no formula is unassigned or below_assignability.
  • An adduct is resolved by its exact notation: the one mechanism of mascope.ionization.list() written that way, and null when no single one is. A null loses nothing but the join: the adduct is in ion_formula.
  • The rows go in as many requests as the server's caps call for, by row count and by bytes. The first request and the last are sent once, like assign: if an answer is lost, the error says where to look before sending it again. The ones between are sent again, which is safe, as the server applies each row offset once. Any request the server holds up behind another one on the sample (409, code assignment_claim_held) waits for it and goes again.
  • A refused import leaves no run. If the server refuses a request after the run was created, or a request between goes unanswered on every try, import_run deletes the run before raising. abandon_import(sample_id, run_id) deletes any other run left importing, which holds the sample until it ends.
  • A frame well short of the sample's latest completed run is published with a warning: the batch ledger takes the sample's whole contribution from its newest run, so the peaks the frame leaves out leave the batch overview.

The rules the server holds an import to are on the page Publishing an assignment run: the reserved provenance keys (p_correct, calibration and corroboration stripped, evidence and plausibility overwritten), the import_id that makes a repeated create return its run, the 1000-row and 5 MB caps on one request, and what an import replaces and keeps. import_run chooses the import_id and sizes the requests itself. The same page says why calibration is required: an import bypasses the sample's m/z verification, so what the engine calibrated against goes on the record instead.

For cross-sample analysis use the load_assignments loader; for a guided walk-through see tutorial notebook 10_peak_assignment.ipynb, and 11_assignment_round_trip.ipynb for publishing a run and comparing it with Mascope's.

Changing Data

The SDK can also change what your role lets you change: datasets, batches, samples, target collections and compounds, and saved matches. Each write method is one call to one API route and does what that route does, no more: the server checks the fields and your role, and a refusal comes back as the SDK's exceptions.

dataset = mascope.datasets.create("Spring campaign")
mascope.batches.copy(batch_id, dataset["dataset_id"], name="Spring copy")

collection = mascope.collections.create(
    "Organic acids",
    compounds=[
        {"target_compound_formula": "C2H4O2", "target_compound_name": "Acetic acid"}
    ],
)
mascope.collections.associate(collection["target_collection_id"], [batch_id])

preview = mascope.matching.aggregate_batch(batch_id)  # what a save would save
mascope.matching.save_batch(batch_id)
  • A method returns the route's data: the dataset, batch, sample or collection as it now is. One whose route answers with a message alone returns that answer as a dict.
  • A copy, a sample move and a batch delete run in the background on the server: the call returns once the work has started, with its process_id, and the result shows in the listings when it is done.
  • batches.move and datasets.move are one write each and return the moved object. A moved batch keeps its ID, its samples and its target collections; a sample move makes each sample anew under a new ID.
  • Some updates replace rather than add. batches.update leaves the batch's target collections as they are unless target_collection_ids is given; given, it sets them to that list, and an empty list detaches them all. (An older server requires the list: there, to only rename a batch, send the collections it has now.) collections.associate sets the batches a collection is associated with, and an empty list detaches it from them all. collections.update sets a collection's compounds to the ones it creates (compounds=) and names (compound_ids=): to add compounds, send the current compound_ids too, or the ones left out are taken out. samples.update takes the whole sample: start from samples.get, and give an ingested sample (type ACQUISITION, which only the system sets) a user type in the same call, or the route refuses it.
  • A formula change in compounds.update deletes the compound and creates it again under a new ID, with the name and CAS number the item gives: send both with the formula.
  • A write clears the client's cache (see Caching), so the next listing shows the change.
  • A write is sent once. A timeout, a lost connection or a 502 to 504 can come after the server has acted on it, so the SDK does not send it again: a second create would make a second collection, a second save would run the matching twice. The call raises MascopeTimeoutError, MascopeConnectionError or a ServerError; look at what is there before you call it again. The writes that come out the same however often they are sent are retried as reads are: matching.aggregate_sample and aggregate_batch, which save nothing, and the updates that set fields to the values given (datasets.update, batches.update, samples.update, collections.associate, and collections.update when it creates no compounds).
  • Deleting a dataset, a batch, a collection or a compound and matching.resave_batch cannot be undone.

A write your role does not allow raises PermissionDeniedError. The server says only that it refused; the error also names what the call acted on and the role it needs:

from mascope_sdk import PermissionDeniedError

try:
    mascope.datasets.move(dataset_id, other_workspace_id)
except PermissionDeniedError as e:
    print(e.object_type, e.object_id)  # dataset abc123
    print(e.required_role)  # editor in its workspace and in workspace '...'

The role each write needs is listed in the SDK & API guide.

Caching

Dataset, batch, sample, ionization mechanism and ionization mode listings are cached (in volatile memory) automatically after the first call. This speeds up repeated name resolution and avoids redundant API calls. Each call hands out a copy of the cached listing, so editing what you got leaves the cache, and the next call, as fetched. A write made through the SDK clears it. When data on the server changes otherwise (e.g. a batch created in the web app, or a copy the server finishes in the background), the cache needs to be cleared to reload the data on the next call. The cache is not persisted on disk, so restarting the kernel always clears the cache.

# Clear the cache when server data changes
mascope.clear_cache()

API Reference

MascopeClient

from mascope_sdk import MascopeClient

mascope = MascopeClient(workspace="My Workspace")

Resources

All list() methods accept names (or substrings) instead of IDs and return pd.DataFrame | None. A plain string filters case-insensitively as a literal substring — regex metacharacters carry no special meaning, so a name like "Sample (A)" matches as-is. To filter with a regular expression, pass a compiled pattern; case comes from its flags. For example, batches=re.compile("2025|2026") matches batch names containing "2025" or "2026".

mascope.datasets

Method Description Returns
list() List all accessible datasets pd.DataFrame│None
create(name, description=, dataset_type=, instrument=, icon=, workspace_id=) Create a dataset dict
update(dataset_id, name=, description=, icon=, workspace_id=) Rename it, or change its description or icon dict
move(dataset_id, target_workspace_id, workspace_id=) Move it into another workspace dict
delete(dataset_id, workspace_id=) Delete it and everything in it dict
tombstones() What deleted datasets were, newest delete first list[dict]

The writes act in the client's workspace unless workspace_id names another.

A deleted dataset leaves a tombstone: its name, description, descriptive metadata, how many batches, samples and files it held, who deleted it and when, and whether alone or with its workspace. tombstones() returns those of every workspace you are a member of (a global admin's: all of them), across workspaces, not only the client's.

mascope.batches

Method Description Returns
list(dataset) List batches in a dataset (by name) pd.DataFrame│None
update(batch_id, target_collection_ids=, name=, description=) Rename it, change its description, or set its target collections (the whole list) dict
copy(batch_id, dataset_id, name, description=) Copy it into a dataset, in the background dict
delete(batch_id) Delete it and its samples, in the background dict
ion_series(batch_id, collection=, ions=) Each sample's matched intensity of each target ion, one request per collection pd.DataFrame

ion_series returns one row per (sample, target ion) the server holds a match record for: sample_item_id, target_ion_id, target_compound_name, target_compound_formula, ion_formula, ionization_mechanism, intensity and match_category. The misses are rows too: match_category 0 is no match, at intensity 0, so filter on match_category > 0 before counting detections or averaging. It reads the ions of collection (an ID), or the ions named by ID, or else those of every target collection the batch has, with one request each; that last list is the client's cached collections.list, so call clear_cache() after attaching a collection in the same session. Join samples.list(batch=...) on sample_item_id for each sample's time.

mascope.samples

Method Description Returns
list(batch=, batches=, dataset=, samples=) List samples from one or more batches pd.DataFrame│None
get(sample_id) Get sample details dict│None
get_peaks(sample_id, ...) Get peak data with optional match/filter/time params pd.DataFrame│None
get_peak_timeseries(sample_id, mz=, peak_id=) Get intensity over time for a peak pd.DataFrame│None
compute_peak_timeseries(sample_id, peak_ids=) Have the server compute the timeseries peaks lack int
get_spectrum(sample_id, ...) Get averaged spectrum pd.DataFrame│None
get_spectra(sample_ids, ...) Get spectra for multiple samples pd.DataFrame│None
get_centroids(sample_ids, exclude=) Per-scan centroids, flagged ones left out on request dict│None
get_axis_fingerprint(sample_id) Its file's axis fingerprint, with the sample's scans dict
update(sample_id, sample_item) Update a sample's fields (the whole sample) dict
move(sample_ids, batch_id) Move samples into a batch, in the background dict
copy(sample_ids, batch_id) Copy samples into a batch, in the background dict

A get_peaks over a time range (t_min / t_max) leaves out the peaks whose timeseries has not been computed yet; see Peaks left out of a time range.

list accepts exactly one of batch (must match a single batch; raises if ambiguous) or batches (returns samples from all matching batches, with an added sample_batch_name column).

get_centroids returns a dict keyed by sample ID. Each sample's value holds parallel lists with one entry per scan: scan (the scan number), timestamp in seconds, and the scan's centroids as lists of masses, intensities, resolutions, signal_to_noise and flags. A centroid's flags are the sum of the instrument's marks on it: 2 fragmented, 4 merged, 8 exception (a weak side-lobe peak), 16 reference (the lock-mass peak the scan was corrected with), 0 for none. So flag & 16 finds a scan's lock mass. exclude leaves out the centroids that carry any of the flags it names ("reference", "exception", "merged", "fragmented"); without it every stored centroid comes back. A server older than the flags ignores exclude, so given one, an answer without flags raises MascopeAPIError rather than return the centroids asked to be left out.

centroids = mascope.samples.get_centroids(
    [sample_id], exclude=["reference", "exception"]
)
kept = centroids[sample_id]
for scan, masses in zip(kept["scan"], kept["masses"]):
    print(scan, len(masses))

mascope.sample_files

Method Description Returns
get_scans(sample_file_id, fields=, first_scan=, last_scan=, ...) A file's scan table: one row per scan, no centroids pd.DataFrame│None
download_raw(sample_file_id, path) The file's source .raw / .h5, streamed to disk Path
get_axis_fingerprint(sample_file_id) A raw Orbitrap file's axis fingerprint dict
list(datetime_min=, datetime_max=, instrument=, page=, limit=) The files acquired in a time range, in a batch or not pd.DataFrame

list pages through the whole range unless page is given (pages count from 0, limit files each, 1000 by default), oldest file first. datetime_utc is the acquisition's start in tz-aware UTC; datetime is the same moment in the instrument's local time, and acquisition_timezone names that zone where it is known. A time given without a zone is taken as UTC.

A sample names the file it was cut from in sample_file_id (mascope.samples.get(sample_id)["sample_file_id"]). get_scans returns one row per scan of that file with the scan's statistics (ScanNumber, StartTime in minutes, TIC, ScanType, MsType) and its trailer under the instrument's own labels, colon included ("FT Resolution:", "Conversion Parameter B:"). Scans of every MS order are in it and none is left out; filter on MsType for the MS1 scans alone. No peak is read for it, so it stays under a megabyte for a file whose centroids run to hundreds.

file_id = mascope.samples.get(sample_id)["sample_file_id"]
scans = mascope.sample_files.get_scans(
    file_id,
    fields=[
        "Conversion Parameter B:",
        "Conversion Parameter C:",
        "FT Resolution:",
        "MsType",
    ],
    first_scan=1,
    last_scan=100,
)

fields keeps the named columns (ScanNumber always comes with them); first_scan / last_scan, t_min / t_max (seconds) and polarity narrow the scans. The number of scans in the file and the file's own statistics ride on df.attrs["num_of_scans"] and df.attrs["stats_per_file"]. Only a file whose raw Orbitrap data is stored has a scan table; any other is refused with a ValidationError.

download_raw saves the file the instrument wrote, byte for byte as the server stores it, streaming it to disk a megabyte at a time. Give it a directory and the file keeps the name it was uploaded with (a path ending in / is a directory, made if it does not exist yet); give it a file path and it is written there. A download is not resumed: one cut off part way raises MascopeConnectionError and leaves nothing at the destination. The server limits how many files an account may download in a while (60 in ten minutes) and answers 429 past that.

raw = mascope.sample_files.download_raw(file_id, "downloads/")

get_axis_fingerprint returns what Mascope measured of a raw Orbitrap file's m/z axis when it converted the file. On some Orbitrap models the data system divides the frequency axis into frequency bands, and each mass calibration leaves one m/z offset per band on top of a smooth trend; the fingerprint reads those offsets back from the stored profile, per acquisition mode, with the lock mass each scan was corrected with. Mascope never alters an m/z with it. It is a JSON document under the schema mascope.axis_fingerprint, version 1 (libraries/thermo/src/mascope_thermo/axis_fingerprint/axis_fingerprint.schema.json). Read its status first: ok and no_fingerprint carry the whole document; missing (not computed for the file), unavailable and error carry nothing else. ok means that some mode has a table of frequency bands, not that every mode has one: a mode without one, flagged no_segment_table or centroid_only, has segments null. A file that is not an Orbitrap file raises NotFoundError.

fingerprint = mascope.sample_files.get_axis_fingerprint(file_id)
if fingerprint["status"] in ("ok", "no_fingerprint"):
    for mode in fingerprint["modes"]:
        print(mode["mode_id"], mode["flags"], mode["segments"] is not None)

How the fingerprint is measured, and what its flags mean (grid_unmeasured, grid_weak, not_stepwise), is in the reader pipeline notes.

mascope.samples.get_axis_fingerprint(sample_id) returns the same document for the sample's file with an item block: scans, the scan numbers its peak list is built from; mode_id, the mode they belong to, which modes lists first; lock, that mode's lock shares and effective lock mass over those scans; and mz_calibration_factor and file_mz_calibration_factor, what Mascope multiplies into the m/z it serves of the sample's stream and of the file. dominant_mode stays the file's. A stitched sample's mz_calibration_factor is the file's, while its peaks carry the factor of each stream that owns a run of it: streams lists the streams its peak list is read from, each with its stream_key, its scans and its mz_calibration_factor, and get_peaks names each peak's stream in its segment column (the index of an entry of attrs["segments"], whose key is a stream_key). streams is None for a sample over every MS1 scan of its polarity, whose peaks carry the file's factor.

fingerprint = mascope.samples.get_axis_fingerprint(sample_id)
item = fingerprint.get("item")
if item and item["mode_id"]:
    mode = fingerprint["modes"][0]  # the sample's mode
    print(item["lock"]["m_lock_eff"], item["mz_calibration_factor"])
    if mode["segments"]:
        bands = pd.DataFrame(
            mode["segments"]["rows"], columns=mode["segments"]["columns"]
        )

mascope.matching

Method Description Returns
match_compound(sample_id, formula) Match a compound in a sample dict│None
match_compounds(sample_id, formulas) Match multiple compounds list[dict]│None
aggregate_sample(sample_id, target_ion_id=, match_params=) Run a sample's matching, saving nothing dict
aggregate_batch(batch_id, target_ion_id=, match_params=) Run a batch's matching, saving nothing dict
save_sample(sample_id, ...) Run a sample's matching and save it dict
save_batch(batch_id, ...) Run a batch's matching and save it dict
resave_batch(batch_id, ...) Replace a batch's saved matches with a fresh run's dict

The saves take target_ion_id and match_params as the runs do. The batch saves also take match_ions=, match_compounds=, match_collections=, match_samples=: False leaves that level's matches out. save_sample always saves every level; its route takes no such flags. A save answers with the server's status and message.

mascope.collections

Method Description Returns
list(batch_id=, workspace_id=, all_workspaces=) List the workspace's collections and the global ones, or those of one batch pd.DataFrame│None
get(collection_id) One collection, with its compounds and batches dict
create(name, description=, collection_type=, compounds=, compound_ids=, batch_ids=, workspace_id=, is_global=) Create a target collection dict
update(collection_id, name=, description=, collection_type=, compounds=, compound_ids=) Change it or its compounds dict
associate(collection_id, batch_ids) Set the batches it is associated with dict
delete(collection_id, delete_orphan_compounds=) Delete it dict

A collection belongs to the client's workspace unless workspace_id names another, or to every workspace with is_global=True. associate needs only the guest role on the collection, and the editor role on each batch it adds or removes.

mascope.compounds

Method Description Returns
add(compounds) Add compounds, each {"target_compound_formula": ..., "target_compound_name": ...} dict
update(compounds) Update compounds, each with its target_compound_id dict
remove(compound_id) Delete a compound, taking it out of every collection dict
find_structures(formula, cas_number=, name=, limit=) The reference compounds that could give a compound of the formula its structure list[dict]

The compound list is shared by every workspace, so add, update and remove need the global editor role. add lists a compound that already exists (the same name and formula, or CAS number) under existing_compounds instead of creating it again.

find_structures reads, with any role, the rows of the server's active reference lists whose Hill formula is the one given and that carry an InChIKey, an InChI or a SMILES: each with its name, inchikey, inchi, smiles, cas_number, source (the list) and license. The rows recording cas_number come first, flagged cas_match, then those named name, flagged name_match. A row is a candidate, not an identification; to give a compound one, send its fields with update.

mascope.peak_assignments

Method Description Returns
list_runs(sample_id) List a sample's assignment runs, newest first pd.DataFrame│None
get(sample_id, run_id=, tier=, role=, source=) Full run ledger, one row per peak; run metadata on df.attrs["run"] pd.DataFrame│None
detail(sample_id, peak_assignment_id) One assignment in full (alternatives, provenance) dict│None
assign(sample_id, config=, wait=, poll_interval=, timeout=) Run the engine on a sample; with wait=True its ledger, else its run id pd.DataFrame│str│None
wait_for_run(sample_id, run_id, poll_interval=, timeout=) Wait for a run to end and return its ledger pd.DataFrame│None
verify(sample_id, peak_assignment_id, verdict, evidence_level=, note=) Record a verdict on one assignment dict
list_verifications(sample_id) Every verdict on a sample, newest first pd.DataFrame│None
fit_aggregate(sample_id, formula, ionization_mechanism_id) Score a composition against a sample: its isotope table dict
verifications_for_batch(batch_id, verdict=, evidence_level=, since=, include_superseded=) The current verdicts over every sample of a batch, one row per judged peak pd.DataFrame│None
verifications_for_dataset(dataset_id, verdict=, evidence_level=, since=, include_superseded=) The same over every sample of a dataset, in one read pd.DataFrame│None
import_run(sample_id, df, engine=, engine_version=, tier_bands=, calibration=, config=) Publish an external engine's run, one row per peak str
abandon_import(sample_id, run_id) Delete an import left importing, with its rows dict

get reads the latest completed run unless run_id is given, and pages through the API internally — the whole run comes back as one DataFrame. See Peak Assignments, Running and verifying and Publishing a run of your own.

mascope.batch_peaks

Method Description Returns
list(batch_id, tier=, min_n_present=, run_id=) The batch's species table, one row per batch peak pd.DataFrame│None
members(batch_id, sample_id=) The whole ledger, one row per member pd.DataFrame│None
series(batch_id, tier=, min_n_present=2, run_id=) Each sample's intensity of each batch peak, in one read per batch pd.DataFrame
verdicts(batch_id) The batch-level verdicts on its species pd.DataFrame│None
runs(batch_id) The batch runs that rewrote its ledger, newest first pd.DataFrame│None
import_run(batch_id, rows, engine=, engine_version=) Land an external engine's batch-level result as a run dict│None
peak_lists(batch_id, samples=None, matches=False, satellites=False, average=True) Every peak of every sample of the batch, or of the samples named, in one read pd.DataFrame

peak_lists is the batch's peak lists, not its ledger: every sample read as samples.get_peaks reads it with no range, sent by the server as one Parquet table. It needs no ledger and is what load_peaks reads. Its columns are sample_item_id, sample_item_name, datetime_utc, peak_id, mz, sparsity, signal_to_noise, segment, area, height and is_satellite. With matches=True it adds the match columns as the server keeps them, ionization_mechanism_id among them, with no ion or compound score. satellites=True keeps the satellite peaks, sidelobes of a stronger peak that get_peaks leaves out, with is_satellite True. samples= takes a list of sample_item_ids and reads only those; an ID that is no sample of the batch is a failure with status 404. Each ID goes in the request's URL, so name at most a hundred or so per call. df.attrs["failures"] names each sample the server could not read (status_code, error). df.attrs["complete"] is then False, and the rest of the batch is answered without it.

series is the slim counterpart of members: one row per (sample, batch peak) with the member's sample_item_id, sample_peak_id, intensity and tier beside its batch peak's batch_peak_id, batch_mz, consensus_formula, consensus_ion_formula and consensus_tier. min_n_present=2 leaves out the batch peaks only one sample saw. df.attrs["run_id"] names the run the rows are from: run_id when given, else the batch's current run. While a rebuild or search is running, the previous run is still the current one but the live ledger is being rewritten, so the rows may be half of each; series logs a warning then, and a read after the run finishes is the reliable one. See load_batch_ledger.

mascope.ionization

Method Description Returns
list() List available ionization mechanisms pd.DataFrame│None
modes(include_system=False) List the ionization modes pd.DataFrame│None

list() columns: ionization_mechanism_id, ionization_mechanism (the mechanism in the standard adduct notation: [M+H]+, [M-H]-, [M+Br]-, [M]+. for electron transfer), ionization_mechanism_polarity, shipped (whether Mascope ships the mechanism, so that every server holds it from its first start).

modes() gives the chemistries samples are acquired under, one row per mode: ionization_mode_id, ionization_mode_name, ionization_mode_polarity, ionization_mode_token (the file-name token that routes a file to it), instrument (the one instrument it routes files for, or empty for every instrument), ionization_mechanism_ids, system_key (set on a mode Mascope ships), calibration_collection_id and diagnostic_collection_id. A sample names its mode by ionization_mode_id alone; join on it for the name. include_system=True adds the modes Mascope ships that the server has not adopted, which no sample is processed under.

mascope.reference

Method Description Returns
sources() The reference lists the server has loaded, one row per active source pd.DataFrame
compounds(source_name, version=None) The compounds one version of a source holds pd.DataFrame

Reference lists belong to the deployment, not to a workspace, so any role reads them. sources() columns: name, version, label (a shipped list's own label, any other source's name), references (the publications the list comes from, each a dict with citation, doi, isbn and note; as recorded when it was loaded; empty for a source that cites none), license, polarity (empty for a list of either), allow_radicals, known_window, record_count, ingested_at (UTC) and admitted: whether the server's licence gate lets peak assignment match the list. Sorted by label; empty when the server has loaded none.

compounds() takes a source's name, not its label, and reads its active version unless version names another. It pages through the API internally, so the whole version comes back, ordered by mass: name, formula, monoisotopic_mass, inchikey, source_native_id (the list's own id), reference (the DOI the list cites) and tags. df.attrs["version"] names the version read. An unknown source or version raises NotFoundError, as does a server that predates the two routes.

mascope.cheminfo

Method Description Returns
query_by_mz(mz, mechanism_ids, ...) Query potential formulas for an m/z value list[dict]

By default the m/z may be any line of a candidate's ion, not only its monoisotopic one: a 13C or 81Br line, a dibromide's brighter 79Br81Br line, as a peak's m/z often is. A candidate read at another line has that line's m/z as its target_isotope_mz. isotopologues=False searches the monoisotopic line only. known_only=True keeps only formulas of a known reference compound. Both are keyword-only; a server that predates them ignores them, and then searches the monoisotopic line only. The server does not honour limit: it returns every composition it finds, in no ranked order.

Examples

Load peaks and plot by compound

from mascope_sdk import MascopeClient

mascope = MascopeClient(workspace="My Workspace")

peaks = mascope.load_peaks(dataset="My Dataset", batches="Uronium", matches=True)

# Filter to matched peaks and summarise by compound
matched = peaks[peaks["target_compound_formula"].notna()]
summary = matched.groupby("target_compound_formula")["area"].mean()
summary.sort_values(ascending=False).head(10).plot.barh()

Intra-sample timeseries

import matplotlib.pyplot as plt
from mascope_sdk import MascopeClient

mascope = MascopeClient(workspace="My Workspace")

ts = mascope.load_peak_timeseries(
    dataset="My Dataset",
    compound="Urea",
)

# Plot per-isotope timeseries for one sample
sample = ts[ts["sample_item_name"] == ts["sample_item_name"].iloc[0]]
for isotope, group in sample.groupby("target_isotope_formula"):
    plt.plot(group["time"], group["height"], label=isotope)
plt.xlabel("Time (s)")
plt.ylabel("Intensity")
plt.legend()
plt.show()

Compare stages within a sample

from mascope_sdk import MascopeClient

mascope = MascopeClient(workspace="My Workspace")

# First load samples so the name is cached for resolution
mascope.samples.list(batch="My Batch")

stages = [
    (0, 30, "blank"),
    (30, 120, "sample"),
    (120, 180, "wash"),
]

peaks = mascope.load_peaks_by_stage(sample="My Sample", stages=stages)
peaks.groupby("stage_name")[["area", "height"]].mean()

Low-level peak timeseries

import matplotlib.pyplot as plt
from mascope_sdk import MascopeClient

mascope = MascopeClient(workspace="My Workspace")

ts = mascope.samples.get_peak_timeseries(
    sample_id="sample-123",
    mz=180.063,
    mz_tolerance_ppm=5.0,
)

if ts is not None:
    plt.plot(ts["time"], ts["height"])
    plt.xlabel("Time (s)")
    plt.ylabel("Intensity")
    plt.title(f"Peak at m/z {ts['mz'].iloc[0]:.3f}")
    plt.show()

For Developers

Logging

The SDK logs operational info (batch resolution, request counts, etc.) via loguru. The default level is INFO.

Set the MASCOPE_SDK_LOG_LEVEL environment variable to change it:

MASCOPE_SDK_LOG_LEVEL=DEBUG    # verbose (HTTP requests, cache hits, etc.)
MASCOPE_SDK_LOG_LEVEL=WARNING  # quiet (only warnings and errors)

Or in Python before importing the SDK:

import os

os.environ["MASCOPE_SDK_LOG_LEVEL"] = "DEBUG"

from mascope_sdk import MascopeClient

The SDK writes its lines to stderr through a handler of its own, filtered to mascope_sdk. The first client removes loguru's default stderr handler, so those lines are not printed twice. Handlers your application added, before or after, stay in place and receive the SDK's lines too.

SSL Verification

By default the SDK verifies SSL certificates. To disable verification (e.g. for local development with a self-signed certificate), set:

MASCOPE_SDK_VERIFY_SSL=false

Or pass it to the constructor:

mascope = MascopeClient(verify_ssl=False)

Error Handling

from mascope_sdk import MascopeClient
from mascope_sdk.exceptions import (
    AuthenticationError,
    NotFoundError,
    ConfigurationError,
)

try:
    mascope = MascopeClient()
    sample = mascope.samples.get("invalid-id")
except ConfigurationError:
    print("Missing MASCOPE_URL or MASCOPE_ACCESS_TOKEN")
except AuthenticationError:
    print("Invalid API token")
except NotFoundError:
    print("Sample not found")

Exception Hierarchy

  • MascopeError — Base exception
    • ConfigurationError — Missing/invalid configuration
    • MascopeConnectionError — Network/connection issues
      • MascopeTimeoutError — Request timeout
    • MascopeAPIError — API errors (includes status_code, message, url, and the server's answer: body, its detail, and the code that names the condition where the server gives one)
      • AuthenticationError — 401/403 responses
        • PermissionDeniedError — 403: the token is valid, its user lacks the role; a write names its object_type, object_id and required_role
      • NotFoundError — 404 responses
      • ValidationError — 422 responses
        • SampleIneligibleError — peak_assignments.assign on a sample that cannot be assigned; names the reason
      • ConflictError — 409: refused over the state the server is in
        • AssignmentInFlightError — peak_assignments.assign on a sample with a run going; names its peak_assignment_run_id
      • ServerError — 5xx responses
    • AssignmentRunError — a run assign or wait_for_run waited for failed (its error) or was cancelled
    • AssignmentTimeoutError — the wait ended before the run did; carries its peak_assignment_run_id

Branch on code rather than on the wording of message: the message is written for a person, and two conditions can share a status code.

Project Structure

mascope_sdk/
├── __init__.py          # Public exports (MascopeClient, exceptions)
├── client.py            # MascopeClient: main entry point and high-level loader methods
├── exceptions.py        # Exception hierarchy
├── _http.py             # Low-level HTTP session (requests wrapper)
├── _resolve.py          # Name-to-ID resolution helpers
├── _loaders.py          # High-level loaders (load_peaks, load_peak_timeseries, load_peaks_by_stage, load_assignments)
├── _concurrent.py       # ThreadPoolExecutor wrapper with progress bars and cancellation
├── _agents.py           # Internal HTTP helpers for Mascope agents (file-agent)
├── resources/
│   ├── _base.py         # BaseResource: shared HTTP helpers and datetime coercion
│   ├── batches.py       # BatchesResource
│   ├── cheminfo.py      # CheminfoResource (m/z queries)
│   ├── datasets.py      # DatasetsResource
│   ├── ionization.py    # IonizationResource
│   ├── matching.py      # MatchingResource (compound matching)
│   ├── peak_assignments.py  # PeakAssignmentsResource (read persisted assignment runs)
│   ├── reference.py     # ReferenceResource (the server's reference lists)
│   ├── sample_files.py  # SampleFilesResource (a file's scan table)
│   ├── samples.py       # SamplesResource (peaks, spectra, timeseries)
│   └── workspaces.py    # WorkspacesResource
└── examples/            # Jupyter notebook examples

Key patterns:

  • client.py owns the public API. High-level loaders (load_peaks, etc.) are thin wrappers that delegate to _loaders.py.
  • resources/ contains one class per API domain. Each resource inherits BaseResource which provides _get() / _post() helpers and automatic datetime column coercion.
  • _concurrent.py centralises ThreadPoolExecutor usage with run_concurrent(), which handles progress bars (tqdm), None-filtering, future cancellation on error, and the max_workers <= 8 guard. It returns the failed tasks beside the results; mark_complete() turns them into a frame's attrs["complete"] / attrs["failures"].
  • _resolve.py handles name matching (literal substring for strings, regex for compiled patterns) and name -> ID resolution (used by resources and loaders).
  • Underscore-prefixed modules (_http, _loaders, _concurrent, _resolve, _agents) are internal — not part of the public API.

Metadata

Release files for mascope_sdk 2026.11.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mascope_sdk 2026.11.4
File Size Uploaded Provenance Actions
mascope_sdk-2026.11.4.tar.gz 210.9 kB Without provenance Details for mascope_sdk-2026.11.4.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mascope_sdk 2026.11.4
File Interpreter ABI Platform Actions
mascope_sdk-2026.11.4-py3-none-any.whl Python 3 none any Details for mascope_sdk-2026.11.4-py3-none-any.whl

Total release size: 421.7 kB

Release files / mascope_sdk-2026.11.4.tar.gz

Download URL mascope_sdk-2026.11.4.tar.gz
Size 210.9 kB
Tags Source
SHA-256 checksum
How to use checksums
01442707f6ec5b2c9aa0da5d226c667a5b8fe841c1da42066eefa1bdfcc686d6
BLAKE2b-256 checksum
How to use checksums
b1f6938384b9358e4c505d75862837b88107ab7bd907d0f8ea357d5fed6979c4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.1 {"installer":{"name":"uv","version":"0.13.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / mascope_sdk-2026.11.4-py3-none-any.whl

Download URL mascope_sdk-2026.11.4-py3-none-any.whl
Size 210.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1eb42fe6475b7cee92d2c0aec349980d8b22ea4eac908b3c984d76a605d821d4
BLAKE2b-256 checksum
How to use checksums
682e881580e8b3a42553a1aeb93603e2e91770e17417229be375f6be588b94ee
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.1 {"installer":{"name":"uv","version":"0.13.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for mascope_sdk 2026.11.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page