API reference

Experiments

Experiment class and related.

exception qslib.experiment.AlreadyExistsCompleteError(machine: dataclasses.InitVar[Machine], name: str)[source]

Bases: AlreadyExistsError

A run already exists in uncollected (experiment:) with the same name.

exception qslib.experiment.AlreadyExistsError(machine: dataclasses.InitVar[Machine], name: str)[source]

Bases: MachineError

A run already exists with the same name.

exception qslib.experiment.AlreadyExistsWorkingError(machine: dataclasses.InitVar[Machine], name: str)[source]

Bases: AlreadyExistsError

A run already exists in uncollected (experiment:) with the same name.

exception qslib.experiment.AlreadyStartedError(name: str, state: str)[source]

Bases: ValueError

The experiment has already been started.

exception qslib.experiment.DataLoadingError(name: str, message: str, cause: Exception)[source]

Bases: Exception

The data could not be loaded.

exception qslib.experiment.DataNotAvailableError(name: str, message: str)[source]

Bases: Exception

The data is not available.

class qslib.experiment.Experiment(name: str | None = None, protocol: Protocol | None = None, plate_setup: PlateSetup | None = None, _create_xml: bool = True)[source]

Bases: object

A QuantStudio experiment / EDS file

This class can create, modify, load and save experiments in several ways, run them, and control and modify them while running.

Experiments can be loaded from a file:

>>> exp: Experiment = Experiment.from_file("experiment.eds")

They can also be loaded from a running experiment:

>>> machine = Machine("localhost", password="password")
>>> exp = Experiment.from_running(machine)

Or from the machine’s storage:

>>> exp = Experiment.from_machine(machine, "experiment")

They can also be created from scratch:

>>> exp = Experiment("an-experiment-name")
>>> exp.protocol = Protocol([Stage([Step(time=60, temperature=60)])])
>>> exp.plate_setup = PlateSetup({"sample_name": "A5"})

And they can be run on a machine:

>>> exp.run(machine)

Data can be accessed in a few ways:

The (hopefully) easiest way is with welldata, which has multi-indexes for both rows and columns.

>>> exp.welldata.loc[('x1-m4', 4), [('time', 'hours'), ('A05', 'fl')]].plot()

Or for a temperature curve:

>>> exp.welldata.loc[('x1-m4', 4), [('A05', 'st'), ('A05', 'fl')]].plot()

filterdata should still work normally.

Notes

There are a few differences in how QSLib and AB’s software handles experiments.

  • AB’s software considers the run as starting when the machine indicates “Run Starting”. This is stored as runstarttime in QSLib, but as it may include the lamp warmup (3 minutes) and other pre-actual-protocol time, QSLib instead prefers activestarttime, which it sets from the beginning of the first real (not PRERUN) Stage, at which point the machine starts its own active clock and starts ramping to the first temperature. QSLib uses this as the start time reference in its data, and also includes the timestamp from the machine.

  • The machine has a specific language for run protocols. QSLib uses this language. AB’s Design and Analysis software does not, instead using an XML format. Not everything in the machine’s language is possible to express in the XML format (eg, disabling pcr analysis, saving images); the XML format has some concepts not present in the machine format, and is generally more complicated and harder to understand. QSLib uses and trusts the machine’s protocol if at all possible, even for files written by AB D&A (it is stored in the log if the run has started).

  • QSLib will try to write a reasonable XML protocol for AB D&A to see, but it may be an approximation or simply wrong if the actual protocol can’t be expressed there. It stores the lossless machine-language protocol separately in qsl-tcprotocol.xml.

  • By default, creating a step with a per-cycle increment in QSLib starts the change on cycle 2, not cycle 1, as is the default in the software.

  • Immediate pause/resume, mid-run stage addition, and other functions are not supported by AB D&A and experiments using them may confuse the software later.

  • QSLib writes notes to XML files, and tries to create reasonable XML files for AB D&A, but may still cause problems. At the moment, it makes clear that its files are its own (setting software versions in experiment.xml and Manifest.mf).

abort(machine: str | Machine | None = None) → None[source]

If this experiment is running, abort it, stopping it immediately.

Requires and takes exclusive Controller access on the machine.

Raises:

NotRunningError – the experiment is not currently running

activeendtime: datetime | None

The actual end of the main part of the run, indicated by “Stage POSTRun” or an abort.

activestarttime: datetime | None

The actual beginning of the first stage of the run, defined as the first “Run Stage” message in the log after “Stage PRERUN”. This is not what AB’s software considers the start of a run.

property all_filters: Collection[FilterSet]

All filters used at some point in the experiment.

If the experiment has data, this is based on the existing data. Otherwise, it is based on the experiment protocol.

property calibrations: dict

Calibration data parsed from the EDS calibrations directory.

Returns a dict with keys ‘uniformity’, ‘background’, and optionally ‘puredye’.

change_plate_setup(new_plate_setup: PlateSetup | Mapping[str, str | list[str]] | None = None, machine: str | Machine | None = None) → None[source]

Replace the plate setup of this experiment on the machine, and locally.

This writes plate_setup.xml in the run’s folder in the machine’s experiments storage, whether the run is in progress, finished, or already collected. The other contents of the machine’s existing file are kept, and its plate type must match. The local copy is changed only after the machine’s file has been written. Direct SCPI requires the run folder to exist; HTTP file writes can create missing folders.

An EDS file that the machine has already collected is not changed. To change one, load it with from_file(), set plate_setup, and use save_file().

Parameters:
  • new_plate_setup – The new plate setup, or a mapping of sample names to wells. A mapping takes the plate type of the machine’s existing file, or of this experiment if there is none. If None, the experiment’s current plate_setup is written.

  • machine – The machine, by default the machine associated with the experiment.

change_protocol(new_protocol: Protocol, machine: str | Machine | None = None, force: bool = False) → None[source]

Apply a compatible protocol update to the running experiment.

Unless force is true, completed and active portions of the protocol must remain compatible with the current run position.

change_protocol_from_now(new_stages: Sequence[Stage], machine: str | Machine | None = None) → None[source]

End the current stage after this cycle, then run new_stages.

The active protocol’s default filters are retained. Use change_protocol() to change protocol-wide settings.

createdtime: datetime

The run creation time.

data_for_sample(sample: str) → DataFrame[source]

Convenience function to return data for a specific sample.

Finds wells using self.plate_setup.sample_wells[sample], then returns self.welldata.loc[:, wells]

Parameters:

sample (str) – sample name

Returns:

Slice of welldata. Will have multiple wells if sample is in multiple wells.

Return type:

pd.Dataframe

property filter_strings: list[str]

All filters, as x?-m? strings, used at some point in the experiment.

classmethod from_file(file: str | PathLike[str] | IO[bytes]) → Experiment[source]

Load an experiment from an EDS file.

Returns:

file – The filename or file handle to read.

Return type:

str or os.PathLike[str] or IO[bytes]

Raises:

ValueError – if the file does not appear to be an EDS file (lacks an experiment.xml).

classmethod from_machine(machine: str | Machine, name: str, *, include_images: bool | None = None) → Experiment[source]

Create an experiment from data on a machine, checking the running experiment if any, the machine’s public_run_complete storage, and the machine’s uncollected storage.

Parameters:
  • machine (Machine | str) – the machine to connect to, either as a Machine or a host name

  • name (str) – the name of the run

  • include_images – whether to copy acquisition images (TIFFs). By default (None), each source uses its own default: images are left out of running and uncollected runs (from_running(), from_uncollected()) and included from storage (from_machine_storage()).

Returns:

a copy of the experiment

Return type:

Experiment

classmethod from_machine_storage(machine: str | Machine, name: str, *, include_images: bool = True) → Experiment[source]

Create an experiment from the machine’s storage.

Parameters:
  • machine (Machine) – the machine to connect to.

  • name (str) – the name of the run to collect.

  • include_images – copy acquisition images (the TIFFs in apldbio/sds/images), as by default, so that the copy is complete. With False, they are left out. Over qslib-server, the image data is then not transferred; over direct SCPI, the whole EDS file is still read into memory, and the images are only left out locally.

Returns:

a copy of the experiment

Return type:

Experiment

classmethod from_running(machine: str | Machine, *, include_images: bool = False, method: Literal['files', 'zip'] = 'files') → Experiment[source]

Create an experiment from the one currently running on a machine.

Parameters:
  • machine (Machine) – the machine to connect to

  • include_images – also copy acquisition images (the TIFFs in apldbio/sds/images); by default they are left out. A running instrument may delete these while they are being read.

  • method – how to read the folder over SCPI. “files” copies the files as sync_from_machine() does, into the new experiment’s folder, leaving out any that the instrument deletes meanwhile. “zip” uses a single ZIPREAD?, which names only the other files when images are left out. It fails if a file is deleted while it is read and sends nothing while the instrument builds the archive. Over qslib-server, the files are always copied as by sync_from_machine().

Raises:

SyncIncompleteError – some files could not be copied; as for sync_from_machine()

Returns:

a copy of the running experiment

Return type:

Experiment

classmethod from_uncollected(machine: str | Machine, name: str, move: bool = False, *, include_images: bool = False, method: Literal['files', 'zip'] = 'zip') → Experiment[source]

Create an experiment from the uncollected (not yet compressed) storage.

Parameters:
  • machine (Machine) – the machine to connect to

  • name (str) – the name of the run to collect.

  • include_images – also copy acquisition images (the TIFFs in apldbio/sds/images); by default they are left out.

  • method – how to read the folder over SCPI: “zip” for a single ZIPREAD?, or “files” to copy the files as sync_from_machine() does, into the new experiment’s folder. When images are left out, “zip” lists the folder first and names only the other files, so that the instrument does not read the images. Over qslib-server, the images are downloaded one by one, uncompressed. For a long transfer, sync_from_machine() reports progress and can continue after an interruption.

Returns:

a copy of the experiment

Return type:

Experiment

get_status(machine: str | Machine | None = None) → RunStatus[source]

Return the status of the experiment, if currently running.

Requires Observer access on the machine.

Raises:

NotRunningError – the experiment is not currently running

info(format: str = 'markdown', plate: str = 'list') → str[source]

Generate a summary of the experiment, with some formatting configuation. str() uses this with default parameters.

Parameters:
  • format ("markdown" or "org", optional) – Format of output, currently “markdown” or “org”, and currently matters only when plate is “table”. By default “markdown”. If an unknown value, passed as tablefmt to tabulate.

  • plate ("list" or "table", optional) – Format of plate information. “list” gives a list of samples, “table” outputs a plate layout table (possibly quite wide). By default “list”.

Returns:

Summary

Return type:

str

info_html() → str[source]

Create a self-contained HTML summary (returned as a string, but very large) of the experiment.

classmethod latest_from_machine(machine: str | Machine, *, include_images: bool | None = None) → Experiment[source]

Load the currently running experiment if there is one, or the most recently modified run in the machine’s storage.

Parameters:
  • machine (Machine | str) – the machine to connect to

  • include_images – whether to copy acquisition images (TIFFs). By default (None), they are left out of a running experiment and included from storage, as in from_running() and from_machine_storage().

Returns:

a copy of the experiment

Return type:

Experiment

modifiedtime: datetime

The last modification time. QSLib sets this on write. AB D&A may not.

name: str

Experiment name, also used as file name on the machine.

property num_zones: int

The number of temperature zones (excluding cover), or -1 if not known.

pause_now(machine: str | Machine | None = None) → None[source]

If this experiment is running, pause it (immediately).

Requires and takes exclusive Controller access on the machine.

Raises:

NotRunningError – the experiment is not currently running

plate_setup: PlateSetup

Plate setup for the experiment.

plot_anneal_melt(samples: str | Sequence[str] | None = None, filters: str | FilterSet | Collection[str | FilterSet] | None = None, anneal_stages: int | Sequence[int] | None = None, melt_stages: int | Sequence[int] | None = None, between_stages: int | Sequence[int] | None = None, process: Sequence[PolarsProcessor] | PolarsProcessor | None = None, normalization: PolarsProcessor | None = None, ax: Axes | None = None, marker: str | None = None, legend: bool | Literal['inset', 'right'] = True, figure_kw: dict[str, Any] | None = None, line_kw: dict[str, Any] | None = None) → Axes[source]

Plots anneal/melt curves.

This uses solid lines for the anneal, dashed lines for the melt, and dotted lines for anything “between” the anneal and melt (for example, a temperature hold).

Line labels are intended to provide full information when read in combination with the axes title. They will only include information that does not apply to all lines. For example, if every line is from the same filter set, but different samples, then only the sample will be shown. If every line is from the same sample, but different filter sets, then only the filter set will be shown. Wells are shown if a sample has multiple wells.

Parameters:
  • samples – A reference to a single sample (a string), a list of sample names, or a Python regular expression as a string, matching sample names (full start-to-end matches only). Well names may also be included, in which case each well will be treated without regard to the sample name that may refer to it. Note this means you cannot give your samples names that correspond with well references. If not provided, all (named) samples will be included.

  • filters – Optional. A filterset (string or FilterSet) or list of filtersets to include in the plot. Multiple filtersets will be plotted on the same axes. Optional; if None, then all filtersets with data in the experiment will be included.

  • anneal_stages (int | Sequence[int] | None) – Optional. A stage or list of stages (integers, starting from 1), corresponding to the anneal, melt, and stages between the anneal and melt (if any). Any of these may be None, in which case the function will try to determine the correct values automatically.

  • melt_stages (int | Sequence[int] | None) – Optional. A stage or list of stages (integers, starting from 1), corresponding to the anneal, melt, and stages between the anneal and melt (if any). Any of these may be None, in which case the function will try to determine the correct values automatically.

  • between_stages (int | Sequence[int] | None) – Optional. A stage or list of stages (integers, starting from 1), corresponding to the anneal, melt, and stages between the anneal and melt (if any). Any of these may be None, in which case the function will try to determine the correct values automatically.

  • normalization – Optional. A Normalizer instance to apply to the data. By default, this is NormRaw, which passes through raw fluorescence values. NormToMeanPerWell also works well.

  • ax – Optional. An axes to put the plot on. If not provided, the function will create a new figure, by default with constrained_layout=True, though this can be modified with figure_kw.

  • marker – The marker format for data points, or None for no markers (default).

  • legend – Whether to add a legend. True (default) decides whether to have the legend as an inset or to the right of the axes based on the number of lines. “inset” and “right” specify the positioning. Note that for “right”, you must use some method to adjust the axes positioning: constrained_layout, tight_layout, or manually reducing the axes width are all options.

  • figure_kw – Optional. A dictionary of options passed through as keyword options to the figure creation. Only applies if ax is None.

  • line_kw – Optional. A dictionary of keywords passed to all three plotting commands.

Returns:

The axes object of the plot.

Return type:

Axes

plot_over_time(samples: str | Sequence[str] | None = None, filters: str | FilterSet | Collection[str | FilterSet] | None = None, stages: slice | int | Sequence[int] = slice(None, None, None), process: Sequence[PolarsProcessor] | PolarsProcessor | None = None, normalization: PolarsProcessor | None = None, ax: 'Axes' | 'Sequence[Axes]' | None = None, legend: bool | Literal['inset', 'right'] = True, temperatures: Literal[False, 'axes', 'inset', 'twin'] = 'axes', marker: str | None = None, stage_lines: bool | Literal['fluorescence', 'temperature'] = True, annotate_stage_lines: bool | float | Literal['fluorescence', 'temperature'] | Tuple[Literal['fluorescence', 'temperature'], float] = True, annotate_events: bool = True, figure_kw: dict[str, Any] | None = None, line_kw: dict[str, Any] | None = None, time_units: Literal['h', 'm', 's'] = 'h') → Sequence[Axes][source]

Plots fluorescence over time, optionally with temperatures over time.

Line labels are intended to provide full information when read in combination with the axes title. They will only include information that does not apply to all lines. For example, if every line is from the same filter set, but different samples, then only the sample will be shown. If every line is from the same sample, but different filter sets, then only the filter set will be shown. Wells are shown if a sample has multiple wells.

Parameters:
  • samples – A reference to a single sample (a string), a list of sample names, or a Python regular expression as a string, matching sample names (full start-to-end matches only). Well names may also be included, in which case each well will be treated without regard to the sample name that may refer to it. Note this means you cannot give your samples names that correspond with well references. If not provided, all (named) samples will be included.

  • filters – Optional. A filterset (string or FilterSet) or list of filtersets to include in the plot. Multiple filtersets will be plotted on the same axes. Optional; if None, then all filtersets with data in the experiment will be included.

  • stages – Optional. A stage, list of stages, or slice (all using integers starting from 1), to include in the plot. By default, all stages are plotted. For example, to plot stage 2, use stages=2; to plot stages 2 and 4, use stages=[2, 4], to plot stages 3 through 15, use stages=slice(3, 16) (Python ranges are exclusive on the end). Note that is a slice, you can use None instead of a number to denote the beginning/end.

  • normalization – Optional. A Normalizer instance to apply to the data. By default, this is NormRaw, which passes through raw fluorescence values. NormToMeanPerWell also works well.

  • temperatures –

    Optional (default “axes”). Several alternatives for displaying temperatures. “axes” uses a separate axes (created if ax is not provided, otherwise ax must be a list of two axes).

    Temperatures are from Experiment.temperature, and are thus the temperatures as recorded during the run, not the set temperatures. Note that this has a very large number of data points, something that should be dealt with at some point.

  • ax – Optional. An axes to put the plot on. If not provided, the function will create a new figure, by default with constrained_layout=True, though this can be modified with figure_kw. If temperatures=”axes”, you must provide a list or tuple of two axes, the first for fluorescence, the second for temperature.

  • marker – The marker format for data points, or None for no markers (default).

  • legend – Whether to add a legend. True (default) decides whether to have the legend as an inset or to the right of the axes based on the number of lines. “inset” and “right” specify the positioning. Note that for “right”, you must use some method to adjust the axes positioning: constrained_layout, tight_layout, or manually reducing the axes width are all options.

  • stage_lines – Whether to include dotted vertical lines on transitions between stages. If “fluorescence” or “temperature”, include only on one of the two axes.

  • annotate_stage_lines – Whether to include text annotations for stage lines. Float parameter allows setting the minimum duration of stage, as a fraction of total plotted time, to annotate, in order to avoid overlapping annotations (default threshold is 0.05).

  • annotate_events – Whether to include annotations for events (drawer open/close, cover open/close).

  • figure_kw – Optional. A dictionary of options passed through as keyword options to the figure creation. Only applies if ax is None.

  • line_kw – Optional. A dictionary of keywords passed to fluorescence plot commands.

plot_protocol(ax: Axes | None = None) → Tuple[Axes, Tuple[List[Line2D], List[Line2D]]][source]

A plot of the temperature and data collection points in the experiment’s protocol.

plot_temperatures(*, sel: pl.Expr | None = None, times: tuple[float, float] | None = None, ax: Axes | None = None, stage_lines: bool = True, annotate_stage_lines: bool | float = True, annotate_events: bool = True, legend: bool = False, figure_kw: Mapping[str, Any] | None = None, line_kw: Mapping[str, Any] | None = None, time_units: Literal['h', 'm', 's'] = 'h', method: Literal['matplotlib', 'altair'] = 'matplotlib') → Axes[source]

Plot sample temperature readings.

Parameters:
  • sel – A selector for the temperature DataFrame. This is not necessarily easy to use; times is an easier alternative.

  • times – Constructs a selector to show temperatures for a time range (after activestarttime). sel should not be set. Time is measured in time_units.

  • time_units – The units of the time range, and units to plot. “h” for hours, “m” for minutes, “s” for seconds.

  • ax – Optional. An axes to put the plot on. If not provided, the function will create a new figure, by default with constrained_layout=True, though this can be modified with figure_kw.

  • stage_lines – Whether to include dotted vertical lines on transitions between stages.

  • annotate_stage_lines – Whether to include text annotations for stage lines. Float parameter allows setting the minimum duration of stage, as a fraction of total plotted time, to annotate, in order to avoid overlapping annotations (default threshold is 0.05).

  • annotate_events – Whether to include annotations for events (cover opening/closing, drawer opening/closing).

  • legend – Whether to add a legend.

  • figure_kw – Optional. A dictionary of options passed through as keyword options to the figure creation. Only applies if ax is None.

  • line_kw – Optional. A dictionary of keywords passed to plot commands.

  • method

protocol: Protocol

Temperature and reading protocol for the experiment.

property quant_data_from_tiffs_polars: DataFrame

Quant data computed from TIFF images + ROI calibration.

Produces the same DataFrame as quant_data_polars but always uses TIFF images rather than pre-computed .quant files.

property quant_data_polars: DataFrame

Raw quant data as a Polars DataFrame.

Uses pre-computed .quant files if available, otherwise falls back to computing from TIFF images + ROI calibration.

resume(machine: str | Machine | None = None) → None[source]

If this experiment is running, resume it.

Requires and takes exclusive Controller access on the machine.

Raises:

NotRunningError – the experiment is not currently running

property roi_calibration

ROI calibration data parsed from roi.ini.

run(machine: str | Machine | None = None, overwrite: Literal[True, False, 'incomplete'] = False, require_exclusive: bool = False, require_drawer_check: bool = True) → None[source]

Load the run onto a machine, and start it.

Parameters:
  • machine – The machine to run on, by default None, in which case the machine associated with the run (if any) is used.

  • overwrite (bool or "incomplete", optional) – Whether to overwrite files if a run with the same name already exists. If “incomplete”, only overwrite if the existing run is an incomplete folder (in the experiments: working directory). By default False.

  • require_exclusive (bool, optional) – Whether to require exclusive access to the machine, by default False.

  • require_drawer_check (bool, optional) – Whether to ensure the drawer is closed before starting. Note that a close command will be sent regardless of this setting. By default True.

Raises:
runendtime: datetime | None

The run end time as a datetime, taken from the log. This is the end of the run,

runstarttime: datetime | None

The run start time as a datetime. This is taken directly from the log, ignoring the software-set value and replacing it on save if possibe. It is defined as the moment the machine records “Run Starting” in its log, using its timestamp. This may be 3 minutes before the start of the protocol if the lamp needs to warm up. It should be the same value as defined by AB’s software.

Use activestarttime for a more accurate value.

None if the file has not been updated since the start of the run

runstate: Literal['INIT', 'RUNNING', 'COMPLETE', 'ABORTED', 'STOPPED', 'UNKNOWN']

Run state, possible values INIT, RUNNING, COMPLETE, ABORTED, STOPPED(?).

property runtitle_safe: str

Run name with “ “ replaced by “_”; raises ValueError if name has other problematic characters.

property sample_wells: _SampleWellsView

A dictionary of sample names to sample wells (convenience read/write access to the PlateSetup .

save_file(path_or_stream: str | PathLike[str] | BytesIO | IO[bytes] = '.', overwrite: bool = False, update_files: bool = True) → None[source]

Save an EDS file of the experiment. This should be readable by AB’s software, but makes no attempt to hide that it was written by QSLib, and contains some other information. By default, this will refuse to overwrite an existing file.

Parameters:
  • path_or_stream (str or os.PathLike[str] or io.BytesIO) – A filename, open binary IO, or directory. If a directory, the file will be saved with the name from Experiment.runtitle_safe.

  • overwrite (bool, optional) – If True, overwrite any existing file without warning. Defaults to False.

  • update_files (bool, optional) – If True (default), update files before saving. Use False if you don’t want qslib to touch the files, for example, if you have just loaded a run from the machine and don’t want qslib to change anything based on its interpretation.

stop(machine: str | Machine | None = None) → None[source]

If this experiment is running, stop it after the end of the current cycle.

Requires and takes exclusive Controller access on the machine.

Raises:

NotRunningError – the experiment is not currently running

sync_from_machine(machine: str | Machine | None = None, log_method: Literal['copy', 'eval'] = 'eval', include_images: bool = False, *, include_tiffs: bool | None = None, progress: Callable[[str, int, int | None], None] | None = None) → None[source]

Update this experiment from its run on the machine.

Only new and changed files are copied. Each is written to a temporary file and renamed into place when complete; over qslib-server, an interrupted download continues on the next sync. Copied files are recorded in a transfer receipt, .qslib-transfer.json in the experiment’s folder (the format is described in the qslib._transfer module). A file is skipped when the receipt records the size and modification time the machine now lists, and the local copy still has that size; for files not in the receipt, when the local file has the listed size and is at least as new.

If the machine has collected the run, so that its folder is no longer in experiments:, the files of the stored EDS file, as from_machine_storage() reads it, are copied over the local ones instead, and the receipt is removed. This raises ValueError if the stored run log does not begin with the local one, as for another run with the same name, and FileNotFoundError if the run is in neither place. The live protocol is read only while this run is the machine’s current run.

Parameters:
  • machine – the machine, by default the experiment’s machine

  • log_method – "eval" (the default) appends new data to messages.log after checking that the end of the local copy matches; "copy" copies it whole

  • include_images – also copy acquisition images (the TIFFs in apldbio/sds/images); by default they are left out

  • include_tiffs – deprecated name for include_images

  • progress – called as progress(path, done, total) with the path on the machine of the file being copied, the bytes copied so far in this sync, and the listed size of all files to be copied

Raises:

SyncIncompleteError – some files could not be copied. The others are copied, and the receipt saved, before this is raised. Files deleted on the machine before they could be copied are skipped with a warning instead.

property temperatures: DataFrame

A DataFrame of temperature readings, at one second resolution, during the experiment (and potentially slightly before and after, if included in the message log).

Columns (as multi-index):

(“time”, …)float

Time of temperature reading, for choices of “timestamp” (Unix timestamp in seconds), “seconds” (seconds since the active start of the run), or “hours”. The latter two may be negative, and may not be set if the run never became active.

(“sample”, …)float

Sample temperature for blocks 1, 2, …, 6, and average in “avg”.

(“block”, …)float

Block temperature for blocks 1, 2, …, 6, and average in “avg”.

(“other”, “cover”)float

Cover temperature

(“other”, “heatsink”)float

Heatsink temperature

property temperatures_polars: DataFrame

Long-format temperature log (one row per (timestamp, zone, kind)) with columns timestamp (float seconds since epoch), temperature, zone (1-indexed, null for heatsink/cover), kind (one of “sample”, “block”, “heatsink”, “cover”), and time (Datetime[ms, UTC]).

For the 0.14-era wide schema with one column per zone, use temperatures_polars_wide.

property temperatures_polars_wide: DataFrame

a single row per timestamp with one column per (kind, zone) — sample_1..N, heatsink, cover, block_1..N — and timestamp as Datetime[ms, UTC].

The default temperatures_polars is long-format (one row per zone × kind); use this accessor if you need the legacy wide shape.

Type:

Wide-format temperature log matching the 0.14 schema

property tiff_images: dict

Raw TIFF images as numpy arrays, keyed by (stage, cycle, step, point, filter_set, exposure_index).

Returns a dict mapping tuple keys to numpy uint16 arrays of shape (height, width).

property welldata: DataFrame

A DataFrame with fluorescence reading information.

Deprecated since version 0.14.0: Use filter_data instead.

Indices (multi-index) are (filter_set, stage, cycle, step, point), where filter_set is a string in familiar form (eg, “x1-m4”) and the rest are int.

Columns (as multi-index):

(“time”, …)float

Time of the data collection, taken from the .quant file. May differ for different filter sets. Options are “timestamp” (unix timestamp in seconds), “seconds”, and “hours” (the latter two from the active start of the run).

(well, option)float

Data for a well, with well formatted like “A05”. Options are “rt” (read temperature from .quant file), “st” (more stable temperature), and “fl” (fluorescence).

(“exposure”, “exposure”)float

Exposure time from filterdata.xml. Misleading, because it only refers to the longest exposure of multiple exposures.

writesoftware: str

A string describing the software and version used to write the file.

exception qslib.experiment.MachineBusyError(machine: dataclasses.InitVar[Machine], current: RunStatus)[source]

Bases: MachineError

The machine is busy.

exception qslib.experiment.MachineError(machine: dataclasses.InitVar[Machine])[source]

Bases: Exception

Base class for an error from a machine.

exception qslib.experiment.MachineInErrorError(machine: dataclasses.InitVar[Machine], current: RunStatus, errors: list[ErrorLogEntry])[source]

Bases: MachineError

The machine is in the Error state (its error count, ERRor?, is above zero), and qslib will not start a run on it until the state is cleared, normally by restarting the InstrumentServer.

errors holds the most recent Fatal entries of the instrument’s error log (at most 10), which explain the Error state, if they could be read.

exception qslib.experiment.NotRunningError(machine: dataclasses.InitVar[Machine], run: str, current: RunStatus)[source]

Bases: MachineError

The named experiment is not currently running.

exception qslib.experiment.SyncIncompleteError(name: str, failures: dict[str, Exception])[source]

Bases: Exception

Some files could not be copied by Experiment.sync_from_machine().

The files that were copied are kept and recorded in the transfer receipt, so that a later sync copies only the rest.

failures: dict[str, Exception]

The errors, by path on the machine.

qslib.experiment.format_error_log(errors: Sequence[ErrorLogEntry], indent: str = '  ') → str[source]

Format error log entries one per line, with local times.

Machines

exception qslib.machine.AlreadyCollectedError[source]

Bases: Exception

class qslib.machine.FileListInfo[source]

Bases: TypedDict

Information about a file when verbose=True

class qslib.machine.FilterDataFilename(filterset: 'FilterSet', stage: 'int', cycle: 'int', step: 'int', point: 'int')[source]

Bases: object

class qslib.machine.Machine(host: str, password: str | None = None, automatic: bool = True, max_access_level: AccessLevel | str = AccessLevel.Controller, port: int | None = None, ssl: bool | None = None, client_certificate_path: str | None = None, client_key_path: str | None = None, server_ca_file: str | None = None, tls_server_name: str | None = None, server_port: int | None = None, server_token: str | None = None, server_connect_timeout: int = 3, _initial_access_level: AccessLevel | str = AccessLevel.Observer, *, backend: Literal['scpi', 'qslib', 'auto'] = 'scpi')[source]

Bases: object

A QuantStudio connection.

See Direct and managed transports for the choice of backend, ports and TLS.

Parameters:
  • host (str) – Machine host name or IP address.

  • password (str | None) – InstrumentServer password for direct SCPI.

  • automatic (bool) – Open and close connections and manage access levels around calls.

  • max_access_level ("Observer", "Controller", "Administrator", or "Full") – Maximum direct-SCPI access; the initial level is Observer.

  • port (int | None) – Direct-SCPI port. The default is 7443 unless ssl=False.

  • ssl (bool | None) – Force TLS or plaintext. None selects from the port number.

  • client_certificate_path – PEM client certificate for direct TLS.

  • client_key_path – PEM client key, if separate from the certificate.

  • server_ca_file – CA bundle used to verify direct TLS.

  • tls_server_name – Expected direct-TLS certificate name.

  • backend – One of "scpi", "qslib", or "auto".

  • server_port (int | None) – qslib-server port. Defaults to 7500 for qslib and auto.

  • server_token (str | None) – qslib-server bearer token. It is omitted from asdict() unless passwords are requested.

  • server_connect_timeout – Seconds to wait for qslib-server to answer the probe that selects the transport. Other requests allow the instrument time to act.

abort_current_run() → None[source]

Abort the current run and wait for the instrument to confirm it.

The default command deadline is two minutes to allow InstrumentServer to clean up the run.

at_access(access_level: AccessLevel | str, exclusive: bool = False, stealth: bool = False) → Generator[Machine, None, None][source]

Temporarily set SCPI session access.

For qslib-server, ordinary access through Controller leaves the session unchanged. The server authorizes each request. Exclusive and stealth access require a SCPI session.

authenticate(password: str) → None[source]

Authenticate the current connection with an InstrumentServer password.

Raises:
  • AuthError – The instrument rejected the password.

  • ConnectionError – There is no current connection.

property backend: Literal['qslib', 'scpi']

The resolved backend for this Machine.

property block: tuple[bool, float]

Returns whether the block is currently temperature-controlled, and the current block temperature setting.

compile_eds(run_name: str) → None[source]

Take a finished run directory in experiments:, compile it into an EDS, and move it to public_run_complete:

connect() → None[source]

Connect using the selected backend.

property connected: bool

Whether or not there is a current connection to the machine.

Note that when using automatic connections, this will usually be False, because connections will only be active when running a command.

property connection: QSConnection

The QSConnection for the connection, or a ConnectionError.

cover_lower(check: bool = True, ensure_drawer: bool = True) → None[source]

Lower/engage the plate cover, closing the drawer if needed.

property cover_position: str

Return the cover position.

property current_run_name: str | None

Name of current run, or None if no run is active.

define_protocol(protocol: Protocol) → None[source]

Send a protocol to the machine. This is not related to a particular experiment. The name on the machine is set by the protocol.

Parameters:

protocol – protocol to send

Raises:

ValueError – if the protocol name contains characters the instrument cannot run (see qslib.protocol.check_runnable_protocol_name)

disconnect() → None[source]

Close the current connection, first returning its session to Observer access.

download_dir(remote_dir: str, dest_dir: str | Path, *, leaf: str = 'FILE', include_images: bool = True) → bool[source]

Download a directory using the qslib backend.

include_images is as for read_dir_files().

download_file(path: str, dest: str | Path, *, context: str | None = None, progress: Callable[[str, int, int | None], None] | None = None) → dict[str, Any][source]

Copy a file from the machine to a local path, replacing the local file only once the copy is complete.

Over HTTP, an interrupted download is continued by a later call, with qslib.server.ServerClient.download_file(). Over SCPI, the file is read whole with READ?.

Parameters:
  • path – path on the machine, as for read_file()

  • dest – local file to write

  • context – optional context for path

  • progress – called as progress(path, done, total) with the bytes received so far and the total, or None if unknown. Over SCPI it is called once, at the end.

Returns:

size, and over HTTP etag and mtime (None otherwise)

Return type:

dict

drawer_close(lower_cover: bool = True, check: bool = True) → None[source]

Close the machine drawer using the OPEN command. This will ensure proper cover/drawer operation. It will not check run status, and will open and close the drawer during runs and potentially during imaging.

By default, it will lower the cover automaticaly after closing, use lower_cover=False to not do so.

drawer_open() → None[source]

Open the machine drawer using the OPEN command. This will ensure proper cover/drawer operation. It will not check run status, and will open and close the drawer during runs and potentially during imaging.

property drawer_position: str

Return the drawer position from the DRAW? command.

ensure_server(binary: str | bytes | None = None, *, listen: str, remote_path: str = '/data/qslib-server', file_root: str = '/data/vendor/IS', unauthenticated_role: Literal['observer'] | None = None, extra_args: tuple[str, ...] = (), timeout: float = 5.0) → ServerClient[source]

Return a ready server, deploying it if needed using a SCPI Machine.

Deployment requires Controller access. The server_token is given the Controller role on the server. The server uses unencrypted HTTP (see qslib-server). The Machine’s password, if set, is passed to the server in its environment so that it can elevate its SCPI connection.

listen must be an IP address and port, and remote_path and file_root may contain only letters, digits and /._:-. A server process that runs from remote_path but does not answer is not replaced. timeout limits the wait for an existing server to become ready and for the new one to start; each health check during deployment waits up to 4 seconds. Deployment replaces <remote_path>.auth.toml (removing it when there is no token) and removes a legacy <remote_path>.token; both are restored if the deployment fails. Once started, deployment cannot be interrupted with Ctrl-C: it runs until the server is up or the previous files are restored.

errors(limit: int | None = 100) → list[ErrorLogEntry][source]

Return the instrument’s error log: the last limit errors and warnings published since the InstrumentServer started (all of them if limit is None), oldest first.

Entries with fatal set usually explain an instrument in the Error state. That state means the instrument’s error count (ERRor?) is above zero: the handlers that publish fatal entries raise it, but some failed self-tests raise it without one. It lasts until the InstrumentServer is restarted or the count is reset. The log is the one written to LOGS:error.log; older entries are kept in LOGS:errorhistory.log. Over direct SCPI the whole log is read from the instrument; with qslib-server, only the entries returned.

get_all_filterdata(run: str | None = None, as_list: bool = False) → Any[source]

Fetch all filterdata from the machine.

Returns a list of Rust PlateData objects (as_list=True) or a Polars DataFrame.

get_filterdata_one(ref: FilterDataFilename, *, run: str | None = None, return_files: Literal[True]) → tuple[Any, list[tuple[str, bytes]]][source]
get_filterdata_one(ref: FilterDataFilename, *, run: str | None = None, return_files: bool = False) → Any

Fetch a single filterdata reading from the machine.

Returns a Rust PlateData object with timestamp set from quant data.

get_plate_setup(run: str | None = None) → PlateSetup[source]

Read the plate setup of a run from its folder in the machine’s experiments storage.

Parameters:

run – The run name. If None, the current run is used.

Raises:

FileNotFoundError – The run has no plate_setup.xml.

get_running_protocol() → Protocol[source]

Return the protocol for the active run.

Raises:

ValueError – No run is currently active.

get_timing_profile(protocol: Protocol) → TimingProfile[source]

Query live ramp and optics timing for protocol.

The returned profile is tied to the block identity, protocol volume, and run mode. Verified bundled block defaults are used only when an optional optics configuration query is unavailable; live values always take precedence.

get_zone_count() → int[source]

Query the number of temperature control zones from the server.

Returns:

The number of zones (typically 6 for current QuantStudio instruments).

list_runs_in_storage(glob: str = '*', *, verbose: Literal[True]) → list[FileListInfo][source]
list_runs_in_storage(glob: str = '*', *, verbose: Literal[False] = False) → list[str]
list_runs_in_storage(glob: str = '*', *, verbose: bool = False) → list[str] | list[FileListInfo]

List runs in machine storage.

Returns:

run filenames. Retrieve with load_run_from_storage (to open as :any`Experiment`) or save_run_from_storage (to download and save it without opening.)

Return type:

list[str]

load_run_from_storage(path: str, *, include_images: bool = True) → Experiment[source]

Load a run from machine storage as an Experiment.

include_images is passed to qslib.Experiment.from_machine_storage(): acquisition images are included by default.

machine_status() → MachineStatus[source]

Return information on the status of the machine.

pause_current_run() → None[source]

Pause the current run now.

property power: bool

Get and set the machine’s operational power (lamp, etc) as a bool.

Setting this to False will not turn off the machine, just power down the lamp, temperature control, etc. It will do so even if there is currently a run.

read_dir_as_zip(path: str, leaf: str = 'FILE', *, files: Sequence[str] | None = None, timeout: float = 600.0) → ZipFile[source]

Read a directory on the machine as a ZIP file, using ZIPREAD?.

The instrument builds the whole archive before it replies, and the read fails if a file is deleted meanwhile. For the folder of a running experiment, read_dir_files() is more reliable.

Parameters:
  • path (str) – path on the machine

  • leaf (str, optional) – leaf to use, by default “FILE”

  • files – if given, only these files, as ‘/’-separated paths relative to path, are read; the instrument does not open the others. Names that are not in the directory are ignored. An empty list gives an empty archive.

  • timeout – seconds to wait for the reply

Returns:

the returned zip file

Return type:

zipfile.ZipFile

Raises:

FileNotFoundError – if the directory does not exist

read_dir_files(path: str, leaf: str = 'FILE', *, include_images: bool = True) → dict[str, bytes][source]

Read the files under a directory one by one, with read_files().

Parameters:
  • path (str) – path on the machine

  • leaf (str, optional) – leaf to use, by default “FILE”

  • include_images – if False, leave out the acquisition images in apldbio/sds/images.

Returns:

file contents by path relative to the directory. Hidden files are not listed, so they are left out, as are files deleted before they could be read.

Return type:

dict[str, bytes]

Raises:

FileNotFoundError – if the directory does not exist

read_file(path: str, context: str | None = None, leaf: str = 'FILE', encoding: Literal['base64', 'plain'] = 'base64') → bytes[source]

Read a file through the selected backend.

read_files(paths: Sequence[str], *, leaf: str = 'FILE', failures: dict[str, Exception] | None = None) → dict[str, bytes][source]

Read several files, and return their contents by path.

Files that no longer exist are left out of the result. Over SCPI, the READ? commands are sent in groups of READ_GROUP_SIZE before their replies are collected, which avoids a delay after every reply.

Without failures, any other error is raised. With it, each error is recorded there by path, and the files that were read are returned. A timeout or a lost connection stops the reading, and that error is recorded for every path not yet read.

restart_machine(*, force: bool = False, wait: bool = False, timeout: float = 180) → None[source]

Reboot the instrument’s computer over direct SCPI with Controller access.

Set force=True to allow rebooting during an active run. The current SCPI session closes after the reboot command, which may have no reply. Set wait=True to wait up to timeout seconds after sending the command for the instrument to answer a query on a fresh connection. A wait that expires raises TimeoutError. Reconnect explicitly before using a machine configured with automatic=False again.

Any qslib-server process running on the instrument stops during reboot.

With force=True during a run, what happens to the run is decided as described for restart_system().

restart_system(*, force: bool = False) → None[source]

Restart InstrumentServer and the Android framework and front-panel app.

This is refused while a run is active; set force=True to restart anyway. The SCPI session closes during the restart. To reboot the instrument’s computer, use restart_machine().

With force=True during a run, the InstrumentServer’s power-failure recovery, which runs when it starts, decides what happens to the run. If the run’s message log was written within the last hour, the run’s protocol is started again from the beginning of the saved stage and cycle. Otherwise, if the instrument’s computer has been up for more than 200 seconds (the InstrumentServer restarted without a reboot), the protocol is started again from the saved step, and the front-panel app restarted. Otherwise the run is marked Failed.

resume_current_run() → None[source]

Resume the current run.

run_command(command: str | SCPICommand, *, timeout: float | None = None) → str[source]

Run a SCPI command, and return the response as a string. Waits for OK, not just NEXT.

Parameters:
  • command (str) – command to run

  • timeout – seconds to wait for OK or an error. If omitted, the connection’s command-specific defaults apply.

Returns:

Response message (after “OK”, not including it)

Return type:

str

Raises:

CommandError – Received an Error response.

run_command_bytes(command: str | bytes | SCPICommand) → bytes[source]

Run an SCPI command, and return the response as bytes (undecoded). Returns after the command is processed (OK or NEXT), but potentially before it has completed (NEXT).

Parameters:

command – command to run

Returns:

Response message (after “OK” or “NEXT”, likely “” in latter case)

Return type:

bytes

Raises:

CommandError – Received

run_command_to_ack(command: str | SCPICommand) → None[source]

Run an SCPI command and wait for its acknowledgement.

This method expects NEXT from an asynchronous command. Use run_command() for synchronous commands such as AbortRun.

Parameters:

command – command to run

Raises:

CommandError – Received an Error response.

run_command_to_bytes(command: str | SCPICommand, *, timeout: float | None = None) → bytes[source]

Run an SCPI command, and return the response as bytes (undecoded). Waits for OK, not just NEXT.

Parameters:
  • command – command to run

  • timeout – seconds to wait for OK or an error. By default, the connection’s timeouts apply: normally 30 seconds for the first reply, then 10 minutes after NEXT. AbortRun allows two minutes for its first reply.

run_status() → RunStatus[source]

Return information on the status of any run.

save_run_from_storage(machine_path: str, download_path: str | IO[bytes], overwrite: bool = False) → None[source]

Download a file from run storage on the machine.

Parameters:
  • machine_path (str) – filename on the machine

  • download_path (str | IO[bytes]) – filename to download to, or an open file

  • overwrite (bool, optional) – if False and provided a filename rather than an open file, will not overwrite existing filies; by default False

property server: ServerClient

Return a client for the qslib-server endpoint.

set_plate_setup(plate_setup: PlateSetup | Mapping[str, str | list[str]], run: str | None = None, *, preserve_existing: bool = True) → None[source]

Write the plate setup of a run to its folder in the machine’s experiments storage.

Parameters:
  • plate_setup – The new plate setup, or a mapping of sample names to wells. The samples replace all samples in the existing file. A mapping takes the plate type of the existing file, or 96 wells if there is none.

  • run – The run name. If None, the current run is used.

  • preserve_existing – If True (default), and the run already has a plate_setup.xml, keep the other contents of that file and only replace the samples. The plate types must then match. If False, or if there is no existing file, a new file is written.

set_status_led(color: StatusLedColor | str, mode: StatusLedMode | str = 'on') → None[source]

Set the front-panel status LED.

This is the machine’s indicator light, not the optical excitation lamp.

Parameters:
  • color – One of red, green, blue, yellow, cyan, magenta, white A color name or StatusLedColor value (case-insensitive).

  • mode – “on” (solid, the default), “blink”, or “off” A mode name or StatusLedMode value.

Notes

Requires Controller access.

property status: RunStatus

Return the current status of the run.

property status_led: StatusLedState

Current color and mode of the front-panel status LED.

Reading returns a StatusLedState (.color is None when off). Setting accepts a color name or StatusLedColor value (solid on), or a (color, mode) tuple.

status_led_off() → None[source]

Turn the front-panel status LED off. Requires Controller access.

stop_current_run() → None[source]

Stop the current run at the end of its current cycle.

The instrument acknowledges StopRun at once, but replies only when the run has stopped. This returns once the instrument shows that the stop has been requested, or that no run is in progress, and raises CommandResponseError if neither happens within 30 seconds.

write_file(path: str, data: str | bytes) → None[source]

Write a file through the selected backend.

qslib.machine.READ_GROUP_SIZE = 64

Number of READ? commands that Machine.read_files() sends before collecting their replies. Several hundred sent at once have timed out.

exception qslib.machine.RunNotFinishedError[source]

Bases: Exception

qslib.machine.ZIPREAD_MAX_NAMES = 1000

Most file names that experiment downloads put in one ZIPREAD?. The instrument compares every file in the folder with every name, and writes each command, names and all, into the log of a run in progress.

qslib.machine.ZIPREAD_TIMEOUT = 600.0

Default wait in seconds for one ZIPREAD? reply. The instrument builds the whole archive before it replies.

Protocols

class qslib.protocol.CustomStep(body: Sequence[ProtoCommand], identifier: int | str | None = None, repeat: int = 1)[source]

Bases: ProtoCommand

A protocol step composed of SCPI/protocol commands.

class qslib.protocol.Exposure(settings: Sequence[Tuple[FilterSet, Sequence[int]]], state: str = 'HoldAndCollect')[source]

Bases: ProtoCommand

Modifies exposure settings.

class qslib.protocol.HACFILT(filters: Sequence[str | FilterSet], default_filters: Sequence[FilterSet] = NOTHING)[source]

Bases: ProtoCommand

Sets filters for HoldAndCollect .

class qslib.protocol.Hold(time: int | float | str | Quantity | None, increment: int | float | str | Quantity = <Quantity(0, 'second')>, incrementcycle: int = 2, incrementstep: int = 2)[source]

Bases: ProtoCommand

A protocol hold (for a time) command.

class qslib.protocol.HoldAndCollect(time: int | float | str | Quantity, increment: int | float | str | Quantity = <Quantity(0, 'second')>, incrementcycle: int = 2, incrementstep: int = 2, tiff: bool = False, quant: bool = True, pcr: bool = False)[source]

Bases: ProtoCommand

A protocol hold (for a time) and collect (set by HACFILT) command.

qslib.protocol.NZONES: int = 6

Default number of temperature control zones.

Current QuantStudio instruments have 6 zones. This is used when expanding a single temperature to a per-zone list. Query the actual count from the server with Machine.get_zone_count() (sends TBC:ControlZones?).

class qslib.protocol.ProtoCommand(*args: Any, **kwargs: Any)[source]

Bases: ABC

class qslib.protocol.Protocol(stages=NOTHING, name: str = NOTHING, volume: float = 50.0, runmode: str = 'standard', filters: Iterable[FilterSet | str] = NOTHING, covertemperature: float = 105.0, prerun: Sequence[SCPICommandLike] = NOTHING, postrun: Sequence[SCPICommandLike] = NOTHING, classname: str = 'Protocol')[source]

Bases: ProtoCommand

A run protocol for the QuantStudio. Protocols encapsulate the temperature and camera controls for an entire run. They are composed of Stage`s, which may repeat for a number of cycles, and the stages are in turn composed of Steps, which may be created for usual cases with :class:`Step, or from SCPI commands. Steps may repeat their contents as well, but this is not yet implemeted.

Parameters:
  • stages (Iterable[Stage]) – The stages of the protocol, likely Stage.

  • stage (_NumOrRefIndexer[Stage]) – A more convenient way of accessing the stages of the protocol, with numbering that matches the machine.

  • name (str | None) – A protocol name. If not set, a timestamp will be used, unlike AB’s uuid.

  • volume (float) – The sample volume, in µL.

  • runmode (str | None) – The run mode.

  • covertemperature (float (default 105.0)) – The cover temperature

  • filters (Sequence[str]) – A list of default filters that can be used by any collection commands that don’t specify their own.

  • prerun (Sequence[SCPICommand]) – Sets PRERUN. DO NOT USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING.

  • postrun (Sequence[SCPICommand]) – Sets POSTRUN. DO NOT USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING.

Notes

Protocol equality is based on functional attributes (stages, volume, runmode, filters, covertemperature, prerun, postrun) but excludes the name. This means two protocols with identical configurations but different names are considered equal.

property all_filters: Collection[FilterSet]

A list of all filters used at some point in the protocol.

property all_temperatures: ndarray

An array of temperature settings at all_times.

property all_times: ndarray

An array of all start and end times of each step, interleaved.

check_compatible(new: Protocol, status: RunStatus) → bool[source]

Checks compatibility for changing a running protocol to a new one.

Raises ValueError if incompatible, returns True if compatible.

Parameters:
  • new – New protocol.

  • status – Current run status.

Raises:

ValueError – Protocols are incompatible.

copy() → Protocol[source]

Returns a new copy (recursively) of the protocol.

property dataframe: DataFrame

A nominal DataFrame representation of the temperature protocol.

This is a simple view that assumes a fixed 1.6 °C/s ramp rate, as Stage.dataframe() does, and ignores Step.ramp_rate, the run mode, the volume and data collection time. It is useful for plotting the programmed protocol, but is not an estimate of instrument runtime. Use estimate_timeline() for InstrumentServer-compatible timing.

estimate_timeline(profile: TimingProfile, *, ramp_model: Literal['vendor', 'calibrated'] = 'vendor', initial_temperature: float = 25.0) → ProtocolTimeline[source]

Estimate ramp endpoints, holds, and optical acquisitions.

classmethod from_scpi_string(text: str) → Protocol[source]

Parse a Protocol from an SCPI command string.

info() → str[source]

Generate a (markdown) text protocol description.

plot_protocol(ax: plt.Axes | None = None) → Tuple[plt.Axes, Tuple[List[plt.Line2D], List[plt.Line2D]]][source]

A plot of the temperature and data collection points.

property stage: _NumOrRefIndexer[Stage]

A one-indexed view of Protocol.stages matching the machine’s stage numbering. Slices are inclusive, so protocol.stage[5:6] returns stages 5 and 6. Getting, setting, and appending stages are supported.

to_scpi_string() → str[source]

Serialize this protocol to an SCPI command string.

to_scpi_string_rust() → str[source]

Serialize this protocol to an SCPI string using the Rust implementation.

class qslib.protocol.Ramp(temperature: int | float | str | ~pint.registry.Quantity | ~typing.Sequence[int | float | str | ~pint.registry.Quantity], increment: int | float | str | ~pint.registry.Quantity | None = <Quantity(0.0, 'delta_degree_Celsius')>, incrementcycle: int = 2, incrementstep: int = 2, rate: float = 100.0, cover: int | float | str | ~pint.registry.Quantity | None = None)[source]

Bases: ProtoCommand

Ramps temperature to a new setting.

class qslib.protocol.Stage(steps: CustomStep | Sequence[CustomStep], repeat: int = 1, index: int | None = None, instrument_label: str | None = None, default_filters: Sequence[FilterSet] = ())[source]

Bases: ProtoCommand

A Stage in a protocol, composed of Step s with a possible repeat.

instrument_label is the stage’s label in the machine’s protocol format, and is normally left unset, in which case STAGE_<index> is used. qslib-server accepts only labels of 1 to 128 ASCII letters, digits, spaces and _-.(); Protocol.validate() warns about other labels.

dataframe(start_time: float = 0, previous_temperatures: list[float] | None = None) → DataFrame[source]

Create a dataframe of the steps in this stage.

This is a simple view that assumes a fixed 1.6 °C/s ramp rate, and ignores Step.ramp_rate, the run mode, the volume and data collection time. Use Protocol.estimate_timeline() for a fuller estimate.

Parameters:
  • start_time – The initial start time, in seconds, of the stage (before the ramp to the first step). Default is 0.

  • previous_temperatures – A list of temperatures at the end of the previous stage, to allow calculation of ramp time. If None, the ramp is assumed to take no time.

classmethod hold_at(temperature: float | str | Sequence[float], total_time: int | str | Quantity, step_time: int | str | Quantity | None = None, collect: bool | None = None, filters: Sequence[str | FilterSet] = ()) → Stage[source]

Hold at a temperature for a set amount of time, with steps of a configurable fixed time.

Parameters:
  • temperatures – The temperature or temperatures to hold. If not strings or quantities, the value/values are interpreted as °C.

  • total_time – Desired total time for the stage. If this is not a multiple of step_time, it may not be the actual total time for the stage. The function will emit a warning if the difference is more than 10%. If an integer, value is interpreted as seconds.

  • step_time – If None (default), the stage will have one step. Otherwise, it will have steps of this time. If an integer, value is interpreted as seconds.

  • collect – Whether or not each step should collect fluorescence data. If None (default), collects data if filters is explicitly set.

  • filters – A list of filters to collect. If empty, and collect is True, then each step will collect the default filters for the Protocol.

Returns:

The resulting Stage

Return type:

Stage

Raises:

ValueError – If step time is larger than total time.

classmethod hold_for(temperature: float | str | Sequence[float], total_time: int | str | Quantity, step_time: int | str | Quantity | None = None, collect: bool | None = None, filters: Sequence[str | FilterSet] = ()) → Stage

Hold at a temperature for a set amount of time, with steps of a configurable fixed time.

Parameters:
  • temperatures – The temperature or temperatures to hold. If not strings or quantities, the value/values are interpreted as °C.

  • total_time – Desired total time for the stage. If this is not a multiple of step_time, it may not be the actual total time for the stage. The function will emit a warning if the difference is more than 10%. If an integer, value is interpreted as seconds.

  • step_time – If None (default), the stage will have one step. Otherwise, it will have steps of this time. If an integer, value is interpreted as seconds.

  • collect – Whether or not each step should collect fluorescence data. If None (default), collects data if filters is explicitly set.

  • filters – A list of filters to collect. If empty, and collect is True, then each step will collect the default filters for the Protocol.

Returns:

The resulting Stage

Return type:

Stage

Raises:

ValueError – If step time is larger than total time.

classmethod stepped_ramp(from_temperature: float | str | Quantity | Sequence[float], to_temperature: float | str | Quantity | Sequence[float], total_time: int | str | Quantity, *, n_steps: int | None = None, temperature_step: float | str | Quantity | None = None, points_per_step: int = 1, collect: bool | None = None, filters: Sequence[str | FilterSet] = (), start_increment: bool = False) → Stage[source]

Hold at a series of temperatures, from one to another.

Parameters:
  • from_temperature – Initial temperature/s (inclusive). If None, uses the final temperature of the previous stage (FIXME: None is not currently handled).

  • to_temperature – Final temperature/s (inclusive).

  • total_time – Total time for the stage

  • n_steps – Number of steps. If None, uses 1.0 Δ°C steps, or, if doing a multi-temperature change, uses maximum step of 1.0 Δ°C. If n_steps is specified, it is the number of temperature steps to take. Normally, since there is an initial cycle of the starting temperatures, this means there will be n_steps + 1 cycles. If start_increment is True, and the initial cycle is already stepped away from the starting temperature, then there will be only n_steps cycles.

  • temperature_step – Step temperature change (optional). Must be None, or correctly match calculation, if n_steps is not None. If both this and n_steps are None, default is 1.0 Δ°C steps. If temperature step does not exactly fit range, it will be adjusted, with a warning if the change is more than 5%. Sign is ignored. If doing a multi-temperature change, then this is the maximum temperature step.

  • collect – Collect data? If None, collects data if filters is set explicitly.

  • filters – Filters to collect.

  • start_increment – If False (default), start at the from_temperature, holding there for the same hold time as every other temperature. If True, start one step away from the from_temperature. This is useful, for example, if the previous stage held at a particular temperature, and you now want to step away from that temperature. When True, note the remarks about n_steps above.

Returns:

The resulting stage.

Return type:

Stage

class qslib.protocol.Step(time: int | float | str | ~pint.registry.Quantity, temperature: int | float | str | ~pint.registry.Quantity | ~typing.Sequence[int | float | str | ~pint.registry.Quantity], collect: bool | None = None, temp_increment: int | float | str | ~pint.registry.Quantity = <Quantity(0.0, 'delta_degree_Celsius')>, temp_incrementcycle: int = 2, temp_incrementpoint: int | None = None, time_increment: int | float | str | ~pint.registry.Quantity = <Quantity(0, 'second')>, time_incrementcycle: int = 2, time_incrementpoint: int | None = None, filters: ~typing.Iterable[~qslib._qslib.FilterSet | str] = (), pcr: bool = False, quant: bool = True, tiff: bool = False, repeat: int = 1, ramp_rate=100.0, default_filters: ~typing.Sequence[~qslib._qslib.FilterSet] = ())[source]

Bases: CustomStep

A normal protocol step, of a hold and possible collection.

Parameters:
  • time (int) – The step time setting, in seconds.

  • temperature (float | Sequence[float]) – The temperature hold setting, either as a float (all zones the same) or a sequence (of correct length) of floats setting the temperature for each zone.

  • collect (bool | None) – Collect fluorescence data? If None (default), collect only if the Step has an explicit filters setting.

  • temp_increment (float) – Amount to increment all zone temperatures per cycle on and after temp_incrementcycle.

  • temp_incrementcycle (int (default 2)) – First cycle to start the increment changes. Note that the default in QSLib is 2, not 1 (as in AB’s software), so the first cycle uses temperature and the next uses temperature + temp_incrementcycle.

  • time_increment (float)

  • time_incrementcycle (int) – The same settings for time per cycle.

  • filters (Sequence[FilterSet | str] (default empty)) – A list of filter pairs to collect, either using qslib.data.FilterSet or a string like "x1-m4". If collect is True and this is empty, then the filters will be set by the Protocol.

  • ramp_rate (float (default 100.0)) – Percentage of the run-mode ramp rate to use. This is serialized as the InstrumentServer RAMP -rate option; it is not a temperature rate in degrees per second.

Notes

repeat is the machine’s step-level repeat. Avoid it for a collecting step: the instrument runs a repeated step inside its REPeat wrapper, which waits for each iteration to finish, so the temperature hold no longer overlaps acquisition and the step takes roughly twice as long as asked for. Use several steps instead.

duration_at_cycle_point(cycle: int, point: int = 1) → Quantity[source]

Durations of the step at cycle (from 1)

durations_at_cycle(cycle: int) → list[Quantity][source]

Duration of the step (excluding ramp) at cycle (from 1)

info_str(index: None | int = None, repeats: int = 1) → str[source]

String describing the step.

temperatures_at_cycle(cycle: int) → list[Quantity][source]

Temperatures of the step at cycle (from 1)

temperatures_at_cycle_point(cycle: int, point: int) → Quantity[source]

Temperatures of the step at cycle (from 1)

qslib.protocol.c

alias of Hold

qslib.protocol.check_runnable_protocol_name(name: str) → None[source]

Raise ValueError if the instrument cannot run a protocol with this name.

The instrument stores each protocol under a variable named after it, and reads number-like and boolean-like run arguments as numbers and booleans. Names must therefore contain only letters, digits, _ and -, must not start with -, must be at most 128 bytes long in UTF-8, must not be a number other than a plain whole number such as 123, and must not be true, false, yes, no, on or off in any case. This is the same check qslib-server applies.

Timing

InstrumentServer-compatible protocol runtime estimation.

The legacy qslib.protocol.Protocol.dataframe intentionally remains a simple nominal representation. This module models the verified vendor ramp formula, optical collection time, and optional instrument-specific empirical ramp corrections. No empirical calibration is bundled yet.

exception qslib.timing.CalibrationExtrapolationError[source]

Bases: TimingError

A transition lies outside the calibrated interpolation domain.

exception qslib.timing.CalibrationUnavailableError[source]

Bases: TimingError

Calibrated timing was requested without an exactly matching profile.

exception qslib.timing.MissingExposureError[source]

Bases: TimingError

Optical timing information is absent for a collected filter.

class qslib.timing.OpticsTiming(indexing_time: float | None = 0.6, file_access_time: float | None = 0.85, exposures: FilterSet | str, ~typing.Sequence[int | float]]=<factory>)[source]

Bases: object

Optical indexing, file-access, and exposure timings.

Exposure sequences are expressed in milliseconds and keyed by any filter representation accepted by FilterSet.fromstring().

collection_duration(filters: Iterable[FilterSet | str], *, exposures: Mapping[str, Sequence[int | float]] | None = None) → float[source]

Calculate a HoldAndCollect duration in seconds.

exposure_sequence(filter_set: FilterSet | str) → tuple[float, ...][source]

Return the configured exposure sequence in milliseconds.

exception qslib.timing.ProfileMismatchError[source]

Bases: TimingError

The timing profile does not describe the protocol run settings.

class qslib.timing.ProtocolTimeline(steps: DataFrame, acquisitions: DataFrame, total_duration: float)[source]

Bases: object

Estimated thermal steps, optical acquisitions, and total duration.

exception qslib.timing.TimingError[source]

Bases: ValueError

Base class for timing-profile and timeline errors.

class qslib.timing.TimingProfile(block_id: int, volume: float, run_mode: str, zone_count: int, up_rate: float, down_rate: float, optics: OpticsTiming, block_serial: str | None = None, provenance: str | Mapping[str, str] = 'vendor', calibration: EmpiricalCalibration | None = None)[source]

Bases: object

Timing inputs for one exact block, volume, and run mode.

classmethod for_block(block_id: int, volume: float, run_mode: str) → TimingProfile[source]

Create an offline vendor profile from verified bundled settings.

exception qslib.timing.UnsupportedTimingCommandError[source]

Bases: TimingError

A custom command can affect timing but cannot be modelled safely.

Plate setup

Code for handling plate setup.

class qslib.plate_setup.PlateSetup(sample_wells: 'Mapping[str, str | List[str]] | None' = None, samples: 'Iterable[Sample] | Mapping[str, Sample]' = (), plate_type: 'Literal[96, 384]' = 96) → 'None'[source]

Bases: object

classmethod from_array(array: ndarray) → PlateSetup[source]

Given an (8,12) or (16,24) array of sample names, create a PlateSetup. Interprets None, “None”, and “null” as empty wells.

classmethod from_picklist(picklist: 'PickList' | str, plate_name: str | None = None, labware: 'Labware' | None = None) → Self[source]

Create a PlateSetup from a Kithairon PickList.

Parameters:
  • picklist (PickList or str) – The picklist to read. If a string, it is treated as a path to a CSV picklist.

  • plate_name (str or None) – The destination plate that the PlateSetup is for. If None, and there is only one destination plate, that one is used. If there are multiple destination plates, the user must specify one.

  • labware (Labware or None) – The Kithairon labware to use. If None, the default labware is used.

Raises:

ValueError – If: - There is more than one destination plate and no plate_name is specified. - There are multiple sample names in a single well. - The destination plate is not a destination plate type in the Labware. - The destination plate shape is not 96 or 384 (taken from Labware)

classmethod from_xml_string(xml: str | bytes) → PlateSetup[source]

Create a PlateSetup from an XML string (or bytes).

Uses Rust XML parsing internally.

get_wells(samples_or_wells: str | Sequence[str]) → list[str][source]

Given a sample, well, or list of the two, returns the corresponding wells. Note that this relies on samples not having well-like names.

to_xml_string(existing_xml: str | None = None) → str[source]

Serialize this PlateSetup to an XML string.

If existing_xml is provided, the existing XML structure is preserved and only the sample data is updated. Otherwise a new XML structure is created.

Uses Rust XML handling internally.

Data and processors

Fluorescence data processors supporting both Polars and Pandas DataFrames.

This module provides processor classes that can work with either Polars or Pandas data without requiring the user to choose. The process() method automatically detects the input type and applies the appropriate implementation.

class qslib.processors.FilterDict[source]

Bases: TypedDict

class qslib.processors.NormRaw[source]

Bases: Processor

A Processor that takes no arguments and passes through raw fluorescence values.

ylabel(previous_label: str | None = None) → str[source]

Return a y-axis label describing this processor’s transformation.

class qslib.processors.NormToMaxPerWell(stage: slice | int | Sequence[int] | range | None = None, step: slice | int | Sequence[int] | range | None = None, cycle: slice | int | Sequence[int] | range | None = None, point: slice | int | Sequence[int] | range | None = None, *, expr: Expr | None = None, selection: Any | None = None)[source]

Bases: Processor

A Processor that divides the fluorescence reading for each (filterset, well) pair by the max value of that pair within a particular selection of data.

See NormToMeanPerWell for usage examples.

ylabel(previous_label: str | None = None) → str[source]

Return a y-axis label describing this processor’s transformation.

class qslib.processors.NormToMeanPerWell(stage: slice | int | Sequence[int] | range | None = None, step: slice | int | Sequence[int] | range | None = None, cycle: slice | int | Sequence[int] | range | None = None, point: slice | int | Sequence[int] | range | None = None, *, expr: Expr | None = None, selection: Any | None = None)[source]

Bases: Processor

A Processor that divides the fluorescence reading for each (filterset, well) pair by the mean value of that pair within a particular selection of data.

The easiest way to use this is to give a particular stage (all data in that stage will be used), or a stage and set of cycles (those cycles in that stage will be used). For example:

  • To normalize to the mean stage 8 values, use NormToMeanPerWell(stage=8).

  • To normalize to the first 5 cycles of stage 2, use

    NormToMeanPerWell(stage=2, cycle=range(1, 6)).

For Polars, use expr for custom filter expressions. For Pandas, use selection for arbitrary indexing.

ylabel(previous_label: str | None = None) → str[source]

Return a y-axis label describing this processor’s transformation.

qslib.processors.PandasProcessor

alias of Processor

qslib.processors.PolarsProcessor

alias of Processor

class qslib.processors.Processor[source]

Bases: object

Base class for fluorescence data processors.

Processors transform fluorescence data (normalization, smoothing, etc.) and work with both Polars and Pandas DataFrames automatically. The process() method detects the input type and applies the appropriate implementation.

For Pandas, there’s also process_scoped() for scope-aware processing.

process(data: LazyFrame) → LazyFrame[source]
process(data: DataFrame) → DataFrame

Process the data, auto-detecting whether it’s Polars or Pandas.

Parameters:

data (pl.LazyFrame, pl.DataFrame, or pd.DataFrame) – The fluorescence data to process.

Returns:

The processed data.

Return type:

Same type as input

process_scoped(data: pd.DataFrame, scope: ScopeType) → pd.DataFrame[source]

Process Pandas data only if scope matches this processor’s scope.

This is useful for writing scope-agnostic code, provided that you call this for every scope before using the data.

Parameters:
  • data (pd.DataFrame) – The fluorescence data to process.

  • scope ("all" or "limited") –

    • “all”: the entire welldata array.

    • ”limited”: all time points, but limited to the filter sets and samples being plotted.

Returns:

The processed data (or unchanged if scope doesn’t match).

Return type:

pd.DataFrame

abstractmethod ylabel(previous_label: str | None = None) → str[source]

Return a y-axis label describing this processor’s transformation.

class qslib.processors.SmoothEMWMean(com: float | None = None, span: float | None = None, halflife: float | str | timedelta | None = None, alpha: float | None = None, min_periods: int = 0, adjust: bool = True, ignore_na: bool = False)[source]

Bases: Processor

A Processor that smooths fluorescence readings using an exponentially weighted moving average (EWMA).

ylabel(previous_label: str | None = None) → str[source]

Return a y-axis label describing this processor’s transformation.

class qslib.processors.SmoothWindowMean(window: int, min_periods: int | None = None, center: bool = False, win_type: str | None = None, closed: str | None = None)[source]

Bases: Processor

A Processor that smooths fluorescence readings using a rolling window mean.

ylabel(previous_label: str | None = None) → str[source]

Return a y-axis label describing this processor’s transformation.

class qslib.processors.SubtractByMeanPerWell(stage: slice | int | Sequence[int] | range | None = None, step: slice | int | Sequence[int] | range | None = None, cycle: slice | int | Sequence[int] | range | None = None, point: slice | int | Sequence[int] | range | None = None, *, expr: Expr | None = None, selection: Any | None = None)[source]

Bases: Processor

A Processor that subtracts the fluorescence reading for each (filterset, well) pair by the mean value of that pair within a particular selection of data.

See NormToMeanPerWell for usage examples.

ylabel(previous_label: str | None = None) → str[source]

Return a y-axis label describing this processor’s transformation.

qslib.processors.match_expr(stage: int | Sequence[int] | range | None = None, cycle: int | Sequence[int] | range | None = None, step: int | Sequence[int] | range | None = None, point: int | Sequence[int] | range | None = None, expr: Expr | None = None) → Expr[source]

Build a Polars filter expression from stage/cycle/step/point constraints.

qslib.processors.match_expr_single(stage: int | None = None, cycle: int | None = None, step: int | None = None, point: int | None = None) → Expr[source]

Build a Polars filter expression for single values.

qslib.processors.norm_zero_to_one_per_well(zero_filter: FilterDict, one_filter: FilterDict) → Expr[source]

Create a Polars expression that normalizes fluorescence to a 0-1 range.

Parameters:
  • zero_filter (FilterDict) – Filter for data points to use as the “zero” baseline.

  • one_filter (FilterDict) – Filter for data points to use as the “one” level.

Returns:

Expression that computes normalized fluorescence.

Return type:

pl.Expr

qslib.processors.pandas_process(data: pd.DataFrame, processors: Sequence[Processor] | Processor, scope: ScopeType = 'limited', ylabel: str | None = None) → 'pd.DataFrame' | tuple['pd.DataFrame', str][source]

Apply processors to Pandas data.

Parameters:
  • data (pd.DataFrame) – The fluorescence data.

  • processors (Processor or list of Processors) – The processor(s) to apply.

  • scope ("all" or "limited") – The scope for process_scoped.

  • ylabel (str, optional) – If provided, return (data, updated_ylabel) tuple.

Returns:

Processed data, optionally with updated ylabel.

Return type:

pd.DataFrame or (pd.DataFrame, str)

qslib.processors.polars_process(data: LazyFrame, processors: Sequence[Processor] | Processor | Expr, ylabel: str | None = None) → LazyFrame | tuple[LazyFrame, str][source]

Apply processors to Polars data.

Parameters:
  • data (pl.LazyFrame) – The fluorescence data.

  • processors (Processor, list of Processors, or pl.Expr) – The processor(s) to apply.

  • ylabel (str, optional) – If provided, return (data, updated_ylabel) tuple.

Returns:

Processed data, optionally with updated ylabel.

Return type:

pl.LazyFrame or (pl.LazyFrame, str)

SCPI commands

SCPI Command class and parsing

exception qslib.scpi_commands.AccessGiven[source]

Bases: CommandError

Raised when access has already been given to another session.

exception qslib.scpi_commands.AccessLevelExceeded[source]

Bases: CommandError

Raised when the requested access level exceeds what is allowed.

class qslib.scpi_commands.ArgList(opts: dict[str, bool | int | float | str], args: list[bool | int | float | str])[source]

Bases: object

A representation of an SCPI list of options (-key=value) and arguments.

classmethod from_string(argument_string: str) → ArgList[source]

Parse an SCPI argument string.

exception qslib.scpi_commands.AuthError[source]

Bases: CommandError

Raised when authentication fails (wrong password).

exception qslib.scpi_commands.ExclusiveAccessGiven[source]

Bases: CommandError

Raised when another session holds exclusive access.

exception qslib.scpi_commands.InsufficientAccess[source]

Bases: CommandError

Raised when the current access level is insufficient for an operation.

exception qslib.scpi_commands.NoMatch[source]

Bases: CommandError

Raised when a file or pattern match finds no results.

class qslib.scpi_commands.SCPICommand(command: str, *args: str | int | float | number[Any] | Sequence[str | int | float | number[Any]] | Sequence[SCPICommand], comment: str | None = None, **kwargs: str | int | float | number[Any] | Sequence[str | int | float | number[Any]])[source]

Bases: SCPICommandLike

A representation of an SCPI Command.

classmethod from_scpicommand(com: SCPICommand) → SCPICommand[source]

Try to create the object from an SCPICommand.

classmethod from_string(command_string: str) → SCPICommand[source]

Parse (as SCPICommands) an SCPI command string.

specialize() → SCPICommandLike[source]

If possible, convert SCPICommand to QSLib classes for the command.

to_scpicommand(**kwargs: Any) → SCPICommand[source]

Convert the object to an SCPICommand

to_string() → str[source]

Create a usable command string, including terminal newline.

class qslib.scpi_commands.SCPICommandLike[source]

Bases: ABC

Abstract class for an object that can be converted from/to an SCPICommand.

abstractmethod classmethod from_scpicommand(com: SCPICommand) → T[source]

Try to create the object from an SCPICommand.

abstractmethod to_scpicommand(**kwargs: Any) → SCPICommand[source]

Convert the object to an SCPICommand

qslib.scpi_commands.quote_string_if_needed(s: str) → str[source]

Quote a string if it contains spaces, quotes, or newlines.

Strings with newlines are wrapped in <quote>…</quote> tags. Strings with spaces or quotation marks are wrapped in double quotes with escaped quotes. Other characters like $, {, } are not escaped.

qslib.scpi_commands.specialize_command_error(e: CommandError) → CommandError[source]

Re-raise a CommandError as a more specific subclass if possible.

HTTP client

Typed client for qslib-server’s optional /api/v1 HTTP API.

ServerClient wraps the Rust client that qs-monitor also uses.

class qslib.server.ServerClient(host: str, port: int = 7500, token: str | None = None, timeout: float = 30.0)[source]

Bases: object

Synchronous client for qslib-server API v1.

token is sent as a bearer token over HTTP, which is unencrypted (see qslib-server). Mutation methods raise ServerOutcomeUnknown unless a failed response explicitly proves whether the operation started. Retry an idempotent operation only with the exception’s idempotency_key.

Parameters:
  • host (str) – qslib-server host name or IP address.

  • port (int) – HTTP port.

  • token (str | None) – Optional bearer token.

  • timeout (float) – Default request timeout in seconds.

allows(template_key: str, *, group: str | None = None) → bool[source]

Return whether the entry document advertises a mutation template, checking group as a coarser key when the specific one is absent.

available() → bool[source]

Return whether the service reports ready.

capabilities() → dict[str, Any][source]

Return v1 capabilities. An unreachable server is not asked again for 30 seconds.

clear_capability_cache() → None[source]

Force the next capability or link request to contact the server.

current_run() → dict[str, Any][source]

Return the current run state.

delete_experiment(name: str) → None[source]

Delete a non-running working experiment.

delete_staged_package(name: str, etag: str) → None[source]

Delete a staged package only if its ETag still matches.

download_abs_file(abspath: str, dest: str | Path, **kwargs: Any) → dict[str, Any][source]

Download an absolute InstrumentServer path with download_file().

download_context_dir(context: str, path: str, dest_dir: str | Path, chunk_size: int = 1048576, *, exclude: Sequence[str] = ()) → int[source]

Atomically replace a local directory from a named-context archive.

download_dir(abspath: str, dest_dir: str | Path, chunk_size: int = 1048576, *, exclude: Sequence[str] = ()) → int[source]

Atomically replace a local directory from a server archive.

exclude lists ‘/’-separated paths relative to abspath to leave out, with everything under them. Servers that do not support this send them anyway, and they are left out when extracting.

The server sends the archive file by file as it builds it, so the client’s usual timeout applies to each read: a download that stalls for that long has lost its connection, and raises ServerError.

download_file(path: str, dest: str | Path, *, context: str = 'default', chunk_size: int = 1048576, timeout: float | None = None, progress: Callable[[str, int, int | None], None] | None = None) → dict[str, Any][source]

Download a named-context file to a local path, continuing an interrupted earlier download where possible.

Data is written to .<name>.part beside dest, and the server URL and ETag it came from to .<name>.part.json. A later call for the same URL requests only the rest, with Range and If-Range. If the partial data came from another URL, or the file has changed, the download starts over. Once the length matches the server’s, the file is renamed to dest. If the call fails, the partial file is kept for the next call.

progress, if given, is called as progress(path, done, total) with the bytes of this file received so far, counting any earlier partial data, and its size (None if unknown). chunk_size is accepted for compatibility and not used.

Returns:

size, etag (None if the server sent none) and mtime (seconds from Last-Modified, or None).

Return type:

dict

events(last_event_id: str | None = None) → Iterator[dict[str, Any]][source]

Yield SSE events, reconnecting with their opaque Last-Event-ID cursors. Each event is a dict with event, data and, if the server sent one, id.

experiment(name: str) → dict[str, Any][source]

Return one experiment resource.

get_abs_file(abspath: str, dest: str | Path | BinaryIO | None = None, chunk_size: int = 1048576, *, range_start: int | None = None) → bytes | None[source]

Download an absolute InstrumentServer path through its context.

get_eds(name: str) → bytes[source]

Download a completed EDS archive.

get_file(path: str, dest: str | Path | BinaryIO | None = None, chunk_size: int = 1048576, *, context: str = 'default', range_start: int | None = None) → bytes | None[source]

Download a named-context file to memory, a path, or a stream.

A path is replaced only once the whole file has arrived. chunk_size is accepted for compatibility and not used.

get_package(name: str) → tuple[bytes, str | None][source]

Return a staged package and its ETag.

get_running_protocol() → dict[str, Any][source]

Return the active protocol as SCPI.

Return whether the server’s entry document advertises a relation.

health() → dict[str, Any][source]

Return the unversioned readiness resource.

indicator_off() → None[source]

Turn off the status indicator.

instrument_errors(limit: int | None = 100) → list[dict[str, Any]][source]

Return the last limit entries of the instrument’s error log (all of them if limit is None), oldest first.

instrument_status() → dict[str, Any][source]

Return the current instrument status.

list_context_dir(context: str, path: str = '', *, pattern: str = '*', recursive: bool = False) → list[dict[str, Any]][source]

List a directory in a named file context.

list_dir(abspath: str, *, pattern: str = '*', recursive: bool = False) → list[dict[str, Any]][source]

List an absolute InstrumentServer directory.

list_experiments() → dict[str, Any][source]

Return staged and working experiments.

list_runs(location: str = 'working') → list[str][source]

List working or completed run names.

open_abs_file(abspath: str, *, buffer_size: int = 262144, timeout: float | None = None) → BinaryIO[source]

Open an absolute InstrumentServer path as a seekable, read-only file that fetches data with ranged requests as it is read.

This suits reading parts of a large file, such as selected members of a ZIP archive. Reads raise ServerError if the file changes on the server after it was opened.

open_file(path: str, *, context: str = 'default', buffer_size: int = 262144, timeout: float | None = None) → BinaryIO[source]

Open a named-context file for reading through ranged requests.

operation(operation_id: str) → dict[str, Any][source]

Return an operation owned by the current identity.

preflight_run(experiment: str, *, overwrite: bool | str = False) → None[source]

Check whether a run start would conflict with existing state.

put_abs_file(abspath: str, data: bytes) → None[source]

Write an absolute InstrumentServer path through its context.

put_file(path: str, data: bytes, *, context: str = 'default', etag: str | None = None) → None[source]

Atomically write a named-context file.

put_protocol(name: str, scpi: str, tcprotocol_xml: bytes, qsl_tcprotocol_xml: bytes) → dict[str, Any][source]

Replace the current run’s live and persisted protocol.

restart_instrument(*, idempotency_key: str | None = None, force: bool = False) → dict[str, Any][source]

Submit an idempotent instrument restart. The server refuses it while a run is active unless force is set.

run(name: str) → dict[str, Any][source]

Return one working/completed run resource.

run_action(name: str, action: str, *, idempotency_key: str | None = None) → dict[str, Any][source]

Submit an idempotent pause, resume, stop, or abort action.

scpi(command: str, access: str | None = None, timeout_ms: int | None = None) → str[source]

Run opt-in raw SCPI, limited by the token’s role and server policy.

set_block(enabled: bool, target_c: float | None = None) → None[source]

Enable or disable block control, optionally setting its target.

set_cover(position: str = 'down', *, verify: bool = True, ensure_drawer: bool = False) → None[source]

Lower the cover, optionally closing the drawer first.

set_drawer(position: str, *, lower_cover: bool = True, verify: bool = True) → None[source]

Open or close the drawer.

set_indicator(color: str, mode: str = 'on') → None[source]

Set the status indicator color and mode.

set_power(enabled: bool) → None[source]

Enable or disable operational power.

stage_package(name: str, package: bytes) → str[source]

Stage an experiment package and return its ETag.

start_run(experiment: str, package_etag: str, *, overwrite: bool | str = False, require_exclusive: bool = False, require_drawer_check: bool = True, idempotency_key: str | None = None) → dict[str, Any][source]

Submit an idempotent run start and return its operation resource.

supports(resource: str) → bool[source]

Return whether API v1 advertises a resource.

wait_operation(operation: str | dict[str, Any], timeout: float = 120.0) → dict[str, Any][source]

Wait for an operation’s terminal state, preferring the poll target the server supplied with the accepted operation.

A failed operation raises ServerError; an operation whose outcome cannot be determined raises ServerOutcomeUnknown.

exception qslib.server.ServerError(message: str, status: int | None = None, *, code: str | None = None, retryable: bool = False, outcome: str | None = None, request_id: str | None = None, details: Any | None = None)[source]

Bases: RuntimeError

A structured server, response, or transport error.

exception qslib.server.ServerOutcomeUnknown(message: str, state_query: str, *, status: int | None = None, code: str | None = None, retryable: bool = False, request_id: str | None = None, details: Any | None = None, idempotency_key: str | None = None)[source]

Bases: ServerError

A mutation may have reached the server; retry only with its key.

exception qslib.server.ServerUnavailable(message: str, status: int | None = None, *, code: str | None = None, retryable: bool = False, outcome: str | None = None, request_id: str | None = None, details: Any | None = None)[source]

Bases: ServerError

The qslib-server endpoint could not be reached.